html2canvas 绘制网络图片 跨域问题

技术框架 vue ,使用html2canvas 将图片绘制下来并下载

过程中的经典报错:

Uncaught SecurityError: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.

未捕获的SecurityError:未能在“htmlCanvaseElement”上执行“ToDataURL”:可能无法导出受污染的画布。

使用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.

跨源资源共享策略阻止在源站“http://sub1.xx.com”加载重定向:请求的资源上不存在“访问控制允许源站”头。因此,不允许访问源站“http://sub2.xx.com”。

跨域访问报错

解决方案:

1.在img标签上添加 crossorigin=“anonymous” 属性。允许图片跨域 不过设置这个之后,图片会无法显示 会报错

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.

这是因为你img是在缓存数据中 读取的 并没有访问远程这个图片的时候没有携带请求头。可以在图片路径上拼接上固定 字符串 '?any_string_is_ok'

注意一定是固定字符串 。如果是随机字符串的话会导致CDN的缓存被击穿

image

2. 使用 html2Canvas的时候 需要配置useCORS为 true

这个属性是 html2Canvas 开启跨域用的 可以在html2Canvas的文档上找到

  1. 确保你的图片服务器支持CORS访问,也就是会返回Access-Control-Allow-Origin等响应头;

网上有一些关于这个的处理是修改源码,个人建议不要去修改源码。

你可能感兴趣的:(html2canvas 绘制网络图片 跨域问题)