Image Filter Tutorial

HTML5 Web Development

Image Filter Example Image Filter Source Code Introduction Load and Draw the Image Resize Event Filter Functions Filter the Image Summary

Introduction

This short tutorial explains how to implement an image filter with HTML5. Filters include red, green, and blue. Select the Red button to see just the red channel. Select the Blue button to see just the blue channel. Select the Green button to see just the green channel.

The example and tutorial include responsive Web design, for the image. Styles, not covered here, resize the image based on device orientation, browser resize events, or screen width. JavaScript, in this tutorial, saves the scaled image dimensions in response to resize events. For example, if the user rotates a mobile phone, the image scales down or up.

Declare Shared Variables

The JavaScript file, image-filter.js, declares four variables named canvas, context, img, and nDim. Variable, canvas, references an HTML5 canvas element. Variable, img, references an image element. Variable, context, references an HTML5 canvas CanvasRendering2DContext. Number, nDim, represents the image's dimensions including both width and height.

var canvas  = null;
var context  = null;
// Image reference:
var img   = null;
// Default image width & height:
var nDim = Number(300);

Load Image, Assign Event Listener

When the Web page loads, obtain references to the canvas element and the CanvasRendering2DContext. Retrieve the CanvasRendering2DContext with method getContext(), as follows.

canvas = document.getElementById(
 'cv'
);

context = canvas.getContext(
 '2d'
);  

Next create a new image reference named, img. Create an onload function which draws an image to the Web page. The top, left corner's at coordinates (0,0). The width and height equal (nDim,nDim). Variable nDim represents the dimensions, along both width and height, of the image. After preparing the onload event listener, assign the path to an image file to the image's src property. The image filter example loads file view-kinnor.jpg, as follows.

img = new Image();

img.onload = function() {
 context.drawImage(
  this,
  0,
  0,
  nDim,
  nDim
 );
};

img.src = 'view-kinnor.jpg';

Last assign a resize event listener, as follows. See the entire loadImage() function. Function resizeHandler() simply adjusts variable, nDim, up or down based on the size of the canvas. The resize event handler's covered next.

window.addEventListener(
 'resize',
 function (e) {
  resizeHandler(ev);
 },
 false
);  
} 

Resize Event

The entire resize event listener follows. Function resizeHandler() simply saves the size of the canvas width. CSS3 styles with media queries, resize the canvas based on orientation and screen size. Here JavaScript captures the resized canvas and saves the width.

function resizeHandler(ev){
 // Save new dimensions.
 nDim = canvas.width;
}

Filter the Image

The image filter example includes four buttons. Tap the buttons to filter based on color channel, or reset the image. The HTML markup for the four buttons follows. Notice all four buttons call function drawReset(). The parameter for the red filter equals zero. The parameter for the green filter equals one. The parameter for the blue filter equals two. The parameter for the reset function equals null.

<button 
onclick="javascript:drawReset(0)">
 Red
</button>

<button 
onclick="javascript:drawReset(1)">
 Green
</button>

<button 
onclick="javascript:drawReset(2)">
 Blue
</button>

<button 
onclick="javascript:drawReset(null)">
 Reset
</button>

Filter Functions

Two functions accomplish filtering. The first function, drawReset(), resets the image to default values. Function drawReset() passes it's parameter to the second function, drawFilter(), through an event object. After the default image loads, then call drawFilter() to filter the image.

Function drawReset() has one parameter. The parameter indicates which color channel to keep. All other channels will be assigned black.

First assign the number passed as a parameter to drawReset(), to a property of the current image. Variable n is the formal parameter of drawReset(). The signature to drawReset() follows.

function drawReset(n)

We want to access the parameter to drawReset(), after the image's onload event activates. Create property nFilter on the image reference. Assign parameter n to property nFilter. Property nFilter represents the color channel to display with the filter.

img.nFilter = n;

Second prepare an onload event listener for the image. After the image loads, the onload event listener obtains the number which represents the color filter. The event object's currentTarget property references our image. Therefore currentTarget.nFilter equals the parameter passed to drawReset() and the image's nFilter property. The following line, within the onload event, retrieves property nFilter from the example project's image.

var n = ev.currentTarget.nFilter;

If n doesn't equal null then call drawFilter(n). Function drawFilter() transforms the image color channels on display. The next section demonstrates filtering every pixel in an image.

 img.onload = function(ev) {
 context.drawImage(
  this,
  0,
  0,
  nDim,
  nDim
 );
 
 var n = ev.currentTarget.nFilter;
 if(n != null){
  drawFilter(n)
 }
 };
 img.src = 'view-kinnor.jpg';

Filter the Image

This section covers the most important part of the tutorial. Filter ever pixel in the image. First obtain an array of pixels from the image. 2D context method, getImageData(), returns image data with an array of pixels. Parameters include the upper left corner coordinates, (0,0), with the width and height, (nDim,nDim). Image data returned represents a square from within the image, starting at corner (0,0), with width and height of nDim.

This tutorial filters the entire image, however developers can filter just sections of an image. Change the upper left corner, width, or height coordinates. The following listing saves an array of pixels which cover the entire image.

var aPixels = context.getImageData(
 0, 
 0, 
 nDim,
 nDim
);

The actual array of data is saved to property data. Every four values represent one pixel. The first value represents the red channel. The second value represents the blue channel. The third value represents the green channel. The fourth value represents the alpha channel.

var data = aPixels.data;

JavaScript iterates over every pixel, changing each channel except the alpha channel. A color channel represents one hue from an image. Most digital images include red, green, and blue channels. Some images also include an alpha channel which represents the amount of transparency per pixel. Method getImageData() retrieves four channels, including alpha. The default value for the alpha channel equals 1.0, opaque, or not transparent.

This tutorial does not change the alpha channel, however consider modifying the alpha value for some fascinating effects.

As JavaScript iterates over the array of pixels, each channel, except the alpha channel, receives the value zero. Zero represents black. However before assigning zero to every hue, save the color channel we're keeping for the filter.

A for loop iterates over every pixel in the array named, data. The for loop skips every four entries, representing red, green, blue, and alpha values. The following line causes variable i to process from 0,4,8... to data.length.

for(var i = 0; i < data.length; i += 4){...}

Within the for loop, first save the channel we want to keep. Remember the HTML buttons pass parameter n as zero for red, one for green, and two for blue. The following line saves the correct color channel.

intSave = data[i+n];

Second assign zero, or black, to the red, green, and blue channels, within the for loop, as follows.

// Red Component
 data[i] = 0;
// Green component
 data[i + 1] = 0; 
// Blue component
 data[i + 2] = 0;

Third reassign the saved color channel as follows.

data [i + n] = intSave;

Outside of the for loop, copy the modified pixels back to our image as follows.

context.putImageData(
 aPixels, 
 0, 
 0
);

See the entire image filter drawFilter() function.

Summary

This short tutorial explained how to implement an image filter with HTML5. Filters include red, green, and blue. Select the Red button to see just the red channel. Select the Blue button to see just the blue channel. Select the Green button to see just the green channel.

The example and tutorial include responsive Web design, for the image. Styles, not covered here, resize the image based on device orientation, browser resize events, or screen width. JavaScript, in this tutorial, saves the scaled image dimensions in response to resize events. For example, if the user rotates a mobile phone, the image scales down or up. See the image filter source code. See more color for the Web examples.

HTML5 Color Examples

Copyright © 2015 Seven Thunder Software. All Rights Reserved.