HTML5 Guidelines for Web Developers

(coco) #1

146 Chapter 5—Canvas


Figure 5.29 Color manipulation with “getImageData()” and “putImageData()”

For converting the color to shades of gray, the documentation of the free, image-
editing program GIMP offers three formulae in the chapter Desaturate (see the
web link http://docs.gimp.org/en/gimp-tool-desaturate.html) with which you
can calculate the shade of gray via Lightness, Luminosity, or average lightness
(Average). If we implement these calculations with JavaScript, we get our first
three color filters:

var grayLightness = function(r,g,b,a) {
var val = parseInt(
(Math.max(r,g,b)+Math.min(r,g,b))*0.5
);
return [val,val,val,a];
};

var grayLuminosity = function(r,g,b,a) {
var val = parseInt(
(r*0.21)+(g*0.71)+(b*0.07)
);
return [val,val,val,a];
};

var grayAverage = function(r,g,b,a) {
var val = parseInt(
Free download pdf