Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You need a function to get the <a href="http://www.quirksmode.org/js/findpos.html" rel="noreferrer">position of the canvas element</a>:</p> <pre><code>function findPos(obj) { var curleft = 0, curtop = 0; if (obj.offsetParent) { do { curleft += obj.offsetLeft; curtop += obj.offsetTop; } while (obj = obj.offsetParent); return { x: curleft, y: curtop }; } return undefined; } </code></pre> <p>And calculate the current position of the cursor relative to that:</p> <pre><code>$('#canvas').mousemove(function(e) { var pos = findPos(this); var x = e.pageX - pos.x; var y = e.pageY - pos.y; var coordinateDisplay = "x=" + x + ", y=" + y; writeCoordinateDisplay(coordinateDisplay); }); </code></pre> <p>The values of <code>offsetLeft</code> and <code>offsetTop</code> are relative to <code>offsetParent</code>, which is your <code>div</code> node. When you remove the <code>div</code> they're relative to the <code>body</code>, so there is no offset to subtract.</p> <p>Similary, <code>e.pageX</code> and <code>e.pageY</code> give 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.</p> <p>An alternative for <em>positioned</em> elements is to directly use the values of <code>e.layerX</code> and <code>e.layerY</code>. This is less reliable than the method above for two reasons:</p> <ol> <li>These values are also relative to the entire document when the event does not take place inside a positioned element</li> <li>They are not part of any standard</li> </ol>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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