javascript 当不存在周围元素时在画布中跟踪鼠标位置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5085689/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 15:54:28  来源:igfitidea点击:

Tracking mouse position in canvas when no surrounding element exists

javascripthtmlcanvas

提问by dragonfly

I'm having trouble in getting the mouse position w.r.t canvas.

我无法在画布上获取鼠标位置。

There are two cases:

有两种情况:

1) If there is no div element surrounding the canvas divthen I was able to get the mouse position.

1) 如果画布 div 周围没有 div 元素,那么我就能够获得鼠标位置。

2) When the canvas is wrapped in a divthen offsetLeftand offsetTopdo not work as expected

2) 当画布被包裹在一个divthen 中offsetLeft并且offsetTop没有按预期工作时

What accounts for this difference?

造成这种差异的原因是什么?

回答by Wayne

You need a function to get the position of the canvas element:

您需要一个函数来获取画布元素位置

function findPos(obj) {
    var curleft = 0, curtop = 0;
    if (obj.offsetParent) {
        do {
            curleft += obj.offsetLeft;
            curtop += obj.offsetTop;
        } while (obj = obj.offsetParent);
        return { x: curleft, y: curtop };
    }
    return undefined;
}

And calculate the current position of the cursor relative to that:

并计算光标相对于该位置的当前位置:

$('#canvas').mousemove(function(e) {
    var pos = findPos(this);
    var x = e.pageX - pos.x;
    var y = e.pageY - pos.y;
    var coordinateDisplay = "x=" + x + ", y=" + y;
    writeCoordinateDisplay(coordinateDisplay);
});

The values of offsetLeftand offsetTopare relative to offsetParent, which is your divnode. When you remove the divthey're relative to the body, so there is no offset to subtract.

的值offsetLeftoffsetTop相对于offsetParent,这是你的div节点。当您删除div它们时,它们是相对于 的body,因此没有要减去的偏移量。

Similary, e.pageXand e.pageYgive the position of the cursor relative to the document. That's why we subtract the canvas's offset from those values to arrive at the true position.

类似地,e.pageXe.pageY给出光标相对于文档的位置。这就是为什么我们从这些值中减去画布的偏移量以获得真实位置的原因。

An alternative for positionedelements is to directly use the values of e.layerXand e.layerY. This is less reliable than the method above for two reasons:

一种替代定位元件是直接使用的值e.layerXe.layerY。由于两个原因,这不如上述方法可靠:

  1. These values are also relative to the entire document when the event does not take place inside a positioned element
  2. They are not part of any standard
  1. 当事件不在定位元素内发生时,这些值也相对于整个文档
  2. 它们不属于任何标准