需求:将自己写的html内容转化为图片并可以下载到本地
1.安装html2canvas
npm install --save html2canvas
2.在自己所需要的页面进行引入
import html2canvas from "html2canvas";
3.html
<div class="popuptop" id="img">
<div class="pupupbg">
内容内容内容
</div>
</div>
<div class="weixin" @click="downimg">
<div class="weixinlogo" >
<img src="../../assets/images/mypage/down.png">
<p class="weixinshare" >下载</p>
</div>
</div>
<a id="downimg" href="" style="display:none"></a>
4.JS
//下载图片
let downimg= ()=>{
setTimeout(()=>{
proxy.$nextTick(()=>{
html2canvas(document.querySelector('#img'),{
useCORS: true
}).then(canvas => {
var url = canvas.toDataURL() //把canvas转成base64
// 写一个隐藏的按标签,借助按标签的download属性下载图片
document.querySelector('#downimg').href = url
document.querySelector('#downimg').download = "我的持仓报告.png"
document.querySelector('#downimg').click()
})
})
},2000)
}
以上代码就能实现将html内容转为图片并下载到本地。