The purpose of this example is to show you how to create a mouse suspension effect of a grayscale/color image using HTML5 and jQuery. Before HTML5 appeared, achieving this effect required two images, colored and grayscale versions. HTML5 now makes creating this effect easier and more efficient, as grey images will be generated directly from the original file. I hope you will find this script useful in designs such as display cabinets or photo albums.
The following jQuery code will look for the target image and generate a grayscale version. When the mouse is suspended on the image, the code will gradually change the grayscale image to color.
- <mce:scriptsrc=jquery.min.jsmce_src=jquery.min.jstype=text/javascript></mce:script>
- <mce:scripttype=text/javascript><!--
- //Onwindowload.Thiswaitsuntilimageshaveloaded whichissential
- $(window).load(function(){
- //Fadeinimagessothereisn'tacolorpopdocumentload and thenonwindowload
- $(.itemimg).fadeIn(500);
- //cloneimage
- $('.itemimg').each(function(){
- varel=$(this);
- el.css({position:absolute}).wrap(<divclass='img_wrapper'style=display:inline-blockmce_style=display:inline-block>).clone().addClass('img_grayscale').css({position:absolute,z-index:998,opacity:0}).insertBefore(el).queue(function(){
- varel=$(this);
- el.parent().css({width:this.width,height:this.height});
- el.dequeue();
- });
- this.src=grayscale(this.src);
- });
- //Fadeimage
- $('.itemimg').mouseover(function(){
- $(this).parent().find('img:first').stop().animate({opacity:1},1000);
- })
- $('.img_grayscale').mouseout(function(){
- $(this).stop().animate({opacity:0},1000);
- });
- });
- //Grayscalewcanvasmethod
- functiongrayscale(src){
- varcanvas=document.createElement('canvas');
- varctx=canvas.getContext('2d');
- varimgObj=newImage();
- imgObj.src=src;
- canvas.width=imgObj.width;
- canvas.height=imgObj.height;
- ctx.drawImage(imgObj,0,0);
- varimgPixels=ctx.getImageData(0,0,canvas.width,canvas.height);
- for(vary=0;y<imgPixels.height;y++){
- for(varx=0;x<imgPixels.width;x++){
- vari=(y*4)*imgPixels.width+x*4;
- varavg=(imgPixels.data[i]+imgPixels.data[i+1]+imgPixels.data[i+2])/3;
- imgPixels.data[i]=avg;
- imgPixels.data[i+1]=avg;
- imgPixels.data[i+2]=avg;
- }
- }
- ctx.putImageData(imgPixels,0,0,0,0,imgPixels.width,imgPixels.height);
- returncanvas.toDataURL();
- }
- //--></mce:script>
How to use * Quote jQuery.js
* Paste the above code
* Set the target image (for example .post-img, img, .gallery img, etc.)
* You can change the speed of the animation (for example, 1000=1 second)
compatibility Can work on any browser that supports HTML5 and Javascript, such as Chrome, Safari, and Firefox. If the browser does not support HTML5, this effect will fall back to the original color image. Note: If the local file does not work on Firefox and Chrome, you must put the HTML code on a web server.