They are indeed shifting as mouse coordinates are relative to client window not the canvas element itself.
I suspect you are using the clientX/Y as-is without compensating for this.
Example: correcting mouse positions
function getXY(canvas, event) {
var rect = canvas.getBoundingClientRect(); // absolute position of canvas
return {
x: event.clientX - rect.left,
y: event.clientY - rect.top
}
}
Now simply call this function each time you need the mouse position:
function onmousemove(e) {
var pos = getXY(canvas, e);
console.log(pos.x, pos.y);
}
This will provide adjusted position. Notice it does not compensate for border or padding if you use that - in those cases, wrap canvas in a parent div and apply border/padding to that div instead.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…