Tom Tom - 5 months ago 17x
Javascript Question

How do I get the coordinates of a mouse click on a canvas element?

What's the simplest way to add a click event handler to a canvas element that will return the x and y coordinates of the click (relative to the canvas element)?

No legacy browser compatibility required, Safari, Opera and Firefox will do.


As described here:

var x;
var y;
if (e.pageX || e.pageY) { 
  x = e.pageX;
  y = e.pageY;
else { 
  x = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft; 
  y = e.clientY + document.body.scrollTop + document.documentElement.scrollTop; 
x -= gCanvasElement.offsetLeft;
y -= gCanvasElement.offsetTop;

Worked perfectly fine for me.