Video icon 64
Learning to code? Skill up faster with our practical video courses. Start your free trial today.
Advertisement

How to Generate Noise with Canvas

by

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,
   number,
   opacity = opacity || .2;

   canvas.width = 45;
   canvas.height = 45;

   for ( x = 0; x < canvas.width; x++ ) {
      for ( y = 0; y < canvas.height; y++ ) {
         number = Math.floor( Math.random() * 60 );

         ctx.fillStyle = "rgba(" + number + "," + number + "," + number + "," + opacity + ")";
         ctx.fillRect(x, y, 1, 1);
      }
   }

   document.body.style.backgroundImage = "url(" + canvas.toDataURL("image/png") + ")";
}
generateNoise(.1); // default opacity is .2

</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 Dennis Hotson for the concept.

Advertisement