5.8 Pixel Manipulation 143
top to bottom. The number of all values is saved in the attribute ImageData.
data.length.
Using a simple for loop, we can now read the individual values of the CanvasPix-
elArray and make them visible with alert(). Starting at 0 , we work from pixel
to pixel by increasing the counter by 4 after each loop. The RGBA values are the
result of offsets from the current position. Red can be found at counter i, green
at i+1, blue at i+2, and the alpha component at i+3:
for (var i=0; i<ImageData.data.length; i+=4) {
var r = ImageData.data[i];
var g = ImageData.data[i+1];
var b = ImageData.data[i+2];
var a = ImageData.data[i+3];
alert(r+" "+g+" "+b+" "+a);
}
Modifying pixel values works exactly the same: We change the Canvas-PixelAr-
ray in-place by assigning new values. In our example, the RGB values are set to
random numbers between 0 and 255 via Math.random(); the alpha component
remains unchanged:
for (var i=0; i<ImageData.data.length; i+=4) {
ImageData.data[i] = parseInt(Math.random()255);
ImageData.data[i+1] = parseInt(Math.random()255);
ImageData.data[i+2] = parseInt(Math.random()*255);
}
After this step, the canvas still looks the same. The new colors only become vis-
ible after we write the modified CanvasPixelArray back to the canvas via the
method putImageData(). When calling putImageData(), we can have a maximum
of seven parameters:
context.putImageData(
ImageData, dx, dy, [ dirtyX, dirtY, dirtyWidth, dirtyHeight ]
)
The first three attributes are required; in addition to the ImageData object, they
contain the coordinate of the origin point dx/dy, from which the CanvasPix-
elArray is applied via its width and height attributes. The optional dirty pa-
rameters cut out only a specified section of the CanvasPixelArray and write
back only that section with reduced width and height. Figure 5.28 shows our
4-pixel canvas before and after modification, with a list of the relevant values
of the CanvasPixelArray.