Basic image filters for HTML5 with JavaScript

Basic image filters for HTML5 with JavaScript

Basic image filters for HTML5 with JavaScript

This post demonstrates you how you can create a HTML5 page with JavaScript that will open a picture and apply a basic image filter to it.
You can use the filter from this tutorial, or any other basic image filter. The filter that we use here is an invert filter, therefore all colors in the target picture will be inverted.

Of course HTML5 is new and not yet fully supported by all browsers. I tested it on Windows Phone (7.8 and 8), Android (2.3) and iPhone (5) and it worked on all of them. Internet Explorer supports the canvas element since version 9.

I think it must be because of security reasons, but the code only works on the web server that hosts the image that is loaded.

To see the filter in action, visit this page.

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
		Basic image filters for HTML5 with JavaScript
	<canvas id="myCanvas" width="435" height="486"></canvas>
		// Define our image
		var imageObj = new Image();

		// Add an onload event to the image
		imageObj.onload = function () {

		// Set the image source
		imageObj.src = 'kim.jpg';

		// Our function to draw the image with the filter applied
		function drawImage(imageObj) {
			var canvas = document.getElementById('myCanvas');
			var canvasContext = canvas.getContext('2d');

			// Draw the image on location x 0, y 0 on the canvas
			canvasContext.drawImage(imageObj, 0, 0);

			// Get the image data from location x 0, y 0
			var imageData = canvasContext.getImageData(0, 0, imageObj.width, imageObj.height);

			// Call our filter

			// Put back the image data at location x 0, y 0
			canvasContext.putImageData(imageData, 0, 0);

		// Our invert filter in JavaScript
		function InvertFilter(pixels) {
			// for each ARGB pixel
			for (var i = 0; i < pixels.length; i += 4) {
				// Subtract the pixel from white
				// red
				pixels[i] = 255 - pixels[i];
				// green
				pixels[i + 1] = 255 - pixels[i + 1];
				// blue
				pixels[i + 2] = 255 - pixels[i + 2];
				// alpha
				pixels[i + 3] = pixels[i + 3];


Leave a Reply

Your email address will not be published. Required fields are marked *