Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><strong>Update</strong> (5/5/16): <a href="https://stackoverflow.com/a/18053642/1026023">patriques' answer</a> should be used instead, as it's both simpler and more reliable.</p> <hr> <p>Since the canvas isn't always styled relative to the entire page, the <code>canvas.offsetLeft/Top</code> 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 <code>div</code> element containing the canvas with a <code>position: relative</code> style applied. To account for this you need to loop through the chain of <code>offsetParent</code>s, beginning with the canvas element itself. This code works perfectly for me, tested in Firefox and Safari but should work for all. </p> <pre><code>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; </code></pre> <p>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</p> <pre><code>coords = canvas.relMouseCoords(event); canvasX = coords.x; canvasY = coords.y; </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload