title: html5 canvas elastic collision squares
body: <p>I am re-asking this question since I did not make myself clear in what I wanted in my last question.</p>
  
  <p>Does anyone know how to do elastic collision or handle collision in Canvas using rectangles? Or can point me in the right direction?</p>
  
  <p>I created a canvas that has multiple square and would like each square to deflect when they touch.</p>
  
  <p>Here is a quick fiddle that I put together showing to black buffer canvases <a href="http://jsfiddle.net/claireC/Y7MFq/10/" rel="nofollow">http://jsfiddle.net/claireC/Y7MFq/10/</a></p>
  
  <p>line 39 is where I started the collision detection and line 59 is where I tried to execute it. I will have more than 3 squares moving around and want them to deflect if/when they touch each other</p>
  
  <pre><code>var canvas = document.getElementById("canvas"),
      context = canvas.getContext("2d");
  context.fillStyle = "#FFA500";
      context.fillRect(0, 0, canvas.width, canvas.height);
  
  var renderToCanvas = function (width, height, renderFunction) {
      var buffer = document.createElement('canvas');
      buffer.width = width;
      buffer.height = height;
      renderFunction(buffer.getContext('2d'));
      return buffer;
  };
  
  var drawing = renderToCanvas(100, 100, function (ctx) {
  ctx.fillStyle = "#000";
      ctx.fillRect(0, 0, canvas.width, canvas.height);
  
  
  });
  
  var drawing2 = renderToCanvas(100, 100, function (ctx) {
  ctx.fillStyle = "blue";
      ctx.fillRect(0, 0, canvas.width, canvas.height);
  
  
  });
  
  var x = 0, 
   y = 0,
  x2 = 200,
  y2 = 10,
  vx = .80,
  vy = .80,
  vx2 = .80,
  vy2 = .80;
  
  
  
      function collides(rectA, rectB) {
        return !(rectA.x + rectA.width &lt; rectB.x2 ||
         rectB.x2 + rectB.width &lt; rectA.x ||
         rectA.y + rectA.height &lt; rectB.y2 ||
         rectB.y2 + rectB.height &lt; rectA.y);
        }; 
  
      function executeFrame() {
          x+=vx;
          y+=vy;
          x2+=vx2;
          y2+=vy2;
  
          if( x &lt; 0 || x &gt; 579) vx = -vx; 
          if( y &lt; 0 || y &gt; 265) vy = -vy;
  
          if( x2 &lt; 0 || x2 &gt; 579) vx2 = - vx2; 
          if( y2 &lt; 0 || y2 &gt; 233) vy2 = - vy2;
  
          if(collides(drawing, drawing2)){
              //move in different direction
          };
  
          context.fillStyle = "#FFA500"; 
          context.fillRect(0, 0, canvas.width, canvas.height);
          context.drawImage(drawing, x, y);
          context.drawImage(drawing2, x2, y2);
  
  
          requestAnimationFrame(executeFrame);
      }
  
      //start animation
      executeFrame();
  </code></pre>