JavaScript Canvas - Getting Mouse Position When Page is Scrolled

Feb 16, 2014   Programming   Nick Vogt   Comments (3)
Please note that this post is over a year old and may contain outdated information.
If the user has scrolled the page that your canvas game is on, or used the browser zoom feature, it can mess up the accurate calculation of the mouse position. An easy solution is to use the getBoundingClientRect method of the canvas object. This returns a rectangle object that gives you the current offset of the canvas relative to the page.

Here is an example usage inside a mousemove event to get the accurate mouse position:

window.addEventListener('mousemove', mouseMoveEvent);

function mouseMoveEvent(e) {
    var canvas = document.getElementById('canvas');
    var rect = canvas.getBoundingClientRect();
    var mouseX = e.clientX - rect.left;
    var mouseY = e.clientY - rect.top;
Share This Post

Comments (3)

Randall   Apr 27, 2020
The two other commenters clearly didn't understand the article.
anonymous   Apr 02, 2020
What a stupid article... "mousemove" event is not the "scroll" event. Change our article for "Getting Mouse Position When mouse is moved"... which is pretty useless.
anonymous   Feb 03, 2020
mousemove Event is not triggered on scrolling
Share This Post
H3XED © Nick Vogt   RSS   Policies   Twitter