我的坐标是NaN,NaN

时间:2014-03-21 00:03:39

标签: javascript nan mouse-position

我试图将我的鼠标位置放在画布上。但我回来的只有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);

}

2 个答案:

答案 0 :(得分: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);
}

答案 1 :(得分:0)

这是另一种解决方案!

尝试使用mouseMoved功能:

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

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

完整代码的实时预览:Fiddle

Reference