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 cursor position relative to this:
$('#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 offsetLeft and offsetTop refer to offsetParent , which is your div node. When you delete a div , they refer to the body , so there is no bias.
Similary, e.pageX and e.pageY indicate the position of the cursor relative to the document. Therefore, we subtract the canvas offset from these values ββin order to reach the true position.
An alternative for positioned elements is to directly use the e.layerX and e.layerY . This is less reliable than the method above for two reasons:
- These values ββalso apply to the entire document when an event does not occur inside a positioned element.
- They are not part of the standard.
Wayne Burkett Feb 23 2018-11-11T00: 00Z
source share