簡體   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