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

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">
<head>
    <meta charset="UTF-8" />
    <title>Noise</title>
</head>
<body>

   <script>
      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);
            }
         }

         document.body.style.backgroundImage = "url(" + canvas.toDataURL("image/png") + ")";
      }

      generateNoise(.1);
   </script>
</body>
</html>

Conclusion

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!

Schweinderl