In this tutorial I will write a Javascript function that will add a transition hover effect from greyscale to color on any image you want, all this stuff is now possible thanks to the new canvas element in HTML5, no need to upload two images or doing it server side.
Here's a running Demo, just pass the mouse over the images :
HTML Markup :
The HTML markup is strait forward, just add the css class name ‘colorup’ to any image you want.
<img src="imgs/sample2.jpg" class="colorup" />
The JavaScript part :
The JavaScript function need to be started after the document load event to ensure that all images are loaded and the document is ready :
$(window).load(function () {
$('.colorup').each(function () {
var curImg = $(this).wrap('<span />');
var newImg = curImg.clone().css({ "position": "absolute", "z-index": "98","opacity":"0" }).insertBefore(curImg);
newImg.attr("src", grayImage(this));
newImg.addClass('grayscaled').animate({ opacity: 1 }, 1000);
});
// Fade the image in and out
$('.grayscaled').mouseover(function () {
$(this).stop().animate({ opacity: 0 }, 500);
})
$('.grayscaled').mouseout(function () {
$(this).stop().animate({ opacity: 1 }, 500);
});
});
The following function will take the original image and paint it on a HTML5 canvas element, loop through the image pixels, update the RGB (red, green and blue) values to generate a grayscale version, it will return to the previous function a DataURL wich contain the greyscaled image data :
// this function return the DataURL of the grayscaled image
function grayImage(image) {
// get the canvas's 2d context
var myCnv = document.createElement("canvas");
var myCtx = myCnv.getContext("2d");
// Copy the image on the canvas
myCnv.width = image.width;
myCnv.height = image.height;
myCtx.drawImage(image, 0, 0);
// read image bytes
var imgData = myCtx.getImageData(0, 0, myCnv.width, myCnv.height);
// create grayscale image
for (var y = 0; y < imgData.height; y++) {
for (var x = 0; x < imgData.width; x++) {
// the Pixel position
var pos = (y * 4) * imgData.width + (x * 4);
// Compute and apply the average color
// The 4th byte represents the alpha, we will not change it.
imgData.data[pos] = imgData.data[pos + 1] = imgData.data[pos + 2] = imgData.data[pos] * 0.32 + imgData.data[pos + 1] * 0.48 + imgData.data[pos + 2] * 0.2
}
}
myCtx.putImageData(imgData, 0, 0, 0, 0, imgData.width, imgData.height);
return myCnv.toDataURL();
}
The grayscale computation can be altered to create other effects instead of the grayscale: we can solarize the image, create a sepia tone, a negative image effect...
EDIT : after writing this tutorial, I enhanced the code and made up a jQuery plugin
Check it out :
Image Color-Up (
Live demo page )
I'd love to hear your thoughts and ideas, so feel free to comment.
And if you like this tutorial, please Share it.