HTML and CSS Reference
var v = 0.2126 * r + 0.7152 * g + 0.0722 * b ;
d [ i ] = d [ i + 1 ] = d [ i + 2 ] = v
return pixels ;
The grayscale function in listing 8.18 is adapted from the HTML Rocks article on image
filters; see www.html5rocks.com/en/tutorials/canvas/imagefilters/ for more details.
With the complex math all safely hidden in a general-purpose function, all that remains is
to apply it to the canvas. Listing 8.19 shows how you'd call the grayscale() function
from within your draw() function. For this to work, you need to declare a variable
grayed alongside the framed one you created in listing 8.14 and set it to an initial value
of false .
Listing 8.19. index.html—Use the grayscale() function within draw()
The getImageData() method will trigger a security error if you access the example
from a file:// URL. If you run into any problems, try accessing the file using a local
web server. In Chrome there's also a bug that causes a security violation when
getImageData() is called after an SVG image has been drawn on the canvas. Check