鼠标在canvas里的相对坐标
<canvas id="canvas"></canvas>
//获取相对于canvas的坐标
function captureMouse(element) {
let mouse = { x: 0, y: 0 };
element.addEventListener('mousemove', function (event) {
let x, y;
if (event.pageX || event.pageY) {
x = event.pageX;
y = event.pageY;
} else {
x = event.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
y = event.clientY + document.body.scrollTop + document.documentElement.scrollTop;
}
x -= element.offsetLeft;
y -= element.offsetTop;
mouse.x = x;
mouse.y = y;
}, false);
return mouse;
}
var canvas = document.getElementById("canvas");
var mouse = captureMouse(canvas); //鼠标在画布的相对坐标,随着鼠标在画布上移动实时变化