clientX 和 clientY 与实际坐标有偏移

clientX and clientY are offset from reall coordinates

我不明白为什么 clientX 和 clientY 属性偏移到它们的实际位置。 这是我的代码:

 <!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>

这是问题的屏幕截图。有任何想法吗?

试试这个:

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>

您需要使用 canvas 中的 getBoundingClientRect() API 将当前坐标重新调整到 relative-to-parent 位置。

这里是完整的文档:

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

此 API 将 return 客户区坐标中的位置,因此,如果您只需将 clientX/Y 从您的事件中减去,您就可以完成。

.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() 提供元素在客户区坐标中的位置和尺寸。

综合起来,您可以修改 .onmousemove 代码,如下所示:

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