title: Javascript - Rotating a rectangle before writing to canvas
body: <p>I've been having an enormous amount of difficulty getting a set of rectangles to face a certain point on a canvas block. I'm iterating through a set of points, and drawing rectangles, which are supposed to all face a certain point.</p>
  
  <p>First I set up the Radius, Focus point and Rectangle</p>
  
  <pre><code>var Angle = Math.PI;
  
  _.each(Points, function(Point) {
  var Radius = 10;
  
  var Focus = {
      X: 500,
      Y: 1000
  }
  
  var Rect = [
  {
      X: (Point.X - Radius/2),
      Y: (Point.Y - Radius/2)
  },
  {
      X: (Point.X + Radius/2),
      Y: (Point.Y - Radius/2)
  },
  {
      X: (Point.X + Radius/2),
      Y: (Point.Y + Radius/2)
  },
  {
      X: (Point.X - Radius/2),
      Y: (Point.Y + Radius/2)
  }
  ];
  </code></pre>
  
  <p>Then, using underscore, I iterate through and used the method I read about on another response.</p>
  
  <pre><code>var index = 0;
  _.each(Rect, function (V) {
      var dx2 = Focus.X - V.X;
      var dy2 = Focus.Y - V.Y;
      var dx2_ = dx2 * Math.cos(Angle) - dy2 * Math.sin(Angle);
      var dy2_ = dy2 * Math.sin(Angle) + dy2 * Math.cos(Angle);
  
      V.X = dx2_ + V.X;
      V.Y = dy2_ + V.Y; 
  
      Rect[index] = V;
      index++;
  });
  </code></pre>
  
  <p>Then its all set up in the normal canvas stuff. The context and the fillStyle are defined beforehand.</p>
  
  <pre><code>ctx.beginPath();
  ctx.moveTo(Rect[0].X, Rect[0].Y);
  ctx.lineTo(Rect[1].X, Rect[1].Y);
  ctx.lineTo(Rect[2].X, Rect[2].Y);
  ctx.lineTo(Rect[3].X, Rect[3].Y);
  ctx.lineTo(Rect[0].X, Rect[0].Y);
  
  ctx.fill();
  
  });
  </code></pre>
  
  <p>These are the initial squares (without the rotation each loop)</p>
  
  <p>Without rotation
  <img src="https://i.stack.imgur.com/dQrdq.png" alt="Without Rotation"></p>
  
  <p>This is what I get instead (seems like the rectangles are being rotated around the point instead of rotating towards the point)</p>
  
  <p>With angle set to pi
  <a href="https://i.stack.imgur.com/bMbzL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bMbzL.png" alt="With angle set to pi"></a>
  </p>
  
  <p>The behavior that I'm trying to get is to have them facing towards the bottom middle. (500,1000) if the canvas is 1000x1000.</p>
  
  <p>JSFiddle: <a href="http://jsfiddle.net/nmartin413/cMwTn/7/" rel="nofollow noreferrer">http://jsfiddle.net/nmartin413/cMwTn/7/</a></p>
  
  <p>I can't for the life of me figure out whats going wrong. If there's anything that stands out to you, please let me know :). Sorry for the long question, but this has really frustrated me.</p>
  
  <p>Thanks in advance!</p>