Skip to content
Advertisement

Get canvas pixel position from mouse coordinates

I have a 16×16 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 16×16 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.

Advertisement

Answer

Try this:

JavaScript
JavaScript
JavaScript

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.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement