Pixelation on Canvas

I’ve been working on an animation for OUBEY.com homepage. The main image on the homepage is OUBEY’s face pixelated in grayscale. I wanted to try to isolate the position and size of random pixels and create an object to match the image. This rendered object would lie exactly on top of the pixel contained in the image and animate on screen. This was accomplished by creating a canvas element of the image and using the canvasContext.getImageData method available in HTML5. Calling this method returns an array with RGBA pixel information:

  • px.data[ 0 ] is Red.
  • px.data[ 1 ] is Green.
  • px.data[ 2 ] is Blue.
  • px.data[ 3 ] is Alpha.

By traversing this array in steps of 4, I was able to choose random pixels from the image and extrapolate x, y, width, height:

  • By moving left one pixel until the RGB value changed, I found the left edge.
  • By moving to the right one pixel at a time until the RGB value changed, right edge.
  • Move up to find top edge.
  • Move down to find bottom edge.

Here’s a screenshot of the result, running 10,000 iterations. The objects created are red for visual contrast:

HTML5 Rocks: Integrating Canvas into your Web App
HTML5 Rocks: Image Filters with Canvas