解决Canvas.toDataURL 图片跨域问题

如题,在将页面的图片地址进行本地输出时(Html2Canvas.js),因不同源存在跨域问题,会出现toDataURL访问权限问题:

Redirect at origin 'http://sub1.xx.com' has been blocked from loading by Cross-Origin Resource Sharing policy: 
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://sub2.xx.com' is therefore not allowed access.
解决方案:
根据错误分析需要在控制头增加“Access-Control-Allow-Origin”,即允许访问源文件权限,那么我们对这个页面【注意是要输出页面的图片】这样处理:
var img = new Image;
img.onload = myLoader;
img.crossOrigin = 'anonymous';  //可选值:anonymous,*      
img.src = 'http://myurl.com/....';

或者是HTML中

<img src="" id="imgclcd" crossorigin="anonymous">

核心是请求头中包含了 Origin: "anonymous"或"*" 字段,响应头中就会附加上 Access-Control-Allow-Origin: * 字段,问题解决。



posted @ 2016-05-10 13:46  GIS流水  阅读(34934)  评论(3编辑  收藏  举报