Posted By

Nettuts on 11/13/10


Tagged


Versions (?)

Who likes this?

9 people have marked this snippet as a favorite

mloberg
tomasdev
Foxyfox
themolitor
antonioreyna
sethetter
qubestream
wirenaught
adambundy


Generate (Image) Noise with Canvas


 / Published in: JavaScript
 

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

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/

  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

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: tomasdev on November 15, 2010

If you do var num=Math.random() * 255; r = Math.floor( num ); g = Math.floor( num ); b = Math.floor( num );

You can make a grayscale or monochromatic noise. And also, you should not generate canvas larger than 2 digits. Because it's going to hang the browser for some seconds! (I've tried 350 and my laptop died about 3 secs)

You need to login to post a comment.