Last Updated: February 25, 2016
·
17.35K
· jackrugile

Set Canvas as Body Background

Dynamic Square of Subtle Noise

To dynamically generate a little chunk of goodness with canvas and set it as a tiled background for your body tag, you just have to leverage the toDataURL() function. Below is a quick example of setting subtle noise as a background. You can go as crazy as you want. The rad part is, you don't even have to append the canvas element to the page to use it.

View Demo on CodePen

var c = document.createElement('canvas'),        
    ctx = c.getContext('2d'),
    cw = c.width = 200,
    ch = c.height = 200;

for( var x = 0; x < cw; x++ ){
    for( var y = 0; y < ch; y++ ){
        ctx.fillStyle = 'hsl(0, 0%, ' + ( 100 - ( Math.random() * 15 ) ) + '%)';
        ctx.fillRect(x, y, 1, 1);
    }
}

document.body.style.background = 'url(' + c.toDataURL() + ')';

Picture

In short, we are looping over each pixel in a 200 × 200 square and filling it with an HSL value with a random lightness between 85 and 100. Once that is complete, we set the body background to the contents of the canvas with toDataURL(). The background then repeats the square by default.