【问题标题】:In google chrome, getBoundingClientRect().x is undefined在谷歌浏览器中, getBoundingClientRect().x 未定义
【发布时间】:2014-11-27 11:24:16
【问题描述】:

我正在画布上执行绘图操作。在我看来,计算相对于画布左上角的光标位置的最佳方法是使用.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 中运行。 Test it.

然而,在 google chrome 中,我的调试行打印了这个:

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

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

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

来自规格:

getBoundingClientRect()

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

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

  2. 如果列表为空,则返回 DOMRect 对象,其 xywidthheight 成员为零。

  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;
};

【问题讨论】:

标签: javascript google-chrome getboundingclientrect


【解决方案1】:

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

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

因此,您只需将rect.xrect.y 更改为rect.leftrect.top

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-29
    相关资源
    最近更新 更多