Advertisement
  1. Web Design
  2. HTML/CSS
  3. HTML

How to Generate Noise with Canvas

Scroll to top
1 min read

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

Please accept marketing cookies to load this content.

Final Source

1
2
<!DOCTYPE html>
3
<html lang="en">
4
<head>
5
    <meta charset="UTF-8" />
6
    <title>Noise</title>
7
</head>
8
<body>
9
10
<script>
11
12
function generateNoise(opacity) {
13
   if ( !!!document.createElement('canvas').getContext ) {
14
      return false;
15
   }
16
17
   var canvas = document.createElement("canvas"),
18
   ctx = canvas.getContext('2d'),
19
   x, y,
20
   number,
21
   opacity = opacity || .2;
22
23
   canvas.width = 45;
24
   canvas.height = 45;
25
26
   for ( x = 0; x < canvas.width; x++ ) {
27
      for ( y = 0; y < canvas.height; y++ ) {
28
         number = Math.floor( Math.random() * 60 );
29
30
         ctx.fillStyle = "rgba(" + number + "," + number + "," + number + "," + opacity + ")";
31
         ctx.fillRect(x, y, 1, 1);
32
      }
33
   }
34
35
   document.body.style.backgroundImage = "url(" + canvas.toDataURL("image/png") + ")";
36
}
37
generateNoise(.1); // default opacity is .2

38
39
</script>
40
</body>
41
</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