HTML5与jQuery实现渐变绚丽网页图片效果


HTML5与jQuery如何实现渐变绚丽网页图片效果呢?通过HTML5和jQuery创建一个灰度/彩色的实现绚丽渐变效果。在HTML5出现之前,要想实现此类似渐变效果,需要彩图和灰度图像两幅...

        });
        // Grayscale w canvas method
        function grayscale(src){
               var canvas = document.createElement('canvas');
               var ctx = canvas.getContext('2d');
               var imgObj = new Image();
               imgObj.src = src;
               canvas.width = imgObj.width;
               canvas.height = imgObj.height;
               ctx.drawImage(imgObj, 0, 0);
               var imgPixels = ctx.getImageData(0, 0, canvas.width, canvas.height);
               for(var y = 0; y < imgPixels.height; y++){
                       for(var x = 0; x < imgPixels.width; x++){
                               var i = (y * 4) * imgPixels.width + x * 4;
                               var avg = (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);
               return canvas.toDataURL();
    }

// --></mce:script>

使用方法:

  • 引用jQuery.js

jQuery.js 下载地址:http://code.google.com/p/jqueryjs/downloads/list

  • 粘贴以上的代码
  • 设置目标图像(例如.post-img, img, .gallery img等等)
  • 你可以更改动画的速度(例如3000=3秒)

 兼容性:

       此段代码可以工作在任何支持HTML5和Javascript的浏览器里,例如:谷歌Chrome、Safari和Firefox。浏览器不支持HTML5图像将会显示原始的彩色图像。如果本地无法正常工作,你可以将HTML代码放到Web服务器上进行测试。

示例:HTML5灰度渐变(http://webdesignerwall.com/demo/html5-grayscale/)

标签: jQuery