O'Reilly logo

HTML5 Web Application Development By Example Beginner's guide by J.M. Gustafson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Time for action – black and white

Ok, the invert() method was pretty simple. Let's try something a little more challenging, but not much more. We will implement an effect that changes a color image to black and white. Let's implement a toBlackAnWhite() method in the imageEffects object:

function toBlackAndWhite(canvas)
{
    var imageData = getImageData(canvas);
    var data = imageData.data;
    for (var i = 0; i < data.length; i += 4)
    {
        var grayscale = (data[i] * 0.3) +
            (data[i + 1] * .59) +
            (data[i + 2] * .11);
        data[i]   = grayscale;
        data[i+1] = grayscale;
        data[i+2] = grayscale;
    }
    
    putImageData(canvas, imageData);
}

For each pixel, we compute the gray scale value by taking a percentage of each color channel and adding them together; 30 percent red, 59 percent ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required