Funky Image Pixels Manipulation with Canvas
Just got a few moments, so decided to play with canvas. The idea is basically based off this tutorial on Nettuts.
In this creation, we'll quickly load an image inside the 2d context of canvas (or simply, inside a canvas) and then get it's pixel data. After fetching the pixel data with getImageData
we're just gonna randomly manipulate all the R G B components and draw the manipulated image back into the canvas using setImageData
.
I would like to explain a bit on the pixel's data array returned by getImageData
which is basically a CanvasPixelArray
object. It's a single dimensional array where the index of the R value for each pixel is a multiple of 4. So arr[0]
is going to be the R value for the coordinate (0,0)
while arr[4]
is going to be the same for (0,1)
, so on and so forth. Adding +1 to the R's index is going to be the value for G (green) component, +2 for B and +3 for A. Simple!
Still confused ? MDN has a cool article for further explanation.