前端實現 生成圖片海報+二維碼


主要使用了 qrcode 與  html2canvas  實現

 

 

實現思路

先下載依賴 qrcode  與  html2canvas

npm install qrcode --save-dev    //引入生成二維碼插件
npm install html2canvas --save
// 建議下載我這個版本  高版本   部分手機不能顯示圖片,算是一個坑
"html2canvas": "^1.0.0-rc.4",

 在需要使用的界面引入

import QRCode from "qrcode";
import html2canvas from "html2canvas";  

然后繪制生成海報的dom  元素

一般就是樣式繪制出來以后就給一個固定定位(position: fixed;)  設置(bottom: -100%;)把內容隱藏在底部

 

 

 

先繪制圖片二維碼

通過 QRCode.toCanvas這個方法就能實現

   qrcode() {
    //  找到繪制二維碼的canvas元素
    // this.pageUrl 是自己定義的二維碼內容
      QRCode.toCanvas(document.getElementById("share-canvas"), this.pageUrl, {
        margin: 1,
      });
    },

使用html2canvas  生產海報

  showShareHandles() {
      this.$Indicator.open("生成圖片中");
      // 獲取自定義海拔的dom  元素
      var copyDom = document.getElementById("copyDom");
      var width = copyDom.width;
      var height = copyDom.height;
      // 定義canvas對象
      let canvas = document.createElement("canvas");
      var scale = 6; // 放大圖片6倍
      canvas.width = width * scale;
      canvas.height = height * scale;
      //  設置圖片為2d
      canvas.getContext("2d").scale(scale, scale);
      
      // 調用html2canvas 生成海報的方法  這樣寫是為了兼容部分手機不能顯示
      //  this.$refs.article  就是定義的海報dom元素
      // useCORS: true   設置圖片可以跨域
      // canvas.toDataURL()方法會生成一個  圖片url 可以直接拿來用
      (window.html2canvas || html2canvas)(this.$refs.article, {
        useCORS: true,
        logging: false,
      }).then((canvas) => {
        this.imgUri = canvas
          .toDataURL("image/png")
          .replace("image/png", "image/octet-stream");
        html2canvas(this.$refs.article, {
          useCORS: true,
          logging: false,
        }).then((canvas) => {
          this.imgUri = canvas
            .toDataURL("image/png")
            .replace("image/png", "image/octet-stream"); // 獲取生成的圖片的url
          this.lives = true;
          this.$Indicator.close();
        });
      });
    },

 


免責聲明!

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



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