I’m having trouble in getting the mouse position w.r.t canvas.
There are two cases:
1) If there is no div element surrounding the canvas 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 accounts for this difference?
You need a function to get the position of the canvas element:
And calculate the current position of the cursor relative to that:
The values of
offsetLeftandoffsetTopare relative tooffsetParent, which is yourdivnode. When you remove thedivthey’re relative to thebody, so there is no offset to subtract.Similary,
e.pageXande.pageYgive 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.layerXande.layerY. This is less reliable than the method above for two reasons: