HTML5 Canvas - Coordinate Scaling

Written on: December 10, 2015

While I was working on Muse, I ran into a fun problem. The application relied heavily on everyone's x and y coordinates and since most people's screens were different sizes this meant that other people's mouse pointers would display in the wrong locations.

To fix this I realized that I needed some way to scale everyone's coordinates to a default scale. It ended up being the same equation I use to figure out what grade I got out of 100 when getting an exam out of 130 or 47.

The Equation

\(Scaling: coordinate * {default scale \over current scale}\)
\(Descaling: coordinate / {default scale \over current scale}\)

Simple enough, and it works. So for the application I used that to transfer scaled coordinates and unscale coordinates the client received.

As an example: converting a 9/10 to an out of 100 scale:
\(Sending: 9 * {100 \over 10} = 90\)
\(Receiving: 90 / {100 \over 10} = 9\)

Sending

socket.emit('mouseCoord',  {
    x: mouse.x * (2000/windowWidth),
    y: mouse.y * (2000/windowHeight)
};

Receiving

updateCursor(
    data.x/(2000/windowWidth),
    data.y/(2000/windowHeight)
    );