vue 生成二維碼,及下載
阿新 • • 發佈:2022-04-20
1. npm install -d qrcode
2. 在頁面中匯入 import QRCode from "qrcode";
3. 頁面html 結構
<canvas id="QRCode_header" > </canvas>4.頁面api 的使用
let opts = { errorCorrectionLevel: "H", //容錯級別 type: "image/png", //生成的二維碼型別 quality: 0.3, //二維碼質量 margin: 0, //二維碼留白邊距 width: 180, //寬 height: 180, //高 text: this.text, //二維碼內容 color: { dark: "#333333", //前景色 light: "#fff", //背景色 }, }; let msg = document.getElementById("QRCode_header"); let that = this; QRCode.toCanvas(msg, this.text, opts, function (error) { console.log(error); that.getBase64(); });
5. 頁面img 圖片下載 , 獲取 canvas 的 base64碼。
let myCanvas = document.getElementById("QRCode_header"); let imgURL = myCanvas.toDataURL("image/png"); 6.生成 blob 。 base64ToBlob(base64) { const parts = code.split(";base64,"); const contentType = parts[0].split(":")[1]; const raw = window.atob(parts[1]); const rawLength = raw.length; const uInt8Array = new Uint8Array(rawLength); for (let i = 0; i < rawLength; ++i) { uInt8Array[i] = raw.charCodeAt(i); } return new Blob([uInt8Array], { type: contentType }); }, 7. 使用a 標籤下載 let imgURL = this.bese64; const blob = this.base64ToBlob(imgURL); const link = document.createElement("a"); link.href = window.URL.createObjectURL(blob); link.download = "QRcode"; document.body.appendChild(link); const evt = document.createEvent("MouseEvents"); evt.initEvent("click", false, false); link.dispatchEvent(evt); document.body.removeChild(link);8. 注意,uc 不支援 base64 圖片使用a 標籤下載
可以做成用base64 碼,在 img標籤上面顯示
提示使用者,長按儲存圖片