title: Getting relative mouse position on canvas after scaling
body: <p><strong>Problem:</strong> 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.</p>
  
  <p><strong>Cause:</strong> To calculate where to start and end a line, I normalize input upon capture to be between 0 and 1 inclusive, like so:</p>
  
  <pre><code>// Pseudocode
  line.x = mousePosition.x / canvas.width;    
  line.y = mousePosition.y / canvas.height;
  </code></pre>
  
  <p>Because of this, the <code>canvas</code> can be of any size and in any position. </p>
  
  <p>To implement a zoom-on-scroll functionality, I simply <code>translate</code> based on the current mouse position, <code>scale</code> the canvas by a factor of 2, then <code>translate</code> back the negative value of the current mouse position (as recommended <a href="https://stackoverflow.com/a/5526721/5665799">here</a>).</p>
  
  <p><strong>Here's where the problem lies</strong></p>
  
  <p>When I zoom, the canvas doesn't seem to have a notion of it's original size. </p>
  
  <p>For instance, let's say I have a 1000px square canvas.  Using my normalized <code>x</code> and <code>y</code> above, the upper left corner is <code>0, 0</code> and the lower right is <code>1, 1</code>.</p>
  
  <p>I then zoom into the center through scaling by a factor of 2.  I would expect that my new upper left would be <code>0.5, 0.5</code> and my lower right would be <code>0.75, 0.75</code>, but it isn't.  Even when I zoom in, the upper left is still <code>0, 0</code> and the lower right is <code>1, 1</code>.</p>
  
  <p>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.</p>
  
  <p><strong>What I need to know:</strong> 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.</p>
  
  <hr>
  
  <p>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.</p>