So … I created canvas element with jquery:
var canvasElement = $("<canvas id='map' width='" + CANVAS_WIDTH + "' height='" + CANVAS_HEIGHT + "'></canvas");
var canvas = canvasElement.get(0).getContext("2d");
canvasElement.appendTo('body');
And now i want to get mouse coordinates, but the next code doesn’t work:
canvasElement.onmousemove = mousemove;
function mousemove(evt) {
var mouseX = evt.pageX - canvasElement.offsetLeft;
var mouseY = evt.pageY - canvasElement.offsetTop;
alert(mouseX+":"+mouseY);
}
canvasElement.offsetLeft is not work, evt.pageX too… Help !
Those properties aren’t cross-browser.
I know of two solutions to get the canvas position :
another one : use a custom and complex code :
As there is a loop, you’d better store
canvas_position_xandcanvas_position_yand have them recomputed at each documentresizeinstead of at eachmousemove.Demonstration