Last active
November 14, 2022 13:40
-
-
Save esimov/3986036 to your computer and use it in GitHub Desktop.
Get mouse position relative to canvas in JS
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
BitmapData.prototype.getContext = function() { | |
return this.context; | |
}; | |
BitmapData.prototype.getCanvas = function() { | |
return this.canvas; | |
}; | |
BitmapData.prototype.getCanvasPos = function(el) { | |
var canvas = document.getElementById(el) || this.getCanvas(); | |
var _x = canvas.offsetLeft; | |
var _y = canvas.offsetTop; | |
while(canvas = canvas.offsetParent) { | |
_x += canvas.offsetLeft - canvas.scrollLeft; | |
_y += canvas.offsetTop - canvas.scrollTop; | |
} | |
return { | |
left : _x, | |
top : _y | |
} | |
}; | |
BitmapData.prototype.mousePos = function(e) { | |
var mouseX = e.clientX - this.getCanvasPos(e.target).left + window.pageXOffset; | |
var mouseY = e.clientY - this.getCanvasPos(e.target).top + window.pageYOffset; | |
return { | |
x : mouseX, | |
y : mouseY | |
}; | |
}; | |
BitmapData.prototype.touchPos = function(e) { | |
if (e.touches !== undefined && e.touches.length == 1) { | |
var touch = e.touches[0]; | |
var touchX = touch.pageX - this.getCanvasPos().left + window.pageXOffset; | |
var touchY = touch.pageY - this.getCanvasPos().top + window.pageYOffset; | |
} | |
return { | |
x : touchX, | |
y : touchY | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment