vue中使用html2canvas将html页面转为图片并且下载该图片
# 1、下载 html2canvas
npm install html2canvas --save
1
# 2、对应页面引入该插件
import html2canvas from 'html2canvas';
1
# 3、具体用法
(要element
使用带有一些(可选)选项的 html2canvas 呈现,只需调用html2canvas(element, options)
;
html2canvas(document.body).then(function(canvas) {
document.body.appendChild(canvas);
});
1
2
3
2
3
# 4、转为图片并且下载
<template>
<div>
<button @click="toImage">导出</button>
</div>
</template>
<script>
export default {
methods: {
toImage() {
html2canvas(this.$refs.imageDom, {
backgroundColor: '#ffffff'
}).then(canvas => {
var imgData = canvas.toDataURL("image/jpeg");
this.fileDownload(imgData);
})
},
fileDownload(downloadUrl) {
let aLink = document.createElement("a");
aLink.style.display = "none";
aLink.href = downloadUrl;
aLink.download = "img.png";
// 触发点击-然后移除
document.body.appendChild(aLink);
aLink.click();
document.body.removeChild(aLink);
}
}
}
</script>
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
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
# 5、总结
import html2canvas from "html2canvas";
// 生成快照
const convertToImage = (container, options = {}) => {
// 设置放大倍数
const scale = window.devicePixelRatio;
// 传入节点原始宽高
const width = container.offsetWidth;
const height = container.offsetHeight;
// html2canvas配置项
const ops = {
scale,
width,
height,
useCORS: true,
allowTaint: false,
...options
};
return html2canvas(container, ops).then(canvas => {
// 返回图片的二进制数据
return canvas.toDataURL("image/png");
});
}
// 调用函数,取到截图的二进制数据,对图片进行处理(保存本地、展示等)
const imgBlobData = await convertToImage(element);
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
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
# 参数配置
- html2canvas配置:https://html2canvas.hertzen.com/configuration
- html2canvas官网:https://html2canvas.hertzen.com/
上次更新: 2024/01/30, 00:35:17
- 01
- Node与GLIBC_2.27不兼容解决方案08-19
- 02
- Git清空本地文件跟踪缓存08-13