How to get real mouse position in canvas with JavaScript?

Sometimes, we want to get real mouse position in canvas with JavaScript.

In this article, we’ll look at how to get real mouse position in canvas with JavaScript.

How to get real mouse position in canvas with JavaScript?

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.

Conclusion

To get real mouse position in canvas with JavaScript, we use the canvas getBoundingClientRect method.