3

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

2 Answers2

5

.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;
Ouroborus
  • 16,237
  • 4
  • 39
  • 62
0

Try this:

function getMousePos(canvas, e) {
  var rect = canvas.getBoundingClientRect();
  return {
    x: e.clientX - rect.left,
    y: e.clientY - rect.top
  };
}

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var coords = document.getElementById("mousecoords");

c.onmousemove = function(e) {
  var {
    x,
    y
  } = getMousePos(c, e);

  coords.innerHTML = x + "," + y;
  ctx.beginPath();
  ctx.arc(x, y, 2, 0, Math.PI * 2, true);
  ctx.fill();
};
<p>The mouse is at</p>
<p id="mousecoords"> "hello" </p>
<canvas id="myCanvas" width="500" height="500" style="border:1px solid #000000;"></canvas>

You need to use the getBoundingClientRect() API from your canvas to readjust your current coordinates to a relative-to-parent position.

Here is the full documentation:

https://developer.mozilla.org/es/docs/Web/API/Element/getBoundingClientRect

This API will return the location in client area coordinates, so if you just substract the clientX/Y from your event to this you will get it done.

Victor Molina
  • 2,353
  • 2
  • 19
  • 49