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