To get real mouse position in canvas with JavaScript, we use the canvas getBoundingClientRect
method.
For instance, we write
const getMousePos = (canvas, evt) => {
const rect = canvas.getBoundingClientRect();
return {
x: ((evt.clientX - rect.left) / (rect.right - rect.left)) * canvas.width,
y: ((evt.clientY - rect.top) / (rect.bottom - rect.top)) * canvas.height,
};
};
to call canvas.getBoundingClientRect
to get an object with the dimensions of the canvas’ bounding rectangle.
Then we get the x and y coordinates of the mouse in the canvas with
((evt.clientX - rect.left) / (rect.right - rect.left)) * canvas.width and
((evt.clientY – rect.top) / (rect.bottom – rect.top)) * canvas.height`.
This takes into account changing coordinates and scaling.