Generate (Image) Noise with Canvas


/ Published in: JavaScript
Save to your folder(s)

This allows you to add image noise to the body of your website. simply call generateNoise(), pass an optional opacity parameter, and then apply a background color to the body element in your stylesheet.

It's not ideal, and maybe isn't practical -- but it works. :)

Adapted from: http://mitchj.info/blog/2010/09/generate-background-noise-with-jquery/


Copy this code and paste it in your HTML
  1. function generateNoise(opacity) {
  2. if ( !!!document.createElement('canvas').getContext ) {
  3. return false;
  4. }
  5.  
  6. var canvas = document.createElement("canvas"),
  7. ctx = canvas.getContext('2d'),
  8. x, y,
  9. number,
  10. opacity = opacity || .2;
  11.  
  12. canvas.width = 45;
  13. canvas.height = 45;
  14.  
  15. for ( x = 0; x < canvas.width; x++ ) {
  16. for ( y = 0; y < canvas.height; y++ ) {
  17. number = Math.floor( Math.random() * 60 );
  18.  
  19. ctx.fillStyle = "rgba(" + number + "," + number + "," + number + "," + opacity + ")";
  20. ctx.fillRect(x, y, 1, 1);
  21. }
  22. }
  23.  
  24. document.body.style.backgroundImage = "url(" + canvas.toDataURL("image/png") + ")";
  25. }
  26. generateNoise(.1); // default opacity is .2

URL: http://nettuts.s3.amazonaws.com/854_noiseWithCanvas/noise.html

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.