Archive
This post is archived and may contain outdated information. It has been set to 'noindex' and should stop showing up in search results.
JavaScript Canvas - Getting Mouse Position When Page is Scrolled
Feb 16, 2014ProgrammingComments (5)
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;
};
Comments (5)
Add a Comment
Pascal Garin   Aug 08, 2022
Thank you very much for this basic, but very useful article for people like me not familiar with canvas. I was looking for recaluculating mouse position in a relatively positioned canvas and found many other - very - complicated solutions. This one is cristal clear and simple!
Jack   Oct 01, 2021
I agree with other comments, Article headline is - "Getting Mouse Position When Page is Scrolled". As there is no mouse position exposed in the scroll event, people will be looking for a workaround and the one above is definitely not a workaround for that.
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