Search code examples
javascripthtmlonmousemove

clientX and clientY are offset from reall coordinates


I can't understand why the clientX and clientY properties are offset to their real positions. Here is my code:

 <!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Hello World!</title>
    <!-- https://electronjs.org/docs/tutorial/security#csp-meta-tag -->
    <meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" />
  </head>
  <body>
   <p>The mouse is at</p><p id="mousecoords"> "hello" </p>
   <canvas id="myCanvas" width="500" height="500" style="border:1px solid #000000;"></canvas>
   <script>
    var c = document.getElementById("myCanvas");
    var ctx = c.getContext("2d");
    var coords = document.getElementById("mousecoords");
    c.onmousemove = function(event){
      
      var x = event.clientX;
      var y = event.clientY;
      coords.innerHTML= x + "," + y;
      ctx.beginPath();
      ctx.arc(x, y, 2, 0, Math.PI * 2, true);
      ctx.fill();
    };
    </script> 
  </body>
</html>

here is a screenshot of the issue. Any Ideas? enter image description here


Solution

  • .clientX and .clientY are provided relative to the "client area", the portion of the page you are currently viewing. You'll need to make adjustments to take into account the canvas element's position relative to the client area. Fortunately, you're also provided with .getBoundingClientRect() which provides an element's location and dimensions in client area coordinates.

    Putting this together, you can modify your .onmousemove code as in:

      var bounding = c.getBoundingClientRect();
      var x = event.clientX - bounding.left;
      var y = event.clientY - bounding.top;