本文介绍了在谷歌浏览器中,getBoundingClientRect()。x是未定义的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  HTMLCanvasElement.prototype.relativeCoords = function(event){
var x,y;
//这是画布的当前屏幕矩形
var rect = this.getBoundingClientRect();

//将鼠标偏移量重新计算为相对偏移量
x = event.clientX - rect.x;
y = event.clientY - rect.y;
// Debug
console.log(x(,x,)= event.clientX(,event.clientX,) - rect.x(,rect.x,) );
//返回数组
return [x,y];
}

我看到这段代码没有错,它在firefox中有效。 。



在google但是,我的调试行显示了这个:

我做错了什么?



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



根据规格说明:





What am I doing wrong?

Edit: seems my code follows W3C:

From the specs:

getBoundingClientRect()

DOMRect

interface DOMRect : DOMRectReadOnly {
    inherit attribute unrestricted double x;
    inherit attribute unrestricted double y;
    inherit attribute unrestricted double width;
    inherit attribute unrestricted double height;
};
解决方案

The object returned by getBoundingClientRect() may have x and y properties in some browsers, but not all. It always has left, top, right, and bottom properties.

I recommend using the MDN docs instead of any W3C specs when you want to know what browsers actually implement. See the MDN docs for getBoundingClientRect() for more accurate information on this function.

So all you need to do is change your rect.x and rect.y to rect.left and rect.top.

这篇关于在谷歌浏览器中,getBoundingClientRect()。x是未定义的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 22:27