功能没有在Chrome中运行,但在IE和Firefox中完全可以

时间:2014-02-18 17:17:11

标签: javascript google-chrome web

我有一个功能,其任务是进入网页并将图像转换为灰度。 它完全适用于IE和Firefox。 但是,它不能在Chrome中运行:图像保持彩色;它们没有变成灰度。

任何人都知道为什么会这样?

<html>
<head>

<script>

function transf_images(){
  var theImages = document.getElementsByTagName("img");

  for (var i=0; i <theImages.length; i++){
    var newImage=new Image();

    /*
    * Store the current index as the new image's id
    * since the onload function is async
    */
    newImage.id = i;        
    newImage.onload=function(){

      // Retrieve the correct index
      var i = this.id;

      // Get width and height
      var theWidth = theImages[i].width;
      var theHeight = theImages[i].height;

      // create a temporary canvas to put the original image
      var tempCanvas=document.createElement("canvas");
      var tempCtx=tempCanvas.getContext("2d");

      // Set width and height of the canvas
      tempCanvas.width = theWidth;
      tempCanvas.height = theHeight;

      // Draw the original in a temporary canvas
      tempCtx.drawImage(this, 0, 0, theWidth, theHeight);

      // pull the entire image into an array of pixel data
      var imageData = tempCtx.getImageData(0, 0, theWidth, theHeight);


      // CHANGE OF THE PIXEL COLOR

     var aux = new Array(3);

         for (var y = 0; y < theHeight; y ++) {
           for (var x = 0; x < theWidth; x ++) {
                 offset = ((y*(theWidth*4)) + (x*4));

                 aux[0] = imageData.data[offset + 0];
                 aux[1] = imageData.data[offset + 1];
                 aux[2] = imageData.data[offset + 2];

                 var gray =  (aux[0]+aux[1]+aux[2])/3;

                imageData.data[offset + 0] = Math.round(gray);
                imageData.data[offset + 1] = Math.round(gray);
                imageData.data[offset + 2] = Math.round(gray);
                imageData.data[offset + 3] = imageData.data[offset + 3]; 
           } //for
         } //for
         // final of the CHANGE OF THE PIXEL COLOR

      // put the altered data back on the canvas  
      tempCtx.putImageData(imageData,0,0);

      // Set the original image
      theImages[i].src = tempCanvas.toDataURL();

    }    // newImage.onload
    newImage.src = theImages[i].src;    

  }  //for  loop - for the image array
}  //function
</script>

</head>

<body onLoad="transf_images();">
    <p>First Image</p>
    <img src="imagens_250x180/rosa.jpg" name="image0" width=250 height=180 ><br/>
    <p>Second Image</p>
    <img src="imagens_250x180/ricardina.jpg" name="image1" width=250 height=180 >
     <p>Third Image</p>
    <img src="imagens_250x180/manaus.jpg" name="image1" width=250 height=180 >
</body>
</html>

2 个答案:

答案 0 :(得分:2)

也许你可以使用css过滤器?

img {  
    -webkit-filter: grayscale(1); /* Webkit */  
    filter: gray; /* IE6-9 */  
    filter: grayscale(1); /* W3C */  
}  

另请参阅此demo

答案 1 :(得分:0)

我是问题的作者

我尝试了其他的消化,但都没有解决。

然后,我确实将代码放在网上(在服务器中)并且它有效。 现在,它完全可以在Chrome中使用。

感谢sugestions