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 the
alternative drawing SVG technology. You can get every pixel
from the 2D context object, broken down into four colour chan-
nels: 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's 4 bits to each pixel.
Since you have access to this data, you can do pixel-level pro-
cessing. So you could create custom image fi lters 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 on to
a canvas and injects dynamic content in to the image seen on
the canvas. As each video frame is drawn on to 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 to the canvas. In Figure 5.16,
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
fi fi le is y is t le m ) a n d fi is r le is t r fi c t le d b y
the same origin rule (it must be
from the same domain).
Search WWH ::

Custom Search