vue html2canvas + qrcode 畫分享圖

安裝

  npm install html2canvas --save  
  npm install qrcodejs2 --save  //二維碼

引入

  import html2canvas from 'html2canvas'
  import QRCode from 'qrcodejs2';

生成二維碼

<div id="qrCode" ref="qrCodeDiv" v-if="isDom"></div>
  qrCode() {
      new QRCode(this.$refs.qrCodeDiv, {  //this.$refs.qrCodeDiv生成二維碼的dom
        text: xxx, //二維碼地址
        width: 125,
        height: 125,
        colorDark: "#333333", //二維碼顏色
        colorLight: "#ffffff", //二維碼背景色
        correctLevel: QRCode.CorrectLevel.L//容錯(cuò)率,L/M/H
      })
    },

把生成的二維碼和海報(bào)圖樣式寫好之后就用html2canvas生成圖片

// 畫圖區(qū)域
<div class="share" id="html2canvas" ref="html2canvas">
   <img :src="ewm" alt="" v-if="isDom" >
   <div id="qrCode" ref="qrCodeDiv" v-if="isDom"></div>
</div>
shareImage() {
      var targetDom = this.$refs.html2canvas //畫圖區(qū)域的dom
      html2canvas(targetDom, {
        allowTaint: false,
        useCORS: true,
        height: targetDom.offsetHeight,
        width: targetDom.offsetWidth,
        taintTest: true, // 在渲染前測試圖片
        timeout: 500, // 加載延時(shí)
        windowWidth: document.body.scrollWidth,
        windowHeight: document.body.scrollHeight,
        dpi: window.devicePixelRatio * 2,
        scale: 2
        // backgroundColor: 'rgb(213,201,221)'
      }).then(canvas => {
        this.$refs.html2canvas.append(canvas);//在下面添加canvas節(jié)點(diǎn)
        this.isDom = false
        let link = document.createElement("a");
        link.href = canvas.toDataURL();//下載鏈接
        link.setAttribute("download","體檢表.png");
        link.style.display = "none";//a標(biāo)簽隱藏
        document.body.appendChild(link);
        // link.click(); // 直接觸發(fā)下載事件   看需求是否需要
      })
    },
mouted() {
  getCode() {
      this.isDom = true
      /** f (this.$refs.html2canvas) {
        this.$refs.html2canvas.removeChild(this.$refs.html2canvas.lastChild)
      } 
      防止每次重復(fù)生成二維碼*/
      this.$nextTick(() => {
        this.qrCode()
        setTimeout(() => {
          this.shareImage()  //生成的時(shí)候需要放在定時(shí)器里面  防止生成的海報(bào)畫圖有偏差,如果有白邊可以嘗試把定時(shí)器的時(shí)間延長
        }, 200)
      })
    },
}

github地址
https://github.com/niklasvh/html2canvas

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容