注意:无法绘制跨域图片


安装 html2canvas

1
npm i html2canvas

引入

1
import html2canvas from 'html2canvas'

使用

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
<template>
<div class="code">存为图片</div>
<button @click="generateImages">下载</button>
</template>

<script>
import html2canvas from "html2canvas";
export default {
...
methods:{
generateImages() {
html2canvas(document.querySelector(".code")).then((canvas) => {
// 生成图片
const imgUrl = canvas.toDataURL("image/png", 1);
const image = document.createElement("img");
image.src = imgUrl;
// 显示图片
const content = document.createElement("div");
content.appendChild(image);
// 下载图片
const a = document.createElement("a");
a.href = imgUrl;
a.download = "图片名称";
a.click();
content.remove();
a.remove();
});
},
}
}
</script>