H3XED

JavaScript Canvas - Getting Mouse Position When Page is Scrolled

Feb 16, 2014   Programming   Nick Vogt   Comments
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
Twitter

Comments (0)

Share This Post
Twitter
H3XED © Nick Vogt   RSS   Policies   Twitter