1、将dom转换为图片
- 这里我们使用
html2canvas工具插件 - 先将dom转为canvas元素
- 然后canvas拥有一个方法可以将绘制出来的图形转为
url - 然后下载即可
- 注意:如果元素使用了渐变背景并透明的话,生成的图片可能会有点问题。我下面这个案例使用了渐变背景实现元素对角线,就有问题。
1.1、下载插件并导入
npm install --save html2canvas
import html2canvas from 'html2canvas';
1.2、编写代码
<template>
<div class="home">
<div class="content">
div>
<button @click="creatUrl">下载图片button>
div>
template>
<script>
import html2canvas from 'html2canvas';
export default {
name: 'HomeView',
components: {
},
methods: {
creatUrl() {
const setup = {
useCORS: true,
};
const dom = document.querySelector(".content")
html2canvas(dom, setup).then((canvas) => {
const link = canvas.toDataURL("image/jpg");
this.downloadPicture(link, "test.jpg");
});
},
downloadPicture(link, name = "未命名文件") {
const file = document.createElement("a");
file.style.display = "none";
file.href = link;
file.download = decodeURI(name);
document.body.appendChild(file);
file.click();
document.body.removeChild(file);
}
}
}
script>
<style lang="scss" scoped>
.home {
.content {
width: 100px;
height: 100px;
border: 1px solid #000;
background: linear-gradient(
to bottom left,
white 50%,
#000,
white 51%
);
}
}
style>
- 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
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
1.3、效果

2、将dom转为图片并放到pdf文件里进行下载
- 这里使用
jspdf插件,创建一个pdf文件,并把上面生成的图片放入pdf中即可完成。 - 上面将dom元素转为图片并生成
url就不再讲解
2.1、下载插件并导入
npm install jspdf --save
npm install --save html2canvas
import jsPDF from 'jspdf'
import html2canvas from 'html2canvas';
2.2、js代码
creatPdf() {
const setup = {
useCORS: true,
};
const dom = document.querySelector(".content")
html2canvas(dom, setup).then((canvas) => {
const link = canvas.toDataURL("image/jpg");
const pdf = new jsPDF();
pdf.addImage(link, 'JPEG', 0, 0, 210, 297);
pdf.save("test.pdf");
});
},
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
2.3、注意
- 我这里斜线是用背景渐变实现的,有兴趣可以查看第三章
CSS的第18篇文章 - 注意:如果有背景图的话,生成出来的图片可能会有问题。