1.下载 html2canvas
npm install html2canvas --S
2.对应页面引入该插件
import html2canvas from 'html2canvas';
3.具体用法
html2canvas(document.body).then( canvas => { })
4.html
<template>
<div>
<div class="imgClass" ref="imgRef">图片</div>
<button @click="downLoadImg">下载图片</button>
</div>
</template>
5.在methods方法中
downLoadImg() { html2canvas(this.$refs.imgRef, { backgroundColor: '#ffffff', //背景色 为null是透明 dpi: 300,//增加像素的 scale:2 //放大倍数 相当于清晰度 调大一点更清晰 }).then(canvas => { var imgUrl = canvas.toDataURL("image/jpeg") this.fileDownload(imgUrl); })},
fileDownload(imgUrl) { var a= document.createElement("a"); //创建一个a标签用来下载 a.style.display = "none"; //隐藏掉a a.href = imgUrl; // 此处的imgUrl为base64格式的图片资源 a.download = "个人名片.png"; //设置下载的图片名称 // 触发点击-然后移除 document.body.appendChild(a); a.click(); document.body.removeChild(a);},