Skip to content

Instantly share code, notes, and snippets.

@CodeZombie
Created January 24, 2016 07:19
Show Gist options
  • Save CodeZombie/4af2d6800bcb968bdf3a to your computer and use it in GitHub Desktop.
Save CodeZombie/4af2d6800bcb968bdf3a to your computer and use it in GitHub Desktop.
A small script that gets the relative mouse position inside a Canvas element.
function mousePosition(e_) {
//accepts a mouseEvent
var canvas = document.getElementById("myCanvas");
var canvas_bound_rect = canvas.getBoundingClientRect();
mousex = Math.round(((e_.clientX - canvas_bound_rect.left)/(canvas_bound_rect.right - canvas_bound_rect.left)) * canvas.width);
mousey = Math.round(((e_.clientY - canvas_bound_rect.top)/(canvas_bound_rect.bottom - canvas_bound_rect.top)) * canvas.height);
return {x : mousex, y : mousey}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment