I want to make a little painting app using canvas. So I need to find the mouse's position on the canvas.
A:
you can get it by
var element = document.getElementById(canvasId);
element.onmousemove = function(e) {
var xCoor = e.clientX;
var yCoor = e.clientY;
}
rob waminal
2010-07-13 05:05:59
Will this work in IE, or does IE still use window.event instead of passing the event to the first argument of the listener? edit - I guess IE lacks the canvas element anyway until version 9, but this should still probably support IE because of things like excanvas....
no
2010-07-13 05:12:23
This will give the coordinates relative to the browser window, still need to figure out if they are in the element using element.getBoundingClientRect()
Pullets Forever
2010-07-13 05:13:04
+1
A:
A good write up of the difficulty of this problem can be found here: http://www.quirksmode.org/js/events_properties.html
Using the technique that is described there you can find the mouses position in the document. Then you just check to see if it is inside the bounding box of your element, which you can find by calling element.getBoundingClientRect() which will return an object with the following properties: { bottom, height, left, right, top, width }. From there it is trivial to figure out if the even happened inside your element or not.
Pullets Forever
2010-07-13 05:08:55