HTML and CSS Reference
In-Depth Information
Pushing pixels
One very cool feature of the canvas API is its ability to inter-
rogate individual pixels, something that isn't possible with SVG,
which is vector-based, and not really aimed at pixel-level opera-
tions. You can get every pixel from the 2D context object broken
down into four colour channels: red, green, blue, and the alpha
transparency channel (rgba). For example:
var ctx = document.querySelector('canvas').
¬ getContext('2d'),
img = document.createElement('img');
// wait until the image has loaded to read the data
img.onload = function () {
ctx.drawImage(img, 0, 0);
var pixels = ctx.getImageData(0, 0, img.width,
¬ img.height);
};
The variable pixels is a CanvasPixelArray , which contains the
height , width , and data properties. data is an array of the pixel
data, which is made up as follows
[ r1, g1, b1, a1, r2, g2, b2, a2, r3, g3, b3, a3, ... ]
where r1, g1, b1, a1 makes up the first pixel, r2, g2, b2, a2
makes up the second pixel, and so on. This means that data.
length is the number of pixels captured from the getImageData
(in the previous example this will be the same size as the image)
multiplied by 4, as there are 4 channels to each pixel. Note that
the pixel arrangement in the CanvasPixelArray is from top-left to
bottom-right, going row by row for the area selected.
Since you have access to this data, you can do pixel-level pro-
cessing. So you could create custom image filters for applica-
tions like the image editors shown in Figure 5.2 or perhaps scan
the image for particular colour ranges or even write a web app
that does facial recognition.
Paul Rouget and Tristan Nitot of Mozilla showed of a demo early
in 2009 (see Figure 5.16 ) that uses a video drawn onto a canvas
and injects dynamic content on top of it. As each video frame
is drawn on the canvas, the pixel data is read and searched for
a solid block of white (where the pixel is 255, 255, 255), which
is used as an anchor point to draw another visual element on
NoTE To u s e t h e s o u r c e
of another image in the
drawImage method, it must be
served through http (not a local
file system).
 
 
Search WWH ::




Custom Search