背景:最近在项目中有这样一个场景,当用户点击“导出”时,需要把当前页面的数据分析导出成一张图,并且直接下载到本地。(当前页面包含有echarts图)
1、安装依赖包 html2canvas
npm i -S html2canvas
2、在需要使用导出的页面导入 html2canvas
import html2canvas from "html2canvas";
<div class="export-btn" @click.stop.once ="exportClick">
<i class="el-icon-loading" v-if="iconShow"></i>
<a ref="down" >{{ iconShow ? '导出中' : '导出' }}</a>
</div>
<div ref="contentRef">
// 这里面就是具体写需要导出的内容了
</div>
methods: {
exportClick() {
this.iconShow = true
let downName = this.villageList[this.activeVillage].name
html2canvas(this.$refs.contentRef,{scale: 5, logging:false, useCORS:true}).then((canvas) => {
const oImg = new Image();
oImg.src = canvas.toDataURL(); // 导出图片
this.$refs.down.href = canvas.toDataURL();
this.$refs.down.download = downName; // 导出图片的名字
this.$refs.down.click();
this.iconShow = false
});
},
}