Created
September 25, 2012 11:34
-
-
Save hendriklammers/3781251 to your computer and use it in GitHub Desktop.
Javascript: Canvas mouse position
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
// Add mousePosition on the Canvas element | |
(function () { | |
function mousePosition(event) { | |
var totalOffsetX = 0, | |
totalOffsetY = 0, | |
coordX = 0, | |
coordY = 0, | |
currentElement = this, | |
mouseX = 0, | |
mouseY = 0; | |
// Traversing the parents to get the total offset | |
do { | |
totalOffsetX += currentElement.offsetLeft; | |
totalOffsetY += currentElement.offsetTop; | |
} | |
while ((currentElement = currentElement.offsetParent)); | |
// Use pageX to get the mouse coordinates | |
if (event.pageX || event.pageY) { | |
mouseX = event.pageX; | |
mouseY = event.pageY; | |
} | |
// IE8 and below doesn't support event.pageX | |
else if (event.clientX || event.clientY) { | |
mouseX = event.clientX + document.body.scrollLeft + document.documentElement.scrollLeft; | |
mouseY = event.clientY + document.body.scrollTop + document.documentElement.scrollTop; | |
} | |
// Subtract the offset from the mouse coordinates | |
coordX = mouseX - totalOffsetX; | |
coordY = mouseY - totalOffsetY; | |
return { | |
x: coordX, | |
y: coordY | |
}; | |
} | |
HTMLCanvasElement.prototype.mousePosition = mousePosition; | |
}()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment