19

我正在画布上执行绘图操作。在我看来,计算相对于画布左上角的光标位置的最佳方法是使用.getBoundingClientRect()

HTMLCanvasElement.prototype.relativeCoords = function(event) {
  var x,y;
  //This is the current screen rectangle of canvas
  var rect = this.getBoundingClientRect();

  //Recalculate mouse offsets to relative offsets
  x = event.clientX - rect.x;
  y = event.clientY - rect.y;
  //Debug
  console.log("x(",x,") = event.clientX(",event.clientX,") - rect.x(",rect.x,")");
  //Return as array
  return [x,y];
}

我看不出这段代码有什么问题,它可以在 Firefox 中运行。测试一下。

然而,在谷歌浏览器中,我的调试行打印了这个:

x( NaN) = event.clientX( 166) - rect.x( undefined)

我究竟做错了什么?这不符合规范吗?

编辑:似乎我的代码遵循 W3C:

从规格:

getBoundingClientRect()

getBoundingClientRect()方法在调用时必须返回以下算法的结果:

  1. 让 list 成为调用getClientRects()此方法的同一元素的结果。

  2. 如果列表为空,则返回其 、DOMRectx成员为零的对象。ywidthheight

  3. 否则,返回一个DOMRect描述最小矩形的对象,该对象包括列表中的第一个矩形和所有剩余的高度或宽度不为零的矩形。

DOMRect

interface DOMRect : DOMRectReadOnly {
    inherit attribute unrestricted double x;
    inherit attribute unrestricted double y;
    inherit attribute unrestricted double width;
    inherit attribute unrestricted double height;
};
4

1 回答 1

33

返回的对象在某些浏览器中getBoundingClientRect()可能具有xy属性,但不是全部。它始终具有lefttoprightbottom属性。

当您想知道浏览器实际实现了什么时,我建议您使用MDN 文档而不是任何 W3C 规范。有关此函数的更准确信息,请参阅getBoundingClientRect() 的 MDN 文档。

因此,您需要做的就是将rect.xand更改rect.yrect.leftand rect.top

于 2015-04-20T07:44:43.923 回答