当不存在周围元素时在画布中跟踪鼠标位置 [英] Tracking mouse position in canvas when no surrounding element exists
问题描述
我无法在画布上获取鼠标位置.
I'm having trouble in getting the mouse position w.r.t canvas.
有两种情况:
1) 如果画布 div 周围没有 div 元素,那么我就能够获得鼠标位置.
1) If there is no div element surrounding the canvas div then I was able to get the mouse position.
2) 当画布被包裹在 div
中时,offsetLeft
和 offsetTop
不能按预期工作
2) When the canvas is wrapped in a div
then offsetLeft
and offsetTop
do not work as expected
造成这种差异的原因是什么?
What accounts for this difference?
推荐答案
您需要一个函数来获取 画布元素的位置:
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);
});
offsetLeft
和 offsetTop
的值是相对于 offsetParent
的,也就是你的 div
节点.当您删除 div
时,它们是相对于 body
的,因此没有要减去的偏移量.
The values of offsetLeft
and offsetTop
are relative to offsetParent
, which is your div
node. When you remove the div
they're relative to the body
, so there is no offset to subtract.
类似,e.pageX
和 e.pageY
给出光标相对于文档的位置.这就是为什么我们从这些值中减去画布的偏移量以获得真实位置.
Similary, e.pageX
and e.pageY
give 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.layerX
和e.layerY
的值.由于两个原因,这种方法不如上述方法可靠:
An alternative for positioned elements is to directly use the values of e.layerX
and e.layerY
. This is less reliable than the method above for two reasons:
- 当事件没有发生在定位元素内时,这些值也是相对于整个文档的
- 它们不属于任何标准
这篇关于当不存在周围元素时在画布中跟踪鼠标位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!