Problem: I'm working with an HTML canvas. My canvas has a background image that multiple people can draw over in real-time (via socket.io), but drawing breaks if you've zoomed in.
Cause: To calculate where to start and end a line, I normalize input upon capture to be between 0 and 1 inclusive, like so:
// Pseudocode
line.x = mousePosition.x / canvas.width;
line.y = mousePosition.y / canvas.height;
Because of this, the canvas
can be of any size and in any position.
To implement a zoom-on-scroll functionality, I simply translate
based on the current mouse position, scale
the canvas by a factor of 2, then translate
back the negative value of the current mouse position (as recommended here).
Here's where the problem lies
When I zoom, the canvas doesn't seem to have a notion of it's original size.
For instance, let's say I have a 1000px square canvas. Using my normalized x
and y
above, the upper left corner is 0, 0
and the lower right is 1, 1
.
I then zoom into the center through scaling by a factor of 2. I would expect that my new upper left would be 0.5, 0.5
and my lower right would be 0.75, 0.75
, but it isn't. Even when I zoom in, the upper left is still 0, 0
and the lower right is 1, 1
.
The result is that when I zoom in and draw, the lines appear where they would as if I were not zoomed at all. If I zoomed into the center and "drew" in the upper left, I'd see nothing until I scrolled out to see that the line was actually getting drawn on the original upper left.
What I need to know: When zoomed, is there a way to get a read on what your new origin is relative to the un-zoomed canvas, or what amount of the canvas is hidden? Either of these would let me zoom in and draw and have it track correctly.
If I'm totally off base here and there's a better way to approach this, I'm all ears. If you need additional information, I'll provide what I can.