Image Filter Source Code

HTML5 Code Modifies the Red Channel of an Image

Red Image Filter Example Red Image Filter Tutorial RGB Image Filter Example Image Filter Tutorial (All Colors) Introduction HTML5 Markup JavaScript

Introduction

This page includes the HTML5 markup and JavaScript source code to filter out the red channel from an image, with the HTML5 canvas element. A graphic, drawn to the canvas, turns red when you tap the canvas. See the Image Filter Example, with tutorial and source code, to filter any color channel, including green and blue.

HTML5 Markup

<canvas 
 id="cv" 
 width="300" 
 height="300"  
 onclick="drawRedFilter()"
>

Your browser doesn't 
support the canvas element.

</canvas>
				
<div>
		
<button 
 onclick="javascript:drawRedFilter()"
>

Red Filter

</button>

<button  
 onclick="javascript:loadImage()"
>

Reset

</button>

</div>	

JavaScript

var canvas = null;

var context = null;

// Image reference:
var img = null;

// Width and height 
// image dimensions:
var N_DIM = new Number(
 300
);

/**
* function loadGame()
* obtains references from the HTML 
* Web page, then calls loadImage().
*/
function loadGame(){
canvas = document.getElementById(
 'cv'
);

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

/**
* function loadImage()
* loads and draws a new 
* copy of the Image. 
*/
function loadImage(){

img = new Image();

img.onload = function() {

context.drawImage(
 this,
 0,
 0,
 N_DIM,
 N_DIM
 );
};

img.src = 'butterfly-fish.jpg';

}
/**
 * function drawRedFilter() 
 * obtains an Array of data,
 * composed of a series
 * of separate numbers 
 * representing
 * R,G,B,A.
 * Then zeros out the 
 * green and blue values.
 */
function drawRedFilter(){
   
var aPixels = context.getImageData(
 0, 
 0, 
 N_DIM, 
 N_DIM
);

var data = aPixels.data;

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

// Green component
data[i + 1] = 0; 

// Blue component
data[i + 2] = 0;      
}

// Display new image
context.putImageData(
 aPixels, 
 0, 
 0
 );
 
}

Summary

This page included the HTML5 markup and JavaScript source code to filter out an images pixel data red channel, with the HTML5 canvas element. See the Image Filter Example, with tutorial and source code, to filter any color channel, including green and blue.

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