前端實現 生成圖片海報+二維碼
阿新 • • 發佈:2021-06-13
主要使用了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(); }); }); },
有幫助可以加個公眾號 我們一起學習探討