Skip to content

Instantly share code, notes, and snippets.

@monkianer
Last active August 3, 2017 17:15
Show Gist options
  • Save monkianer/2762c8c2e9c99f658c9ae577ea4045af to your computer and use it in GitHub Desktop.
Save monkianer/2762c8c2e9c99f658c9ae577ea4045af to your computer and use it in GitHub Desktop.
Get mouse position on the canvas
function getCanvasMousePosition(e, canvas) {
var isRetina = true;
var offsetX = 0, offsetY = 0, mx, my;
if (canvas.offsetParent !== undefined) {
do {
offsetX += canvas.offsetLeft - canvas.scrollLeft;
offsetY += canvas.offsetTop - canvas.scrollTop;
} while ((canvas = canvas.offsetParent));
}
if( e.pageX || e.pageY ){
mx = e.pageX - offsetX - document.body.scrollLeft;
my = e.pageY - offsetY - document.body.scrollTop;
}
else if( e.touches[0].clientX || e.touches[0].clientY ){
mx = e.touches[0].clientX - offsetX;
my = e.touches[0].clientY - offsetY;
}
if( isRetina ){
mx *= 2;
my *= 2;
}
return {x: mx, y: my};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment