JQuery grayscale images turn colored on hover


/ Published in: jQuery
Save to your folder(s)

Works like a charm. Read manual on site. For use with Worpdress, replace $ with jQuery.


Copy this code and paste it in your HTML
  1. <script src="jquery.min.js" type="text/javascript"></script>
  2. <script type="text/javascript">
  3.  
  4. // On window load. This waits until images have loaded which is essential
  5. $(window).load(function(){
  6.  
  7. // Fade in images so there isn't a color "pop" document load and then on window load
  8. $(".item img").fadeIn(500);
  9.  
  10. // clone image
  11. $('.item img').each(function(){
  12. var el = $(this);
  13. el.css({"position":"absolute"}).wrap("<div class='img_wrapper' style='display: inline-block'>").clone().addClass('img_grayscale').css({"position":"absolute","z-index":"998","opacity":"0"}).insertBefore(el).queue(function(){
  14. var el = $(this);
  15. el.parent().css({"width":this.width,"height":this.height});
  16. el.dequeue();
  17. });
  18. this.src = grayscale(this.src);
  19. });
  20.  
  21. // Fade image
  22. $('.item img').mouseover(function(){
  23. $(this).parent().find('img:first').stop().animate({opacity:1}, 1000);
  24. })
  25. $('.img_grayscale').mouseout(function(){
  26. $(this).stop().animate({opacity:0}, 1000);
  27. });
  28. });
  29.  
  30. // Grayscale w canvas method
  31. function grayscale(src){
  32. var canvas = document.createElement('canvas');
  33. var ctx = canvas.getContext('2d');
  34. var imgObj = new Image();
  35. imgObj.src = src;
  36. canvas.width = imgObj.width;
  37. canvas.height = imgObj.height;
  38. ctx.drawImage(imgObj, 0, 0);
  39. var imgPixels = ctx.getImageData(0, 0, canvas.width, canvas.height);
  40. for(var y = 0; y < imgPixels.height; y++){
  41. for(var x = 0; x < imgPixels.width; x++){
  42. var i = (y * 4) * imgPixels.width + x * 4;
  43. var avg = (imgPixels.data[i] + imgPixels.data[i + 1] + imgPixels.data[i + 2]) / 3;
  44. imgPixels.data[i] = avg;
  45. imgPixels.data[i + 1] = avg;
  46. imgPixels.data[i + 2] = avg;
  47. }
  48. }
  49. ctx.putImageData(imgPixels, 0, 0, 0, 0, imgPixels.width, imgPixels.height);
  50. return canvas.toDataURL();
  51. }
  52.  
  53. </script>

URL: http://webdesignerwall.com/tutorials/html5-grayscale-image-hover

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.