title: HTML5 Canvas - Repeat Canvas Element as a Pattern
body: <p>I have a 64x64 canvas square element which I want to repeat in x- and y-directions to fill the page. I've found many explanations on how to do this with an image, but none explaining how to do it with a canvas element. Here is my code so far:</p>
  
  <pre><code>$(document).ready(function(){
      var canvas = document.getElementById('dkBg');
      var ctx = canvas.getContext('2d');  
      ctx.canvas.width  = window.innerWidth;
      ctx.canvas.height = window.innerHeight;
      ctx.fillStyle = 'rgb(0,0,0)';
      //I want the following rectangle to be repeated:
      ctx.fillRect(0,0,64,64);
      for(var w=0; w&lt;=64; w++){
              for(var h=0; h&lt;=64; h++){
                      rand = Math.floor(Math.random()*50);
                      while(rand&lt;20){
                              rand = Math.floor(Math.random()*50);
                      }
                      opacity = Math.random();
                      while(opacity&lt;0.5){
                              opacity = Math.random();
                      }
                      ctx.fillStyle= 'rgba('+rand+','+rand+','+rand+','+opacity+')';
                      ctx.fillRect(w,h,1,1);
              }
      }
  });
  </code></pre>
  
  <p>The thing is, I <strong>don't</strong> want all of the random numbers/etc to be regenerated. I just want to tile the exact same square to fit the page. Is this possible?</p>
  
  <p>Here is a fiddle: <a href="http://jsfiddle.net/ecMDq/" rel="nofollow">http://jsfiddle.net/ecMDq/</a></p>