Skip to content

Instantly share code, notes, and snippets.

@esimov
Last active November 14, 2022 13:40
Show Gist options
  • Save esimov/3986036 to your computer and use it in GitHub Desktop.
Save esimov/3986036 to your computer and use it in GitHub Desktop.
Get mouse position relative to canvas in JS
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