JQuery灰度图像在悬停时变为彩色

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JQuery灰度图像在悬停时变为彩色相关的知识,希望对你有一定的参考价值。

Works like a charm. Read manual on site. For use with Worpdress, replace $ with jQuery.
  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>

以上是关于JQuery灰度图像在悬停时变为彩色的主要内容,如果未能解决你的问题,请参考以下文章

在剪贴蒙版内悬停时从灰度更改为彩色

将精灵从灰度着色为彩色

带有CSS的图像灰度和鼠标悬停时重新着色?

Matlab图像处理彩色图像转换为灰度图像(初学必看)

彩色图像转变为灰度图像的matlab的程序代码是啥?

使用悬停更改 DIV 颜色并单击 JQuery