Skip to content

Instantly share code, notes, and snippets.

@fxcosta
Created February 16, 2018 04:09
Show Gist options
  • Save fxcosta/0e11214867846a338702baa103592b82 to your computer and use it in GitHub Desktop.
Save fxcosta/0e11214867846a338702baa103592b82 to your computer and use it in GitHub Desktop.
HTML canvas resize and mouse coordinates from http://ictknowledge.net/html-canvas-resize-and-mouse-coordinates/
canvasName = "mycanvas";
document.getElementById(canvasName).addEventListener('mousemove', function(evt) {
var xy = getMousePos(evt);
var position = (xy.x) + ', ' + (xy.y);
alert(position);
}
function getMousePos(evt) {
var rect = document.getElementById(canvasName).getBoundingClientRect();
var X = (evt.clientX - rect.left) / (document.getElementById(canvasName).clientWidth / document.getElementById(canvasName).width);
var Y = (evt.clientY - rect.top) / (document.getElementById(canvasName).clientHeight / document.getElementById(canvasName).height);
X = Math.ceil(X);
Y = Math.ceil(Y);
return {
x: X,
y: Y
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment