Newer posts are loading.
You are at the newest post.
Click here to check if anything new just came in.

How to Generate Noise with Canvas

Not too long ago, I noted on Twitter that it’d be fantastic if, one day, CSS3 provided support for adding noise to elements (not audio, but texture). After a bit of experimentation and Googling, I came across a solution that uses JavaScript and canvas to dynamically create noise.

The Screencast

Press the HD button for a clearer picture.

Subscribe to our YouTube page to watch all of the video tutorials!

Final Source

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8" />

      function generateNoise(opacity) {
         if ( !!!document.createElement('canvas').getContext ) {
            return false;
         var canvas = document.createElement('canvas'),
            ctx = canvas.getContext('2d'),
            x, y,
            r, g, b,
            opacity = opacity || .2;

         canvas.width = 55;
         canvas.height = 55;

         for ( x = 0; x < canvas.width; x++ ) {
            for ( y = 0; y < canvas.height; y++ ) {
               r = Math.floor( Math.random() * 255 );
               g = Math.floor( Math.random() * 255 );
               b = Math.floor( Math.random() * 255 );

               ctx.fillStyle = 'rgba(' + r + ',' + g + ',' + b + ',' + opacity + ')';
               ctx.fillRect(x, y, 1, 1);
 = "url(" + canvas.toDataURL("image/png") + ")";



The big question: is it practical to use a solution like this? Ehh — technically, sure. Browsers that don’t support canvas will simply display a solid background color. That being said, a tiny 24-bit PNG still works perfectly, and is what I’ll most likely continue to use until a more convenient solution becomes available.

What do you think? Or better yet, do you know of a better solution? Mostly, the purpose of this tutorial is mostly to work with canvas a bit, and toy around with things! Thanks for watching, and thank you to Mitch Johnson for the concept.

Get rid of the ads (sfw)

Don't be the product, buy the product!