Vue生成分享海報(含二維碼)


本文已同步到專業技術網站 www.sufaith.com, 該網站專注於前后端開發技術與經驗分享, 包含Web開發、Nodejs、Python、Linux、IT資訊等板塊.

 

功能需求:

  • 海報有1張背景圖, 海報上的文案內容動態變化
  • 分享鏈接做成二維碼, 放在背景圖的固定位置上
  • 在微信環境里, 海報可長按保存或轉發

整體實現流程:

  1. 按海報樣式設計好html元素的頁面布局, 包括背景圖,文本,以及二維碼圖片的位置
  2. 使用 qrcodejs2庫 將分享鏈接合成二維碼圖片,賦值到html中的二維碼元素上
  3. 使用 html2canvas庫 將html元素整體轉換成一張海報

使用的第三方庫:

  • qrcodejs2 (合成二維碼)
  • html2canvas (html元素轉換為圖片)

下面是具體實現步驟:

 

一、設計html元素布局

template部分

<template>
  <!-- 海報html元素 -->
  <div id="posterHtml" :style="{backgroundImage: 'url('+posterHtmlBg+')'}" v-show="false">
  <div>{{posterContent}}</div>
  <!-- 二維碼 -->
  <div class="qrcode"><div id="qrcodeImg"></div></div>
  </div>
</template>

 

script部分:

<script>
  import QRCode from 'qrcodejs2'
  import html2canvas from 'html2canvas'
  export default {
    data() {
      return {
      posterContent: '', // 文案內容
      posterHtmlBg: require('../../assets/images/poster/invite_poster_bg.jpg'), // 背景圖
      posterImg: '', // 最終生成的海報圖片
    }
  },
}
</script>

 

二、合成二維碼圖片

methods: {
  createQrcode(text) {
    // 生成二維碼
    const qrcodeImgEl = document.getElementById('qrcodeImg')
    qrcodeImgEl.innerHTML = ''
    let qrcode = new QRCode(qrcodeImgEl, {
      width: 256,
      height: 256,
      colorDark: '#000000',
      colorLight: '#ffffff',
     correctLevel: QRCode.CorrectLevel.H
    })
    qrcode.makeCode(text)
  },
}

 

三、將html元素轉換成海報圖片

methods: {
    createPoster() {
      // 生成海報
      const vm = this
      const domObj = document.getElementById('posterHtml')
      html2canvas(domObj, {
        useCORS: true,
        allowTaint: false,
        logging: false,
        letterRendering: true,
        onclone(doc) {
          let e = doc.querySelector('#posterHtml')
          e.style.display = 'block'
        }
      }).then(function(canvas) {
        // 在微信里,可長按保存或轉發
        vm.posterImg = canvas.toDataURL('image/png')
      })
    },
}

 

注意: 添加html2canvas對象的onclone方法是為了 生成一個復制的虛擬組件,設置為顯示,即可獲取進行繪制,且虛擬組件不會顯示在頁面上.

福利: 本文已同步到我的個人技術網站 IT干貨-sufaith 該網站包括Python, Linux, Nodejs, 前端開發等模塊, 專注於程序開發中的技術、經驗總結與分享, 歡迎訪問.


免責聲明!

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



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