我正在尝试用 JavaScript 制作游戏,并且需要从图像中获取像素数据。我正在使用 getImageData().data;它在 Internet Explorer 上运行良好,但在 Chrome 上我收到此错误:
Uncaught SecurityError: Failed to execute 'getImageData' on 'CanvasRenderingContext2D': The canvas has been tainted by cross-origin data.
我一直在寻找解决方案,但似乎没有任何效果,有人有好主意吗?
这是我的代码:` 变量 宽度=600, 高度 = 400, 图像, 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 问题。
在本地测试时,请始终使用本地服务器,以便可以从本地主机加载文件。
还有一个附带问题:记住对图像使用 onload
处理程序:
function init() {
img = new Image();
img.onload = ... // don't start loop without it...
img.src = "test.png";
}
关于javascript - 本地跨源数据错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29430507/