2015-04-03 47 views
0

我想在JavaScript中製作遊戲,我需要從圖像中獲取pixeldata。我使用getImageData()。data;並且它是工作在Internet Explorer都好,但在Chrome我得到這個錯誤:本地跨源數據錯誤

Uncaught SecurityError: Failed to execute 'getImageData' on 'CanvasRenderingContext2D': The canvas has been tainted by cross-origin data.

我一直在四處尋找解決方案,但似乎沒有任何工作,任何人有一個好主意?

這裏是我的代碼:` VAR 寬度= 600, 高度= 400, IMG, 帆布, CTX;

function main() { 
     canvas = document.createElement("canvas"); 
     ctx = canvas.getContext("2d"); 
     canvas.width = width; 
     canvas.height = height; 
     document.body.appendChild(canvas); 

     init(); 
     loop(); 

    } 

    function init() { 
     img = new Image(); 
     img.src = "test.png"; 


    } 

    function update() { 

    } 

    function render() { 
     ctx.drawImage(img, 0, 0); 
     var data = ctx.getImageData(10, 10, 1, 1).data; 
     console.log(data); 

    } 

    function loop() { 
     window.requestAnimationFrame(loop); 

     update(); 
     render(); 
    } 

    main();` 

該文件正在運行而不是在服務器上運行。

回答

2

如果您使用file://加載頁面或文件,它也會觸發CORS問題。

在本地進行測試時,請始終使用本地服務器,以便您可以從本地主機加載文件。

另外一個次要的問題:記得使用onload處理程序圖像:

function init() { 
    img = new Image(); 
    img.onload = ... // don't start loop without it... 
    img.src = "test.png"; 
} 
0

試試:

function init() { 
    img = new Image(); 
    img.crossOrigin = "Anonymous"; 
    img.src = "test.png"; 


}