今天在項目中遇到一個需求是將生成的二維碼和一些背景作為海報,然后將海報以圖片的形式下載
使用了 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} 允許跨域 否則圖片的部分會是空白的