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
Update (5/5/16): patriques' answer should be used instead, as it's both simpler and more reliable.
Since the canvas isn't always styled relative to the entire page, the canvas.offsetLeft/Top
doesn't always return what you need. It will return the number of pixels it is offset relative to its offsetParent element, which can be something like a div
element containing the canvas with a position: relative
style applied. To account for this you need to loop through the chain of offsetParent
s, beginning with the canvas element itself. This code works perfectly for me, tested in Firefox and Safari but should work for all.
function relMouseCoords(event){
var totalOffsetX = 0;
var totalOffsetY = 0;
var canvasX = 0;
var canvasY = 0;
var currentElement = this;
do{
totalOffsetX += currentElement.offsetLeft - currentElement.scrollLeft;
totalOffsetY += currentElement.offsetTop - currentElement.scrollTop;
}
while(currentElement = currentElement.offsetParent)
canvasX = event.pageX - totalOffsetX;
canvasY = event.pageY - totalOffsetY;
return {x:canvasX, y:canvasY}
}
HTMLCanvasElement.prototype.relMouseCoords = relMouseCoords;
The last line makes things convenient for getting the mouse coordinates relative to a canvas element. All that's needed to get the useful coordinates is
coords = canvas.relMouseCoords(event);
canvasX = coords.x;
canvasY = coords.y;