title: recursive image manipulation (Canvas, HTML5, Javascript)
body: <p>I’m trying to use Canvas for a fractal algorithm that requires one to draw something, then capture that image, draw some mangled copies of it, then capture <em>that</em> image, etc. I’m running into a problem, though, because toDataURL() seems to be causing a failure in either the clear screen command ("clearRect") or the restore transformation matrix command ("restore").</p>
  
  <p>The code below is intended to draw a black square, then copy the canvas to a variable named “img”, translate down and to the right, then paste “img” to the new position. The result should be two squares.  But instead it’s first 1 square, then 2 squares, then 3, then 4 … (Then it goes out of bounds, but presumably it’s still copying squares off the page.)</p>
  
  <p>Any help will be greatly, greatly appreciated.</p>
  
  <p>Here's a link to the code in action: <a href="https://www.msu.edu/~brown202/dataURLproblem.html" rel="nofollow">https://www.msu.edu/~brown202/dataURLproblem.html</a></p>
  
  <p>Here's the code:</p>
  
  <pre><code>    &lt;html&gt;
          &lt;head&gt;
              &lt;script type="application/x-javascript"&gt;
                  function draw() {
                      var canvas = document.getElementById("fractal");
                      if (canvas.getContext) {
                          var ctx = canvas.getContext("2d");
                          var img;
                          ctx.clearRect(0,0,400,400);    // clear the canvas, which measures 400 by 400
                          ctx.fillRect (0,0,100,100);    // draw a square
                          ctx.save();
                              img = canvas.toDataURL();    // store the canvas image in "img"
                              ctx.translate(100,100);      // shift picture
                              ctx.drawImage(img, 0,0);    // draw the stored image of the canvas in the new place
                          ctx.restore();
                      }
                  }
                  function init() {
                      setInterval(draw,500);          // repeat every 500 ms.
                  }
              &lt;/script&gt;
          &lt;/head&gt;
          &lt;body onload="init();"&gt;
              &lt;canvas id="fractal" width="400" height="400"&gt;
                  &lt;p&gt;This animation requires a browser that supports the
                  &lt;a href="http://www.w3.org/html/wg/html5/"&gt;HTML5&lt;/a&gt; 
                  &amp;lt;canvas&amp;gt; feature.&lt;/p&gt;
              &lt;/canvas&gt;
          &lt;/body&gt;
      &lt;/html&gt;
  </code></pre>