javascript 未捕获的安全错误:无法在“CanvasRenderingContext2D”上执行“getImageData”:画布已被跨域数据污染
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26688168/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Uncaught SecurityError: Failed to execute 'getImageData' on 'CanvasRenderingContext2D': The canvas has been tainted by cross-origin data
提问by Rakesh
I am getting this error in Chrome and Opera Browsers:
我在 Chrome 和 Opera 浏览器中收到此错误:
Uncaught SecurityError: Failed to execute 'getImageData' on 'CanvasRenderingContext2D': The canvas has been tainted by cross-origin data.
The code is working fine in Internet Explorer, Mozilla Firefox, and Safari. But I need to fix it in Chrome and Opera. Please help me to find a solution to fix this problem?
代码在 Internet Explorer、Mozilla Firefox 和 Safari 中运行良好。但我需要在 Chrome 和 Opera 中修复它。请帮我找到解决此问题的解决方案?
I am getting this error at this line
我在这一行收到此错误
imgData = ctx.getImageData(x1,y1,w,h);
回答by Aameer
May be this will help, as you have mentioned cross origin so try this,
可能这会有所帮助,正如你提到的交叉起源,所以试试这个,
var UimageObj = new Image();
crossOrigin has to be set to enable the canvas data to be saved.The source image should have access-control-allow-origin
set to *
or a chosen domain
必须设置 crossOrigin 才能保存画布数据。源图像应该access-control-allow-origin
设置为*
或 一个选定的域
UimageObj.crossOrigin = 'anonymous'; // crossOrigin attribute has to be set before setting src.If reversed, it wont work.
UimageObj.src = obj_data.srcUser;
Hope it helps.
希望能帮助到你。
回答by JiriHnidek
When you load your html file from disk using: file://path/to/your/file.html
, then Google Chrome and Opera will raise error at line including: imgData = ctx.getImageData(x1,y1,w,h);
当您使用: 从磁盘加载 html 文件时file://path/to/your/file.html
,Google Chrome 和 Opera 将在以下行引发错误,包括:imgData = ctx.getImageData(x1,y1,w,h);
Solution is simple: start web server (apache, nginx) put your html file somewhere at web server and load your html file from: http://localhost/somewhere/file.html
解决方案很简单:启动 web 服务器(apache、nginx)将您的 html 文件放在 web 服务器的某个位置并从以下位置加载您的 html 文件:http://localhost/somewhere/file.html