views:

1630

answers:

3

Is there a way to get the location mouse inside a <canvas> tag? I want the location relative to to the upper right corner of the <canvas>, not the entire page.

+1  A: 

Subtract the X and Y offsets of the canvas DOM element from the mouse position to get the local position inside the canvas.

Soviut
How do you get the X and Y of the canvas dom element in a way that works accross all browsers?
Richard
+2  A: 

Easiest way is probably to add a onmousemove event listener to the canvas element, and then you can get the coordinates relative to the canvas from the event itself.

This is trivial to accomplish if you only need to support specific browsers, but there are differences between f.ex. Opera and Firefox.

Something like this should work for those two:

function mouseMove(e)
{
    var mouseX, mouseY;

    if(e.offsetX) {
        mouseX = e.offsetX;
        mouseY = e.offsetY;
    }
    else if(e.layerX) {
        mouseX = e.layerX;
        mouseY = e.layerY;
    }

    /* do something with mouseX/mouseY */
}
Jani Hartikainen
I'd highly recommend using JQuery or some other javascript framework that standardizes offsets.
Soviut
This only worked for me if I set the canvas position to be relative as suggested By Nat.
Richard
+1  A: 

Also note that you'll need CSS:

position: relative;

set to your canvas tag, in order to get the relative mouse position inside the canvas.

Nat