If you are using canvas with predefined width and height you probably know that resizing the window and canvas result in size not always the same as the screen.
This is annoying especially for retrieving mouse coordinates exactly matching with the canvas size instead of the window size.
Here is an idea on how to stretch the canvas and still keep the coordinates correct for the original dimension:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
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 }; } |