HTML5 Canvas tag for Creating CSS-based Black & White Image Effects

Marco Lisci has written a tutorial on creating a black and white image effect using the HTML5 Canvas tag. The heart of his tutorial is using getImageData() and looping through the red, green, blue, and alpha values of each pixel to change it's luminance formula: red x 0.3 + green x 0.59 + blue x […]

Marco Lisci has written a tutorial on creating a black and white image effect using the HTML5 Canvas tag. The heart of his tutorial is using getImageData() and looping through the red, green, blue, and alpha values of each pixel to change it's luminance formula: red x 0.3 + green x 0.59 + blue x 0.11. This formula calculates the luminance of a color as it's perceived by the human eye, so the green channel has more importance than the red and the blue.

<script type="text/javascript">
	var imgd = context.getImageData(0, 0, 500, 300);
	var pix = imgd.data;
	for (var i = 0, n = pix.length; i < n; i +="" 4) {
	var grayscale ="" pix[i  ] * .3 + pix[i+1] * .59 + pix[i+2] * .11;
	pix[i  ] ="" grayscale; 	// red
	pix[i+1] ="" grayscale; 	// green
	pix[i+2] ="" grayscale; 	// blue
	// alpha
	}
	context.putimagedata(imgd, 0, 0);
</script>

"The new canvas tag in HTML5 is known for its illustration power. It's basically an empty element on which you can write and sketch using Javascript. But there's a hidden power: image manipulation. With canvas you can perform operations on pixel based artworks. You can write a new image pixel by pixel or import an image in the canvas and modify it as you need."


<img id="canvasSource" src="images/canvas.jpg" alt="Canvas Source" / />

<canvas id="area" width="500" height="300">
</canvas>


<script type="text/javascript">
	window.onload = function() {
	var canvas = document.getElementById("area");
	var context = canvas.getContext("2d");
	var image = document.getElementById("canvasSource");
	context.drawImage(image, 0, 0);
	};
</script>

More Info: TML5 Canvas Image Effects: Black & White

[Source]