先放官网链接 :http://html2canvas.hertzen.com
我是在vue2 中使用的,步骤如下
1 npm 安装
npm install --save html2canvas
2 在需要截图的页面中引入
import html2canvas from "html2canvas";
3 截图是以dom 为节点去截图的
如我需要截 以下整个节点
<div ref="imageWrapper">
4 在vue methods 中获取该节点
this.$refs.imageWrapper
let dataURL = canvas.toDataURL("image/png");
dataURL 为截图后的base64图片地址
5 让图片显示在页面
<img :src="imgURL" ,alt="" />
this.imgURL = dataURL
6 通过a标签的download下载该图片 (href里面的url 要对应data 里面的imgUrl)
<a :href="imgUrl" class="down" download="下载">下载</a>
7 下面是整个页面的完整代码
<template>
<div>
<img :src="imgUrl" alt="" />
<div ref="imageWrapper">
<a-table :dataSource="dataSource" :columns="columns">
<template #age>
<a>dasddsds</a>
</template>
<template #address="{ record }">
<a>{{ record }}</a>
</template>
<template #name="{ text }">
<a>{{ text }}</a>
</template>
<template #customTitles>
<span>
<smile-outlined />
姓名
</span>
</template>
</a-table>
</div>
<button @click="toImage">截图</button>
<a :href="imgUrl" class="down" download="下载">下载</a>
</div>
</template>
<script>
import { SmileOutlined } from "@ant-design/icons-vue";
import html2canvas from "html2canvas";
export default {
components: {
SmileOutlined,
},
data() {
return {
imgUrl: "",
dataSource: [
{
key: "1",
name: "胡彦斌",
age: 32,
address: "西湖区湖底公园1号",
},
{
key: "2",
name: "胡彦祖",
age: 42,
address: "西湖区湖底公园1号",
},
],
columns: [
{
dataIndex: "name",
slots: {
title: "customTitles",
customRender: "name",
},
},
{
title: "年龄",
dataIndex: "age",
key: "age",
slots: {
customRender: "age",
},
},
{
title: "住址",
dataIndex: "address",
key: "address",
slots: {
customRender: "address",
},
},
],
};
},
methods: {
toImage() {
console.log(this.$refs.imageWrapper);
html2canvas(this.$refs.imageWrapper).then((canvas) => {
let dataURL = canvas.toDataURL("image/png");
console.log(dataURL);
this.imgUrl = dataURL;
if (this.imgUrl !== "") {
this.dialogTableVisible = true;
}
});
},
},
};
</script>