我正在处理一个可以用来获取画布坐标的函数。 工作得很好,直到部分画布在屏幕上不可见。
当我使窗口变小,并滚动到右下角时,它似乎从画布的可见部分开始。如何解决此问题以获得正确的坐标?
这是我的代码:
function getMousePosition(event) {
var MX = new Number();
var MY = new Number();
if (event.x != undefined && event.y != undefined) {
MX = event.x;
MY = event.y;
}
else { // Firefox method to get the position
MX = event.clientX + document.body.scrollLeft +
document.documentElement.scrollLeft;
MY = event.clientY + document.body.scrollTop +
document.documentElement.scrollTop;
}
MX -= canvas.offsetLeft;
MY -= canvas.offsetTop;
alert("x: " + MX + " y: " + MY);
}
答案 0 :(得分:1)
这是我用来获取画布坐标的函数:
function getCanvasPos(el) {
var canvas = document.getElementById(el);
var _x = canvas.offsetLeft;
var _y = canvas.offsetTop;
while(canvas = canvas.offsetParent) {
_x += canvas.offsetLeft - canvas.scrollLeft;
_y += canvas.offsetTop - canvas.scrollTop;
}
return {
left : _x,
top : _y
}
};
...这里是鼠标坐标的功能
function mousePos(e) {
var mouseX = e.clientX - getCanvasPos(e.target).left + window.pageXOffset;
var mouseY = e.clientY - getCanvasPos(e.target).top + window.pageYOffset;
return {
x : mouseX,
y : mouseY
};
};
鼠标事件监听器看起来像这样:
canvas.addEventListener('mousemove', function(e){
console.log(canvas.mousePos(e).x);
});