title: Parallax effect with zoom and rotating
body: <p>I am currently experimenting with parallax effect that i am planning to implement to my HTML5-canvas game engine.
  The effect itself is fairly easy to achieve, but when you add zooming and rotating, things get a little more complicated, at least for me. My goal is to achieve something like this:<a href="http://www.youtube.com/watch?v=1u5cGZPdyEk" rel="nofollow">Youtube video.</a></p>
  
  <p>As you can see, you can zoom in and out "to the center", and also rotate around it and get the parallax effect.</p>
  
  <p>In my engine i want to have multiple canvases that are going to be my parallax layers, and i am going to translate them.
  I came up with something like this:</p>
  
  <pre><code>var parallax = {
      target: {
          x: Mouse.x,
          y: Mouse.y
      },
      offset: {
          x: -ctx.width / 2,
          y: -ctx.height / 2
      },
      factor: {
          x: 1,
          y: 1
      }
  }
  
  var angle = 0;
  var zoomX = 1;
  var zoomY = 1;
  
  var loop = function(){
      ctx.canvas.width = ctx.canvas.width; //Clear the canvas.
  
      ctx.translate(parallax.target.x * parallax.factor.x, parallax.target.y * parallax.factor.y);
      ctx.rotate(angle);
      ctx.scale(zoomX, zoomY);
      ctx.translate((-parallax.target.x - parallax.offset.x) * parallax.factor.x, (-parallax.target.y - parallax.offset.y) * parallax.factor.y);
  
      Draw(); //Function that draws all the objects on the screen.
  }
  </code></pre>
  
  <p>This is a very small and simplified part of my script, but i hope that's enough to get what i am doing. The object "parallax" contains the target position, the offset(the distance from the target), and the factor that is determining how fast the canvas is moving away relatively to the target. ctx is the canvas that is moving in the opposite direction of the target.(In this example i am using only one layer.) I am using the mouse as the "target", but i could also use the player, or some other object with x and y property. The target is also the point around which i rotate and scale the canvas.</p>
  
  <p>This method works completely fine as long as the factor is equal to 1. If it is something else, the whole thing suddenly stops working correctly, and when i try to zoom, it zooms to the top-left corner, not the target. I also noticed that if i zoom out too much, the canvas is not moving in the opposite way of the target, but in the same direction.</p>
  
  <p>So my question is: What is the correct way of implementing parallax with zooming and rotating?</p>
  
  <p>P.S. It is important to me that i am using canvases as the layers.</p>