I'm playing around with the HTML5 <canvas> element. One interesting thing to do is interact with the canvas using the mouse.

First we attach the mouse click event to the canvas (suppose we have an HTML page with a canvas element named canvas, and Game is a global "namespace object"):

Game.canvas = document.getElementById('canvas');
Game.canvas.addEventListener('click', on_canvas_click, false);

Now, in the event handler function, we can play with the event object. It has the clientX and clientY properties for finding out where the mouse was clicked, but these give imprecise results!

The reason for that is that the canvas itself isn't placed at 0,0 on the client area. Therefore, we have to subtract its offset from the event's coordinates, like this:

function on_canvas_click(ev) {
    var x = ev.clientX - Game.canvas.offsetLeft;
    var y = ev.clientY - Game.canvas.offsetTop;

    // ... x,y are the click coordinates relative to the
    // canvas itself

Edit (05.05.2010): If the window is scrolled (which is unlikely for a JS canvas application, but might happen in some cases) the method above will give wrong results. You'll have to adjust for the scroll with $(window).scrollTop() (or scrollLeft() for horizontal scrolling).


comments powered by Disqus