HTML5 Guidelines for Web Developers

(coco) #1

144 Chapter 5—Canvas


Figure 5.28 Modifying colors in the “CanvasPixelArray”

You can initialize an empty ImageData object directly via the method
createImageData(). Width and height correspond to the arguments sw/sh or the
dimensions of an ImageData object passed in the call. In both cases, all pixels of
the CanvasPixelArray are set to transparent/black, which is rgba(0,0,0,0):

context.createImageData(sw, sh)
context.createImageData(imagedata)

So we could also create the 2 × 2 pixel modified canvas of Figure 5.28 directly via
createImageData() and draw it via putImageData():

var imagedata = context.createImageData(2,2);
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);
}
context.putImageData(imagedata,0,0);

That’s it for now on dry CanvasPixelArray theory. In practice, things get much
more exciting: With getImageData(), putImageData(), createImageData(), and a
Free download pdf