在对图片进行灰度色处理时,图片只有一半出现灰度色。代码如下:
grayscale.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>grayscale example</title>
<script src="scripts/modernizr.js" type="text/javascript"></script>
</head>
<body>
<img src="image/2.jpg" id="avatar" title="jeffrey Sambells" alt="My Avatar" />
<script src="scripts/grayscale.js"></script>
</body>
</html>
注:* head中的modernizr.js ,必须放在head中,不能放在body的后面,至于modernizr的下载方法如下连接:*
grayscale.js
function convertToGS(img){
if(!Modernizr.canvas) return;
//存储原始的色彩版
img.color=img.src;
//创建灰度版
img.grayscale=createGSCanvas(img);
//在mouseover/out事件发生时切换图片
img.onmouseover=function(){
// this.src=this.color;
this.src=this.grayscale;
}
img.onmouseout=function(){
// this.src=this.grayscale;
this.src=this.color;
}
img.onmouseout();
}
function createGSCanvas(img){
var canvas=document.createElement("canvas");
canvas.width=img.width;
canvas.height=img.height;
var ctx=canvas.getContext("2d");
ctx.drawImage(img,0,0);
var c=ctx.getImageData(0,0,img.width,img.height);
for(i=0;i<c.height;i++){
for(j=0;j<c.width;j++){
var x=(i*4)*c.height+(j*4);
var r=c.data[x];
var g=c.data[x+1];
var b=c.data[x+2];
c.data[x]=c.data[x+1]=c.data[x+2]=(r+g+b)/3;
}
}
ctx.putImageData(c,0,0,0,0,c.width,c.height);
return canvas.toDataURL();
}
window.onload=function(){
convertToGS(document.getElementById('avatar'));
}
显示如下:
在这里只显示半部分的灰度色,为了显示全部分的灰度色,对grayscale.js中的代码做如下改动,只需要将 “height “改成 “width”即可:
改后的显示如下: