首先,我知道这个问题已经问过很多次了。但是,提供的答案不一致,并且使用多种方法来获取鼠标位置。一些例子:
方法1:
canvas.onmousemove = function (event) { // this object refers to canvas object
Mouse = {
x: event.pageX - this.offsetLeft,
y: event.pageY - this.offsetTop
}
}
Run Code Online (Sandbox Code Playgroud)
方法2:
function getMousePos(canvas, evt) {
var rect = canvas.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
}
Run Code Online (Sandbox Code Playgroud)
方法3:
var findPos = function(obj) {
var curleft = curtop = 0;
if (obj.offsetParent) {
do {
curleft += obj.offsetLeft;
curtop += obj.offsetTop;
} while (obj = obj.offsetParent);
}
return { x …Run Code Online (Sandbox Code Playgroud)