【发布时间】: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()方法在调用时必须返回 以下算法的结果:
令 list 为在调用此方法的同一元素上调用
getClientRects()的结果。如果列表为空,则返回
DOMRect对象,其x、y、width和height成员为零。否则,返回一个
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;
};
【问题讨论】:
-
在 Firefox 中,有
x。我告诉过它在 Firefox 中有效。是的,我在 firebug 中检查了它,而不是查看文档 - 这可能是问题所在。 -
@torazaburo specification says there is
xproperty.
标签: javascript google-chrome getboundingclientrect