This question already has an answer here:
I have an HTML file with a <canvas>
element and I am trying to get the mouse coordinates in the click
event. I am using this code:
secondCanvas.addEventListener('click', function(e) {
console.log(e.pageX)
}, false);
When I click on the top left point I get in console 500~ number, not zero... what do I need to do to get the coordinates of the mouse on the canvas?
You should calculate the canvas mouse position by substracting the canvas element offset from the event offset (
e.pageX
ande.pageY
).Here's a link that explains how to get an element position in the dom, and the code should look like :
I use this code and it works perfectly for me. Once added, canvas mouse events have two new properties: canvasX, and canvasY which are properly mapped. Right after you obtained the canvas element, don't forget to call canvas.extendMouseEvents() and you're in business.
It's because you're getting page coordinates. I'm guessing you want the current mouse position within either one of your two canvases? Hopefully this will solve your problem:
http://www.html5canvastutorials.com/advanced/html5-canvas-mouse-coordinates/
Also this stackoverflow is similar to yours and might give you a better understanding: Tracking mouse position in canvas when no surrounding element exists
Solution by user: lwburk