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. Filter red, green, and blue colors from an image. 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.

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.

Use the source code as it is or consider many unique and creative possibilities with color filtering. Filter portions of different channels, filter the alpha channel, modify channels based on various algorithms for an amazing variety of visual effects.

The example and tutorial include simple responsive Web design. The image resizes based on style sheets, loaded with media queries, when the user resizes a browser window or rotates a mobile device. The style sheets and queries aren't described here. However JavaScript function resizeHandler() saves new image dimensions for use in the filtering source code.

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 of type CanvasRendering2DContext. Number, nDim, represents the image's dimensions along both width and height.

var canvas  = null;

var context  = null;

// Image reference:

var img   = null;

// Default image width & height:
var nDim = Number(300);

Save Canvas and Context References

When the Web page loads, obtain references to the canvas element and the CanvasRendering2DContext. The canvas element's id property, in the Web page's HTML markup, equals cv. Retrieve the CanvasRendering2DContext, from the canvas element, with method getContext(), as follows.

// First obtain the
// canvas reference.
canvas = document.getElementById(
 'cv'
);

// From the canvas
// obtain the
// 2D rendering context.
context = canvas.getContext(
 '2d'
);  

Load and Draw the Image

Next create a new image reference named, img. Prepare an onload event listener which draws an image to the Web page. Within the event listener, call 2D context method drawImage(). Parameters to drawImage() include the top left corner, width and height of the image to display. The top left corner's at X and Y coordinates (0,0). The image's width and height equal (nDim,nDim). Variable nDim represents image dimensions, along both width and height.

After preparing the anonymous onload event listener, assign the path to an image file to the image's src property. Assign the src property after the onload event listener. Therefore the onload event listener is sure to activate when the image loads. 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';

Resize Event

Last assign a resize event listener, as follows. See the entire loadImage() function. Function resizeHandler() simply saves the dimensions of the canvas in response to resize events.

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

The entire resize event listener follows. Function resizeHandler() simply saves the size of the canvas width. CSS3 style sheets, applied with media queries, resize the canvas based on orientation and screen size. Here JavaScript accesses 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 three different color channels. The Reset button displays the full color image without filtering. 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. The second function, drawFilter() processes and displays the filtered image. Function drawReset() calls drawFilter() by means of an anonymous onload event listener.

Function drawReset()

Function drawReset() has one parameter. The parameter indicates which color channel to display. Other color channels receive the value zero, which renders as black.

Variable n is the formal parameter of drawReset(). The signature to drawReset() follows.

function drawReset(n)

First assign parameter n to a property of the current image.

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.

img.onload = function(ev) {...

Third after the image loads, call the 2D context's drawImage() method to display the full color image. Remember number nDim represents the width and height of the image.

context.drawImage(
 this,
 0,
 0,
 nDim,
 nDim
);

Fourth the onload event listener obtains the value of property nFilter. The event object's currentTarget property references our image. Therefore currentTarget.nFilter equals the parameter passed to drawReset(). The following line, within the onload event, retrieves the value of 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 image color channels. The next section demonstrates filtering every pixel of an image within function drawFilter(). The entire drawReset() function follows.

function drawReset(n){

img.nFilter = n;
 
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 with function drawFilter(). The only parameter to drawFilter() is a number representing which color channel to display with the filter. The function signature follows.

function drawFilter(n)

First obtain an array of pixels from the image. 2D context method, getImageData(), returns image data with an array of pixels. Parameters to getImageData() describe a square on the canvas. Method getImageData() copies that square from the canvas to an array of pixels. Parameters to getImageData() include the upper left corner, 0,0, width and height, nDim,nDim. Image data returned represents a square starting at the corner (0,0), with width and height of (nDim, 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 aPixels.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. Save a reference to the array as follows.

var data = aPixels.data;

JavaScript iterates over every pixel, changing each channel except the alpha channel. 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 value of one pixel's color channel. Variable i represents the current pixel. Variable n represents the color channel we're currently keeping.

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. You learned to filter out every color except red, green, or 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 included simple responsive Web design. The image, drawn to the canvas, resizes based on style sheets, loaded with media queries, when the user resizes a browser window or rotates a mobile device. The style sheets and queries aren't described here. However JavaScript function resizeHandler() saves new image dimensions for use in the filtering source code.

Use the source code as it is or consider many unique and creative possibilities with color filtering. Filter portions of different channels, filter the alpha channel, modify channels with algorithms for awesome and unique special effects.

See the image filter source code. See more color for the Web examples.

HTML5 Color Examples

Ad for 3D Marketing Learn 3D Programming Ad
Copyright © 2015 Seven Thunder Software. All Rights Reserved.