Mouse events in IE with Google’s excanvas

With modern browsers, we can simply use the function addEventListener to add events to the new HTML5 <canvas> tag. This function does not exist in IE (yet, IE9 apparently has it). I started my code base from Operas examples, which looks like this:

canvas.addEventListener('mousedown', ev_canvas, false);
canvas.addEventListener('mousemove', ev_canvas, false);
canvas.addEventListener('mouseup',   ev_canvas, false);

Sadly Microsofts Internet Explorer does not support these functions. To remedy this, simply include Google’s Excanvas and use this:

// Attach the mousedown, mousemove and mouseup event listeners.
    if (canvas.addEventListener){
        canvas.addEventListener('mousedown', ev_canvas, false);
        canvas.addEventListener('mousemove', ev_canvas, false);
        canvas.addEventListener('mouseup',   ev_canvas, false);
    } else if (canvas.attachEvent){ // IE
        var trackend = false;
        var trackstart = false;
        var trackmid = false;
        canvas.onselectstart = function () {canvas.onmousemove();trackstart = true;return false;}
        canvas.onclick = function () {trackend = true;}
        canvas.onmousemove = function () {
            var mtarget = document.getElementById('Drawing');
            var x = event.clientX + mtarget.scrollLeft;
            var y = event.clientY + mtarget.scrollTop - 20;
            var mtype = 'mousemove';
            if (trackstart) {
                trackstart = false;
                trackmid = true;
                mtype = 'mousedown';
            }
            if (trackend) {
                trackmid = false;
                mtype = 'mouseup';
            }
            if (trackend || trackmid || trackstart) {
                trackend = false;
                ev_canvas({
                    type: mtype,
                    layerX: x,
                    layerY: y,
                    target: mtarget
                });
            }
        }
    }

You will have to change the ChangeMeToYourCanvasID to your canvas ID. The X and Y positions may change if you scroll the page, so I minused var x & y by scrollTop and scrollLeft. ev_canvas is the name of the handle function.

We can now use events exactly the same across all browsers.

One thought on “Mouse events in IE with Google’s excanvas

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>