0

我正在尝试在画布上获取鼠标位置的坐标。但我得到的只是NaN,NaN

var canvasBg = document.getElementById('canvasBg');
var ctxBg = canvasBg.getContext('2d');

var mouseX;
var mouseY;

canvasBg.addEventListener('mousemove', mouseMoved, false);
canvasBg.addEventListener('click', mouseClicked, false);

function mouseMoved(e) {

mouseX = e.pageX - canvasBg.pageOffsetLeft;
mouseY = e.pageY - canvasBg.pageOffsetTop;
document.getElementById('mouseCoors').innerHTML = 'X: ' + mouseX + ' Y: ' + mouseY;

}

function mouseClicked(e) {

    alert( mouseX + "," + mouseY);

}
4

2 回答 2

0

你可以这样做更简单:

function mouseMoved(e) {
    mouseX = e.offsetX;
    mouseY = e.offsetY;
    document.getElementById('mouseCoors').innerHTML = 'X: ' + mouseX + ' Y: ' + mouseY;
}

function mouseClicked(e) {
    alert( e.offsetX + "," + e.offsetY);
}
于 2014-03-21T00:05:37.820 回答
0

这是另一个解决方案!

试试这个你的mouseMoved功能:

function mouseMoved(e) {
    mouseX = e.x - canvasBg.offsetLeft;
    mouseY = e.y - canvasBg.offsetTop;

    document.getElementById('mouseCoors').innerHTML = 'X: ' + mouseX + ' Y: ' + mouseY;
}

完整代码的实时预览:Fiddle

参考

于 2014-03-21T01:49:24.177 回答