將圖片以灰色方式顯示的程式碼

admin發表於2017-02-28
方式一:

使用以下CSS程式碼可以實現此效果:

[CSS] 純文字檢視 複製程式碼
img{ 
   -webkit-filter:grayscale(100%); 
   -webkit-filter:grayscale(1); 
   filter:grayscale(100%); 
   filter:gray; }

以上程式碼能夠相容谷歌和IE10以下的瀏覽器,但是不支援火狐和IE9以上的瀏覽器。

方式二:

使用javascript方式,完整程式碼如下:

[HTML] 純文字檢視 複製程式碼
<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<script type="text/javascript"> 
window.onload=function(){
  var imgObj=document.getElementById('theid'); 
  function gray(imgObj){ 
    var canvas = document.createElement('canvas'); 
    var canvasContext = canvas.getContext('2d'); 
    var imgW = imgObj.width; 
    var imgH = imgObj.height; 
    canvas.width = imgW; 
    canvas.height = imgH; 
    canvasContext.drawImage(imgObj, 0, 0); 
    var imgPixels = canvasContext.getImageData(0, 0, imgW, imgH); 
    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; 
      } 
    } 
    canvasContext.putImageData(imgPixels, 0, 0, 0, 0, imgPixels.width, imgPixels.height); 
    return canvas.toDataURL(); 
  } 
  imgObj.src = gray(imgObj); 
}
</script> 
</head> 
<body> 
<img id="theid" src="mytest/demo/tree.jpg"/>
</body>
</html>

以上程式碼能夠相容IE8以上、谷歌和火狐等瀏覽器,算相容性還不錯吧。

那麼我們可以將上述兩種方式綜合以下,程式碼如下:

[HTML] 純文字檢視 複製程式碼
<!DOCTYPE html> 
<html> 
<head> 
<meta charset=" utf-8"> 
<meta name="author" content="http://www.softwhy.com/" /> 
<title>螞蟻部落</title> 
<style type="text/css"> 
img { 
filter:grayscale(100%); 
filter:gray; 
} 
</style> 
<script type="text/javascript">  
window.onload=function(){ 
  var imgObj=document.getElementById('theid');  
  function gray(imgObj){  
    var canvas = document.createElement('canvas');  
    var canvasContext = canvas.getContext('2d');  
    var imgW = imgObj.width;  
    var imgH = imgObj.height;  
    canvas.width = imgW;  
    canvas.height = imgH;  
    canvasContext.drawImage(imgObj, 0, 0);  
    var imgPixels = canvasContext.getImageData(0, 0, imgW, imgH);  
    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;  
      }  
    }  
    canvasContext.putImageData(imgPixels, 0, 0, 0, 0, imgPixels.width, imgPixels.height);  
    return canvas.toDataURL();  
  }  
  imgObj.src = gray(imgObj);  
} 
</script>  
</head>  
<body>  
<img id="theid" src="mytest/demo/tree.jpg"/> 
</body> 
</html>

以上程式碼能夠相容所有的主流瀏覽器,大家可以放心使用。

相關文章