Last active
August 3, 2017 17:15
-
-
Save monkianer/2762c8c2e9c99f658c9ae577ea4045af to your computer and use it in GitHub Desktop.
Get mouse position on the canvas
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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