Image Filter Source Code

HTML5 Web and Game Development

image-filter.js

Image Filter Example Declare Variables Load Image, Assign Listener Resize Event Listener Reset Before Filter Image Filter

Overview

Image filter source code uses the HTML5 canvas and JavaScript. Tap buttons. Change the image to all red, green or blue. The JavaScript to filter an image, follows.

Declare Variables

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

Load Image, Assign Listener

function loadImage(){
 
canvas = document.getElementById(
 'cv'
);

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

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)
 }
};

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

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

Resize Event Listener

/**
* Respond to resize
* events.
* @param {EventObject} ev.
*/
function resizeHandler(ev){
 // Save new dimensions.
 nDim = canvas.width;
}

Reset Before Filter

/**
* Function drawReset()
* @param {Number) n:
* Color channel pass
* to drawFilter() after
* image loads
*/
function drawReset(n){
 // Older browsers, switch
 // images to force a reload of
 // the kinnor.
 img.nFilter = null;
 img.src = 'color-blue.png';
 
 img.nFilter = n;
 img.src = 'view-kinnor.jpg';

Image Filter

/**
 Function drawFilter()
 @param {Number} n:
 0: save only the red channel.
 1: save only the green channel.
 2: save only the blue channel.
 */
function drawFilter(n){
 
var aPixels = context.getImageData(
 0, 
 0, 
 nDim,
 nDim
);

var data = aPixels.data;

var intSave = 0;

for(var i = 0; i < data.length; i += 4) {
 
 intSave = data[i+n];
// Red Component
 data[i] = 0;
// Green component
 data[i + 1] = 0; 
// Blue component
 data[i + 2] = 0; 
 data [i + n] = intSave;
// Dont change alpha component.

}
// Display new image
context.putImageData(
 aPixels, 
 0, 
 0
);
}
Learn 3D Programming Learn 3D Programming
Copyright © 2015 Seven Thunder Software. All Rights Reserved.