Optimize Images With HTML5 Canvas

Optimize Images With HTML5 Canvas

01 function addNoise(canvas) {
02    var ctx = canvas.getContext('2d');
03  
04    // Get canvas pixels
05    var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
06    var pixels = imageData.data;
07  
08    for (var i = 0, il = pixels.length; i < il; i += 4) {
09 var color = Math.round(Math.random() * 255);
10  
11       // Because the noise is monochromatic, we should put the same value in the R, G and B channels
12       pixels[i] = pixels[i + 1] = pixels[i + 2] = color;
13  
14       // Make sure pixels are opaque
15       pixels[i + 3] = 255;
16    }
17  
18    // Put pixels back into canvas
19    ctx.putImageData(imageData, 0, 0);
20 }
21  
22 // Set up canvas
23 var canvas = document.createElement('canvas');
24 canvas.width = canvas.height = 200;
25 document.body.appendChild(canvas);
26  
27 addNoise(canvas);
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s