从画布图像中获取像素值,CORS限制

时间:2014-11-07 10:02:24

标签: javascript html5 canvas cors

很明显这对某些浏览器来说是一个很大的问题,因为当你尝试从画布图像中获取像素数据时,我搜索了一些关于“画布被污染”的mumbo jumbo,如:

var pix = context.getImageData(3200,3200,1,1).data;

到目前为止,我已经尝试过crossorigin =''和XMLHttpRequest,但我仍然遇到同样的问题。然后,我不知道我是否实施了错误,只是做了一个菜鸟。如果有人能帮我解决这个问题,我将不胜感激。挣扎了1.5天,然后转向论坛问题作为最后的手段。请注意,我的代码适用于Firefox浏览器,但不适用于Chrome ...我的实现具有跨浏览器功能至关重要。这是我从主项目中提取的一个小javascript代码,用于隔离,并尝试修复问题:

<html>
<head>
  </head>
    <body>
      <canvas id="myCanvas" width="6029" height="6968"></canvas>
      <script>  <!-- Javascript section-->

      var canvas = document.getElementById('myCanvas'); //get canvas from html code via identity

      var context = canvas.getContext('2d');    //get context of canvas
      var imageObj = new Image();       //create image object 
      imageObj.src = 'gauteng.png'; //define the image of the image object


      imageObj.onload = function()  //trigger function after the image has loaded in image object
      {
        try
        {
          context.drawImage(imageObj,0,0);  //draw the image object onto context of canvas

          var imgd = context.getImageData(3200,3200,1,1);   //get pixel at x coord 3200, and y coord 3200
          var pix = imgd.data;  //get the RGB values from pixel

          // print out RGB values with alert            
          alert('R val= '+pix[0].toString()+ "\r\nG val= "+pix[1].toString()+"\r\nB val= "+pix[2].toString());

        }
        catch(err)  //display error message if exception is thrown
        {
          alert(err.toString());
        }
     };

     </script>  
  </body>
</html>

我还可以包含我的XMLHttpRequest方法:

imageObj.onload = function() {

    try
    {
        var inputFile = new XMLHttpRequest(); 
        inputFile.open('get', 'gauteng.png', true); //open example file

        inputFile.onreadystatechange = function()
        {
            if(inputFile.readyState==4) //document is ready to parse
            {
                context.drawImage(imageObj, 0, 0);

                //pixel location from image
                var imgd = context.getImageData(3200,3200,6029,6968);
                var pix = imgd.data;

                alert(pix[0].toString()+ " "+pix[1].toString()+" "+pix[2].toString());
            }
        }

        inputFile.send(null); //close file after finished

    }
    catch(err){ alert(err.toString());}
  };

提前谢谢。

1 个答案:

答案 0 :(得分:3)

当它是交叉原点并且您正在使用canvas时,许多问题都由此解决:

imageObj.crossOrigin = 'anonymous';   
// crossOrigin attribute has to be set before setting src.

希望有所帮助