Archive
This post is archived and may contain outdated information. It has been set to 'noindex' and should stop showing up in search results.
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:
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;
};