javascripthtmlcanvas

HTML5 Canvas - Repeat Canvas Element as a Pattern


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:

$(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 <= 64; w++) {
        for (var h = 0; h <= 64; h++) {
            rand = Math.floor(Math.random()*50);
            while(rand < 20){
                rand = Math.floor(Math.random()*50);
            }
            opacity = Math.random();
            while(opacity < 0.5){
                opacity = Math.random();
            }
            ctx.fillStyle= 'rgba('+rand+','+rand+','+rand+','+opacity+')';
            ctx.fillRect(w, h, 1, 1);
        }
    }
});

The thing is, I don't 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?

Here is a fiddle: http://jsfiddle.net/ecMDq/


Solution

  • Doing what you want is actually super easy. You do not need to use images at all. The createPattern function accepts an image or another canvas! (Or a video tag, even)

    All you have to do is make a canvas that is only 64x64 large and make the pattern on it. Let's call this canvas pattern. You only have to make your design once.

    Then with the context of the main canvas we can do:

    // "pattern" is our 64x64 canvas, see code in fiddle
    var pattern = ctx.createPattern(pattern, "repeat");
    ctx.fillStyle = pattern;
    

    Working example using your code to make the pattern, then repeating it onto a 500x500 canvas:

    http://jsfiddle.net/tGa8M/