通过html2canvas将dom节点到出为图片

通过html2canvas将dom节点内容导出为图片的实现方法

项目使用的vue2技术栈,所以也以vue2来做演示

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import html2canvas from 'html2canvas'
// 下面是methods内容
// 导出图片的触发事件
async exportImage(){
// 拿到要导出的dom节点
let container = this.$refs.dashContainer
// 返回base64编码的文件
let imgData = await this.convertToImage(container)
// 通过a标签下载图片
const a = document.createElement('a');
a.href = imgData;
a.setAttribute('download', 'chart-download');
a.click();
},
// 接收dom节点和配置项
convertToImage(container, options = {}){
// 设置放大倍数
const scale = window.devicePixelRatio;

// 拿到节点原始宽高
const _width = container.offsetWidth;
const _height = container.offsetHeight;
// 如果传入了宽高则以传入的为主,否则以节点的宽高为主
let { width, height } = options;
width = width || _width;
height = height || _height;

// html2canvas配置项
const ops = {
scale,
// width,
// height,
useCORS: true,
allowTaint: false,
...options
};

return html2canvas(container, ops).then(canvas => {
// 返回图片的二进制数据
return canvas.toDataURL("image/png");
});
},
作者

胡兆磊

发布于

2022-03-29

更新于

2022-10-23

许可协议