HTML5與jQuery實(shí)現(xiàn)漸變絢麗網(wǎng)頁圖片效果
Posted on 2012-04-15 16:37 zljpp 閱讀(242) 評(píng)論(0) 編輯 收藏HTML5與jQuery如何實(shí)現(xiàn)漸變絢麗網(wǎng)頁圖片效果呢?通過HTML5和jQuery創(chuàng)建一個(gè)灰度/彩色的實(shí)現(xiàn)絢麗漸變效果。在HTML5出現(xiàn)之前,要想實(shí)現(xiàn)此類似漸變效果,需要彩圖和灰度圖像兩幅圖片,利用制圖工具實(shí)現(xiàn)漸變圖片效果。現(xiàn)在HTML5讓開發(fā)者通過HTML5與jQuery實(shí)現(xiàn)漸變絢麗網(wǎng)頁圖片效果。
HTML 5和jQuery動(dòng)態(tài)轉(zhuǎn)換任意一張彩色圖像為灰度顯示展示。
通過HTML5和jQuery向你展示如何創(chuàng)建一個(gè)灰度/彩色圖像的鼠標(biāo)懸浮效果。在HTML5出現(xiàn)前,實(shí)現(xiàn)這個(gè)效果需要兩幅圖像,彩色的圖像和灰度的圖像版本版本?,F(xiàn)在HTML5讓開發(fā)者創(chuàng)建這個(gè)效果更加容易和高效,因?yàn)樵紙D像會(huì)直接生成灰度圖像。
jQuery代碼:
下面的jQuery代碼會(huì)找尋網(wǎng)頁中的圖像生成灰度的圖像版本,直接顯示在瀏覽器中。當(dāng)鼠標(biāo)懸浮在圖像上,代碼會(huì)把灰度圖像漸變?yōu)椴噬珗D像。
<mce:script type="text/javascript"><!--
// On window load. This waits until images have loaded which is essential
$(window).load(function(){
// Fade in images so there isn't a color "pop" document load and then on window load
$(".item img").fadeIn(500);
// clone image
$('.item img').each(function(){
var el = $(this);
el.css({"position":"absolute"}).wrap("<div class='img_wrapper' mce_>").clone().addClass('img_grayscale').css({"position":"absolute","z-index":"998","opacity":"0"}).insertBefore(el).queue(function(){
var el = $(this);
el.parent().css({"width":this.width,"height":this.height});
el.dequeue();
});
this.src = grayscale(this.src);
});
// Fade image
$('.item img').mouseover(function(){
$(this).parent().find('img:first').stop().animate({opacity:1}, 1000);
})
$('.img_grayscale').mouseout(function(){
$(this).stop().animate({opacity:0}, 1000);
});
});
// 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
- 粘貼以上的代碼
- 設(shè)置目標(biāo)圖像(例如.post-img, img, .gallery img等等)
- 你可以更改動(dòng)畫的速度(例如3000=3秒)
兼容性:
此段代碼可以工作在任何支持HTML5和Javascript的瀏覽器里,例如:谷歌Chrome、Safari和Firefox。瀏覽器不支持HTML5圖像將會(huì)顯示原始的彩色圖像。如果本地?zé)o法正常工作,你可以將HTML代碼放到Web服務(wù)器上進(jìn)行測(cè)試。
示例:HTML5灰度漸變(http://webdesignerwall.com/demo/html5-grayscale/)