繁体   English   中英

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

[英]get pixel value from canvas image, CORS restriction

因此,显然,这对于某些浏览器来说是个问题,因为当您尝试从画布图像中获取像素数据时,我搜索了很多有关“画布变脏”的巨型点击,例如:

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());}
  };

先感谢您。

当它是跨源的并且您正在使用画布时,许多问题可以通过此方法解决:

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

希望能帮助到你

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM