Image Filter Tutorial
HTML5 Web Development
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 very simple responsive Web design.
The image redraws to the canvas based on the content area's orientation and dimensions.
The canvas and image are square. Therefore, when the user rotates a mobile
device or resizes the browser window, save just one dimension, nDim
,
representing both width and height.
We need the canvas dimensions in order to filter pixels from the canvas, as well.
Declare Shared Variables
The JavaScript file,
image-filter.js
, declares
six variables named canvas, context, eContent, img, nDim
, and sDim
.
Variable, canvas
, is an HTML5 canvas element.
Variable, img
, is an image element.
Variable, context
, is an HTML5 canvas of type
CanvasRendering2DContext
.
Number, nDim
, represents the image's dimensions along both
width and height. String sDim
represents width and height for
assignment to the canvas' style.
Element, eContent
surrounds the text and canvas area for this project.
var canvas = null; var context = null; var eContent = null; // Image: var img = null; // Default canvas width & height: var nDim = Number(200); var sDim = "200px";
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.
This example assigns an onload event listener just once.
The first time the image's loaded, no filters apply.
However when the image's loaded again in the future,
apply filters. Therefore create a property on
the image called, nFilter
.
Assign the value null
during initialization.
null
simply indicates we want to draw the
image without filters, this first time.
Notice function drawFilter()
activates during the onload event listener,
if nFilter
doesn't equal null.
The section titled Filter the Image
,
explains how drawFilter()
renders different color channels based on
parameter n
.
Call setCanvasDimensions()
to save and assign
the correct canvas dimensions, based on the current browser and orientation.
After preparing the anonymous onload
event listener, and saving the canvas dimensions, we can
assign the image file to the image. 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, not before.
The image filter example
loads file ss-harp.png
, as follows.
img = new Image(); img.nFilter = null; img.onload = function() { context.drawImage( this, 0, 0, nDim, nDim ); var n = ev.currentTarget.nFilter; if(n != null){ drawFilter(n) } }; setCanvasDimensions(); img.src = 'https://code.7thunders.biz/thumbnails/ss-harp.png';
Resize Event
Assign a
resize
event listener,
to the html body tag, as follows.
<body... onresize="resizeHandler()"
The resize event listener
calls setCanvasDimensions()
,
to calculate, save and assign the size
to the canvas.
The resize event listener also calls
function drawReset(null)
.
Parameter null
causes
drawReset()
to draw the
unfiltered image to the canvas.
function resizeHandler(ev){ setCanvasDimensions(); drawReset(null); }
Calculate, Save & Assign Canvas Dimensions
Assign the canvas width and height based on the window's orientation. For landscape; wider than tall, orientation, the canvas uses 40% of the width. For portrait; taller than wide, orientation, the canvas fills 100% of the width.
function setCanvasDimensions(){ // Save display area width,height: // eContent's a div that // surrounds the canvas // and text areas. var nW = Number(eContent.clientWidth); var nH = Number(window.innerHeight); var nXOut = nW; // Landscape: if (nW > nH){ // Canvas fills just 4/10 // of the width: nDim = Number(nW * 0.4); // Canvas floats right: canvas.style.cssFloat = "right"; canvas.style.display = "inline"; } // Portrait: else{ // Canvas fills the full width. nDim = nW; // Canvas doesn't float: canvas.style.cssFloat = "none"; canvas.style.display = "block"; } sDim = new String(nDim + "px"); if(canvas != null){ // Assign width,height: canvas.width = nDim; canvas.height = nDim; // Assign width,height style: canvas.style.width = sDim; canvas.style.height = sDim; } }
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
Three functions accomplish filtering.
Function drawReset()
assigns a value
to the image's nFilter
property,
then activate's the image's onload event listener.
Remember from the previous section
titled, Load and Draw the Image
,
that the image's onload event listener
calls the 2D context's API method drawImage()
and our user defined function drawFilter(n)
,
if n
doesn't equal null
.
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)
Function drawReset()
triggers two calls to the anonymous onload event listener,
assigned in the previous section, titled Load and Draw the Image
.
The first call clears the image. File color-blue.png
is simply a one pixel square blue indexed image.
The second call loads the ss-harp.png
image, of a harp.
Older browsers require two calls to activate the onload event listener.
Newer browsers can skip the first call to load color-blue.png
.
Before loading color-blue.png
, assign the
image's nFilter
property, the value null
.
Before loading ss-harp.png
, assign the
image's nFilter
property, the parameter value n
.
Parameter n
will eventually pass to function
drawFilters()
in order to filter our image.
The entire drawReset()
function follows.
function drawReset(n){ // Older browsers, switch // images to force a reload of // the kinnor. img.nFilter = null; img.src = 'https://7thunders.biz/thumbnails/color-blue.png'; img.nFilter = n; img.src = 'https://code.7thunders.biz/thumbnails/ss-harp.png'; }
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.
Web Development Company
Seven Thunder Software's Web programming skills include HTML5, CSS3, JavaScript, WebGL, GLSL and some PHP with MySQL and Python 3. Web design skills include Web graphics with Photoshop, animation with After Effects and 3ds Max.