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.
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() + ')';
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.
Written by Jack Rugile
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Js
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#