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.
views:
1630answers:
3
+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
2009-07-11 19:37:03
How do you get the X and Y of the canvas dom element in a way that works accross all browsers?
Richard
2010-08-09 10:31:43
+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
2009-07-11 20:10:47
+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
2010-07-18 07:28:35