使用 html2canvas 將頁面中某一部分轉為圖片下載


今天在項目中遇到一個需求是將生成的二維碼和一些背景作為海報,然后將海報以圖片的形式下載

使用了 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} 允許跨域   否則圖片的部分會是空白的


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM