canvas getImageData函数在chrome

时间:2017-05-28 09:44:23

标签: javascript canvas html5-canvas

此代码段基于 CANVAS ,它确实将图像转换为灰度,然后在图像上应用了一些颜色叠加,它在 Mozilla Firefox 上正常工作但不在铬。在Chrome中它会给我一个错误信息。

  

未捕获DOMException:无法执行'getImageData'   'CanvasRenderingContext2D':画布已经被污染了   跨性别数据。


请给我一些解决方案,
提前谢谢。

  <script>
    function tintImage(imgElement, tintColor) {
      // create hidden canvas (using image dimensions)
      var canvas = document.createElement("canvas");
      canvas.width = imgElement.offsetWidth;
      canvas.height = imgElement.offsetHeight;

      var ctx = canvas.getContext("2d");
      ctx.drawImage(imgElement, 0, 0);
      var map = ctx.getImageData(0, 0, 1000, 1000);
      var imdata = map.data;

      // convert image to grayscale
      var r, g, b, avg;
      for (var p = 0, len = imdata.length; p < len; p += 4) {
        r = imdata[p];
        g = imdata[p + 1];
        b = imdata[p + 2];

        avg = Math.floor((r + g + b) / 3);

        imdata[p] = imdata[p + 1] = imdata[p + 2] = avg;
      }

      ctx.putImageData(map, 0, 0);

      // overlay filled rectangle using lighter composition
      ctx.globalCompositeOperation = "overlay";
      ctx.globalAlpha = 0.5;
      ctx.fillStyle = tintColor;
      ctx.fillRect(0, 0, canvas.width, canvas.height);

      // replace image source with canvas data
      imgElement.src = canvas.toDataURL();
    }



    /// some buttons for testing the demo



    var redBtt = document.createElement("button");
    redBtt.appendChild(document.createTextNode("Red"));
    redBtt.onclick = function() {
      tintImage(
        document.getElementById('myImage'),
        "#d60000"
      );
    }
    document.body.appendChild(redBtt);


    var grnBtt = document.createElement("button");
    grnBtt.appendChild(document.createTextNode("Green"));
    grnBtt.onclick = function() {
      tintImage(
        document.getElementById('myImage'),
        "#000000"
      );
    }
    document.body.appendChild(grnBtt);


    var bluBtt = document.createElement("button");
    bluBtt.appendChild(document.createTextNode("Blue"));
    bluBtt.onclick = function() {
      tintImage(
        document.getElementById('myImage'),
        "#050c8c"
      );
    }
    document.body.appendChild(bluBtt);

    </script>
<img id='myImage' src="https://yt3.ggpht.com/-gjxoCu8Fu3c/AAAAAAAAAAI/AAAAAAAAAAA/Uji17DdykF4/s900-c-k-no-mo-rj-c0xffffff/photo.jpg" />

<br/>

1 个答案:

答案 0 :(得分:0)

这比getImageData函数Cross Origin Resource Sharing (CORS)问题更多。

要解决此问题,您需要...

<强>ꜰɪʀꜱᴛ

为图像元素设置crossorigin属性,如此...

<img crossorigin="anonymous" src="www.example.com/myImage.png"> 

<强>ꜱᴇᴄᴏɴᴅ

在本地服务器或支持跨源资源共享的网站(即imgur.com)上托管图像