0

我正在研究一个可以用来获取画布坐标的函数。效果很好,直到画布的一部分在屏幕上不可见。

当我使窗口变小并滚动到右下角时,它似乎是从画布的可见部分开始的。如何解决此问题以获得正确的坐标?

这是我的代码:

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);

}

4

1 回答 1

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);
});
于 2012-07-12T06:57:12.330 回答