You need a function to get the position of the canvas element:
function findPos(obj) {
var curleft = 0, curtop = 0;
if (obj.offsetParent) {
do {
curleft += obj.offsetLeft;
curtop += obj.offsetTop;
} while (obj = obj.offsetParent);
return { x: curleft, y: curtop };
}
return undefined;
}
And calculate the current position of the cursor relative to that:
$('#canvas').mousemove(function(e) {
var pos = findPos(this);
var x = e.pageX - pos.x;
var y = e.pageY - pos.y;
var coordinateDisplay = "x=" + x + ", y=" + y;
writeCoordinateDisplay(coordinateDisplay);
});
The values of offsetLeft
and offsetTop
are relative to offsetParent
, which is your div
node. When you remove the div
they're relative to the body
, so there is no offset to subtract.
Similary, e.pageX
and e.pageY
give the position of the cursor relative to the document. That's why we subtract the canvas's offset from those values to arrive at the true position.
An alternative for positioned elements is to directly use the values of e.layerX
and e.layerY
. This is less reliable than the method above for two reasons:
- These values are also relative to the entire document when the event does not take place inside a positioned element
- They are not part of any standard