title: Confused by globalCompositeOperation
body: <p>I am trying to program a simple demo of the first few iterations of a Sierpinski Carpet like so:</p>
  
  <p><a href="https://i.stack.imgur.com/5CpFs.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5CpFs.gif" alt="Sierpinski Carpet"></a></p>
  
  <p>The way I want to proceed is by clicking to apply the basic pattern mask on a smaller scale each step. It seems to me that by starting with a black square, and then using a globalCompositeOperation of "destination-in" and a source mask just like the second image I should be able to do what I want, but I'm struggling to put it together.</p>
  
  <p>This draws the background black square:</p>
  
  <pre><code>context.globalCompositeOperation = "source-over";
  context.fillStyle = 'black';
  context.fillRect(0, 0, 500, 500);
  </code></pre>
  
  <p>And then I expected code like the following should produce the first step.  But instead it just goes blank.</p>
  
  <pre><code>context.globalCompositeOperation = "destination-in";
  var mask = [1, 1, 1, 1, 0, 1, 1, 1, 1];
  for (var m = 0; m &lt; 9; ++m)
  {
      var x = 10 + m % 3 * 150;
      var y = 10 + Math.floor(m / 3) * 150;
      if (mask[m] &gt; 0)
      {
          context.fillRect(x, y, 150, 150);
      }
  }
  </code></pre>
  
  <p>I've put together a fiddle at <a href="http://jsfiddle.net/128gxxmy/4/" rel="nofollow noreferrer">http://jsfiddle.net/128gxxmy/4/</a> to show the problem.</p>
  
  <p>It really doesn't seem to be a difficult thing to do, so I've clearly misunderstood something significant and will be grateful for any advice.</p>
  
  <p>Thanks.</p>
  
  <p>Edit:  Of course!  I know why it goes blank. The first fill rect clears all but the top left corner, and the next one wipes that out.  I need to use rect(...) then fill() in one go.  If I rework it to paint each pass in a single step it should do the trick.</p>