I have a 16x16 canvas that is scaled with CSS (width:90%; height: auto;
) and I'm attempting to convert mouse coordinates on the canvas to one of the 16x16 pixels. I'm taking it from an onmousemove
event, and while I can get the raw screen coordinates, I need to get where it lies on the canvas.
CodePudding user response:
Try this:
const canvas = document.querySelector( 'canvas' );
canvas.addEventListener( 'mousemove', event => {
const bb = canvas.getBoundingClientRect();
const x = Math.floor( (event.clientX - bb.left) / bb.width * canvas.width );
const y = Math.floor( (event.clientY - bb.top) / bb.height * canvas.height );
console.log({ x, y });
});
html,body { height: 100%; }
canvas { width: 100%; height: 100%; }
<canvas width="16" height="16"></canvas>
So you simply take the coordinate, take of the offset of the canvas (fullscreen that would be 0
), then divide it by the visual width of the canvas and multiply by the actual width of the canvas. If you floor
that you get a rounded pixel coordinate.
The above code works for any size canvas, since it keeps in mind the offset it has from the screen (also client
in mouse coordinate). SO whatever the width of your canvas, this should return the correct pixel.