title: Implementing Layers in HTML5 Canvas
body: <p>I am about to implement Photoshop-like Layers in HTML5 Canvas. Currently I have two ideas. The first and maybe the simpler idea is to have a Canvas element for each layer like:</p>
  
  <pre><code>&lt;canvas id="layerName" width="320" height="240" style="position: absolute; left: 0; top: 0; z-index: 1;"&gt;&lt;/canvas&gt;
  &lt;canvas id="layerName" width="320" height="240" style="position: absolute; left: 0; top: 0; z-index: 2;"&gt;&lt;/canvas&gt;
  &lt;canvas id="layerName" width="320" height="240" style="position: absolute; left: 0; top: 0; z-index: 3;"&gt;&lt;/canvas&gt;
  </code></pre>
  
  <p>This way when you draw to a layer -- it actually goes to that "layer". Layers with transparent positions can be seen through to below layers (Canvases). Layer stacking is controlled with <code>z-index</code> property.</p>
  
  <p>The second idea is to use a single Canvas element and implement some logic to handle layers like in this case:</p>
  
  <pre><code>&lt;!DOCTYPE html&gt;
  &lt;html&gt;
      &lt;head&gt;
          &lt;title&gt;Test&lt;/title&gt;
          &lt;script&gt;
              window.addEventListener('load', function() {
                  var canvas = document.getElementById("canvas");  
                  var ctx = canvas.getContext("2d");  
  
                  var order = 0;
  
                  function drawLayer1() {
                      ctx.fillStyle = "rgb(200,0,0)";
                      ctx.fillRect (10, 10, 55, 50);
                  }
  
                  function drawLayer2() {
                      ctx.fillStyle = "rgba(0, 0, 200, 0.5)";
                      ctx.fillRect (30, 30, 55, 50);
                  }
  
                  function draw() {
                      ctx.clearRect(0, 0, 256, 256);
  
                      if (order === 0) {
                          drawLayer1();
                          drawLayer2();
                      }
                      else {
                          drawLayer2();
                          drawLayer1();
                      }
                  }
  
                  setInterval(draw, 250);
                  setInterval(function() {
                      order = 1 - order;
                  }, 200);
              }, false);
          &lt;/script&gt;
      &lt;/head&gt;
      &lt;body&gt;
          &lt;canvas id="canvas" width="256px" height="256px"&gt;&lt;/canvas&gt;
      &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p>In the above code the two layers will change stacking order every 200msec.</p>
  
  <p>So, the question is that which way would be the best way? What are the pros and cons of both approaches?</p>