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

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.onload = function() {
 context.drawImage(
  this,
  0,
  0,
  nDim,
  nDim
 );
};

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){

 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';

}

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

See HTML5 Color Palette Examples

Copyright © 2015 Seven Thunder Software. All Rights Reserved.