Track mouse position in canvas when no surrounding element exists

I'm having problems getting wrt canvas mouse position.

There are two cases:

1) If there is a div element surrounding a div div , then I was able to get the mouse position.

2) When the canvas is wrapped in a div , then offsetLeft and offsetTop do not work as expected

What explains this difference?

+18
javascript html5 canvas
Feb 23 2018-11-11T00:
source share
1 answer

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.
+28
Feb 23 2018-11-11T00:
source share



All Articles