繁体   English   中英

本地跨域数据错误

[英]Local Cross-origin data error

我正在尝试用JavaScript制作游戏,我需要从图像中获取pixeldata。 我正在使用getImageData()。data; 并且在Internet Explorer上一切正常,但是在Chrome上出现此错误:

未捕获到的SecurityError:无法在“ CanvasRenderingContext2D”上执行“ getImageData”:画布已被跨域数据污染。

我一直在寻找解决方案,但似乎没有任何效果,有人有什么好主意吗?

这是我的代码:`var width = 600,height = 400,img,canvas,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();`

该文件在本地运行,不在服务器上。

如果使用file:// ...加载页面或文件,则也会触发CORS问题。

在本地进行测试时,请始终使用本地服务器,以便您可以从localhost加载文件。

另一个问题:记住对图像使用onload处理程序:

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

试试吧:

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


}

暂无
暂无

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

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