html2canvas关于图片不能正常截取

问题

首先说说遇到了什么问题。首先有这么一个需求。需要前端根据后端传过来数据,动态的生成图片。图片中的文案、背景图片、用户头像全部都是通过后端的接口获取。但是使用 html2canvas 生成的canvas有些图片成功的在canvas里生成了。但是有些图片无论如何都显示不出来。

官方文档

在项目里面操作了半天未果,google了半天未果。此时有些许绝望。突然想到了,为什么不去它的 官网 看看呢。于是乎我在官网上看到了下面的内容。

Limitations

All the images that the script uses need to reside under the same origin for it to be able to read them without the assistance of a proxy. Similarly, if you have other canvas elements on the page, which have been tainted with cross-origin content, they will become dirty and no longer readable by html2canvas.

The script doesn't render plugin content such as Flash or Java applets.

讲的啥呢,这里为英文不好的同学翻译一下。英语好的可以直接看上文。大概的意思就是在html2canvas里面,是使用脚本去操作的,也就是说使用脚本把html转换成canvas,但是有一个限制,那就是不能使用跨源的图片。如果使用了,html2canvas将不会读取资源。

这也就是为什么转换出来的canvas有些图片一直是空白的原因。如果页面中有其他的canvas也使用了跨源的图片资源,html2canvas都不会去读取。

解决方案

对静态资源做一次转发并且在html2canvas的 配置 里面允许加载跨源资源,就可以了。

2018年8月1日更新

在调试的时候console信息,发现html2canvas自带的log太多,眼花缭乱的。大家可以自行配置取消掉。

html2canvas第一个参数就是你需要转换成canvas的dom节点。第二个参数接受一个对象,里面就是各种配置文件。配置项可以看 这里

{ logging: false }

配置成上面这样,就可以取消html2canvas默认开启的log了。

原文地址:https://www.cnblogs.com/detectiveHLH/p/9395406.html