为了获取鼠标在 canvas 中的相对位置,我们在这里创建了一个 getMousePos() 方法,在此方
法中根据鼠标的位置、canvas的位置以及页面的偏移量来计算出鼠标相对于canvas的位置。
效果
http://www.html5canvastutorials.com/advanced/html5-canvas-mouse-
coordinates/
代码
function writeMessage(canvas, message){ var context = canvas.getContext('2d');
context.clearRect(0, 0, canvas.width, canvas.height);
context.font = '18pt Calibri'; context.fillStyle = 'black'; context.fillText(message, 10, 25);
}
function getMousePos(canvas, evt){
// 获得 canvas 位置 var obj = canvas; var top = 0; var left = 0;
while (obj && obj.tagName != 'BODY') { top += obj.offsetTop; left += obj.offsetLeft; obj = obj.offsetParent;
}
// 返回鼠标相对位置
var mouseX = evt.clientX - left + window.pageXOffset; var mouseY = evt.clientY - top + window.pageYOffset; return { x: mouseX, y: mouseY
};
}
window.onload = function(){
var canvas = document.getElementById('myCanvas'); var context = canvas.getContext('2d');
canvas.addEventListener('mousemove', function(evt){ var mousePos = getMousePos(canvas, evt);
var message = "Mouse position: " + mousePos.x + "," + mousePos.y; writeMessage(canvas, message);
}, false);
};