HTML5 Guidelines for Web Developers

(coco) #1
5.8 Pixel Manipulation 145

little bit of math, we can even write our own color filters for manipulating images.
We will show you how in the next section.


5.8.2 Color Manipulation with “getImageData()”,


“createImageData()”, and “putImageData()”


The starting picture for all examples is once again the photo of Yosemite Na-
tional Park, drawn onto the canvas onload via drawImage(). In a second step,
we define the original CanvasPixelArray via getImageData() and then modify
it in the third step. In a for loop, each pixel’s RGBA values are calculated fol-
lowing a mathematical formula and inserted into a CanvasPixelArray created
previously via createImageData(). At the end we write it back to the canvas with
putImageData().


Listing 5.1 provides the basic JavaScript frame of all filters used in Figure 5.29.
The function grayLuminosity() is not part of the code example but will be ad-
dressed later, together with the other filters:


Listing 5.1 Basic JavaScript frame for color manipulation


var image = new Image();
image.src = 'images/yosemite.jpg';
image.onload = function() {
context.drawImage(image,0,0,360,240);
var modified = context.createImageData(360,240);
var imagedata = context.getImageData(0,0,360,240);
for (var i=0; i<imagedata.data.length; i+=4) {
var rgba = grayLuminosity(
imagedata.data[i+0],
imagedata.data[i+1],
imagedata.data[i+2],
imagedata.data[i+3]
);
modified.data[i+0] = rgba[0];
modified.data[i+1] = rgba[1];
modified.data[i+2] = rgba[2];
modified.data[i+3] = rgba[3];
}
context.putImageData(modified,0,0);
};


The server icon in the bottom-right corner of Figure 5.29 indicates that if you are
using Firefox as your browser, this example can only be accessed via a server
with http:// protocol. We will explain the reasons in section 5.15.3, Security
Aspects.

NOTE
Free download pdf