HTML5 and CSS3 Advent 2011

Amazing canvas pixels

One of the standard tools in every front-end developer's arsenal is Adobe Photoshop. You use it to cut up Photoshop designs (if that's the way you work) and to create all kinds of image material for your site. Until recently you also needed it to add effects to your images (think desaturation, pixelation, blur etc.), but with the introduction of <canvas> we can do these things dynamically in the browser!

Leaf in snow
Grayscale filter
Leaf in snow
Threshold filter
Leaf in snow
Pixelation filter

How does it work?

The first thing we do is replace the image with a canvas element. We create the canvas element in javascript (document.createElement("canvas")), give it the width and height of the original image, draw the image onto the canvas with context.drawImage(imgelement,0,0) and replace the image element with the canvas element.

To actually do something with the newly injected canvas image data, we use imgData = context.getImageData(0, 0, canvas.width, canvas.height). This gets us one giant array (in imgData.pixels) with every R, G, B and A value of every pixel in the image. The rest is pretty straight forward, we apply a calculation (depending on filter) to those pixels in a for-loop and put the values back on the canvas by calling context.putImageData(0, 0, imgData).

Show us the source!

Feel free to look around the different source files we used for this example.

Check out our all new HTML & CSS Advent 2012