使用 html2canvas 将页面中某一部分转为图片下载

2022-12-25,,,

今天在项目中遇到一个需求是将生成的二维码和一些背景作为海报,然后将海报以图片的形式下载

使用了 html2canvas  插件

import html2canvas from "html2canvas";

<div class="tc" v-for="(item,index) in qrcodeList" :key="index">
<div :id="item.refname" class="poster " :class="item.bgimg">
<div class="poster-dir">
<div class="poster-title fontSize-3">问卷标题</div>
<img class="qrcode" :src="qrcodeimg" alt="">
<div class="poster-own">问卷工厂提供技术支持</div>
</div>
</div>
<span @click="downLoadCode(item.refname,'问卷海报')" class="konbtn mt10">下载</span>
</div>

  这是要执行的 代码片段

downloadFile(data, fileName) {
if (!data) {
return;
}
let url = window.URL.createObjectURL(data);
let link = document.createElement("a");
link.style.display = "none";
link.href = url;
link.setAttribute("download", fileName);
document.body.appendChild(link);
link.click();
},
downLoadCode(id,name){
html2canvas(document.getElementById(id),{useCORS:true,logging:true}).then(canvas => {
canvas.toBlob(blob => {
this.downloadFile(blob,name);
}, "image/png");
});
},

  如果要下载的部分有图片内容  需要 添加

{useCORS:true,logging:true} 允许跨域   否则图片的部分会是空白的

使用 html2canvas 将页面中某一部分转为图片下载的相关教程结束。

《使用 html2canvas 将页面中某一部分转为图片下载.doc》

下载本文的Word格式文档,以方便收藏与打印。