Getting the Exact Mouse Position

Following up on a thread we left unexplored a few moments ago, the clientX and clientY properties don’t give you the exact mouse position in many situations. Understanding the details of why is something that I cover in this article, but the gist of it is that the clientX and clientY properties don’t account for your canvas element physically being pushed around by all of its ancestors. A margin or padding here and there can cause your positioning inside the canvas element to go out-of-sync. It’s really quite sad.

The solution is to pair up your clientX and clientY properties with the following code (taken from the Get an Element’s Position Using JavaScript article) that takes into account all of the various position-related shenanigans that your canvas might be affected by:

Get hands-on with 1200+ tech skills courses.