vue使用html2canvas 生成照片
使用html2canvas
// 生成快照
convertToImage(container, options = {}) {
// 传入dom节点宽高
const width = container.offsetWidth;
const height = container.offsetHeight;
// 设置放大倍数
const scale = window.devicePixelRatio || 1.5;
// html2canvas的配置项
const ops = {
scale,
width,
height,
useCORS: true,
allowTaint: false,
...options,
};
return html2canvas(container, ops).then((canvas) => canvas.toDataURL('image/png'));
},
// 获取节点照片
async getImage() {
document.body.scrollTop = 0;
document.documentElement.scrollTop = 0;
// 调用函数,取到截图的二进制数据,对图片进行处理(保存本地、展示等)
const imageData = await this.convertToImage(this.$refs.captureTable);
},
问题解决
- 图片跨域
- 设置配置项 allowTaint: false
canvas 的 CanvasRenderingContext2D 属于浏览器的对象,如果渲染过跨域资源,浏览器就认定 canvas 已经被污染了 Taint:污点
- 设置配置项 useCORS: false
表示允许跨域资源共享,注意不能与 allowTaint 同时配置为 true
- img 标签中添加 crossOrigin = “anonymous”
anonymous:如果使用这个值的话就会在请求 header 中带上 Origin 属性,但请求不会带上 cookie 和客户端 ssl 证书等其他的一些认证信息
- 图片服务器配置 Access-Control-Allow-Origin: *
重要的配置项,是跨域问题的根本源泉,需要后端配合
请求图片时,带上允许跨域的响应头:Access-Control-Allow-Origin: *
- 截图锯齿
解决方案:根据设备像素比进行缩放
// 设置放大倍数
const scale = window.devicePixelRatio;
- 截图不全
截图之前将页面滚动到顶部,否则会顶部留空白
document.body.scrollTop = 0;
document.documentElement.scrollTop = 0;
- 部分 css3 支持不好
- 不支持的 CSS 样式属性:
background-blend-mode、background-clip: text、box-decoration-break、repeating-linear-gradient()、font-variant-ligatures、mix-blend-mode、writing-mode、writing-mode、border-image、box-shadow、filter、zoom、transform
- 不支持使用rem单位定义文字大小、元素宽高等,不然无法显示该元素
文章参考: html2canvas使用总结.