Vue3如何更好地使用qrcodejs生成二維碼并添加文字描述?下面本篇文章給大家介紹一下Vue3+qrcodejs生成二維碼并添加文字描述,希望對大家有所幫助。
最近項(xiàng)目中有生成二維碼功能的需求,還需要在二維碼底部添加文字描述,并把二維碼和文字合并成一張圖下載的要求。
之前的項(xiàng)目有用到vue-qr
,確實(shí)非常好用,但是考慮到添加文字描述,后面就選擇了qrcodejs
。(學(xué)習(xí)視頻分享:vue視頻教程)
文章項(xiàng)目基于 《使用Vite搭建Vue3項(xiàng)目實(shí)踐記錄 》
https://juejin.cn/post/7082307153192550430
生成二維碼
安裝qrcodejs
,并安裝其類型定義模塊
npm i qrcode -S npm install --save @types/qrcode
新建全局二維碼組件QRcode.vue
,二維碼信息及文字描述都由外部傳入
基本操作就是先調(diào)用qrcode
的toDataURL
方法,獲取到二維碼的Base64
圖片信息,隨后新建Image
,再把圖片畫到Canvas
里
最后加上自定義文字即可
需要注意的是文字的位置是在圖片底部居中
qrCodeOption
為qrcode
相關(guān)配置,詳情qrcode – npm (npmjs.com)
<template> <canvas id="canvas" ref="canvas" :width="width" :height="height"></canvas> </template> <script setup> import QRCode from "qrcode"; import { onMounted, ref } from "vue"; const props = defineProps({ //二維碼存儲內(nèi)容 qrUrl: { type: String, default: "Hello World" }, // canvas width width: { type: Number, default: 400 }, // canvas height height: { type: Number, default: 400 }, // 二維碼尺寸(正方形 長寬相同) qrSize: { type: Number, default: 360 }, // 二維碼底部文字 qrText: { type: String, default: "Hello World" }, //底部說明文字字號 qrTextSize: { type: Number, default: 24 } }); const qrCodeOption = { errorCorrectionLevel: "H", width: props.qrSize, version: 7 }; const canvas = ref<HTMLCanvasElement>(); /** * @argument qrUrl 二維碼內(nèi)容 * @argument qrSize 二維碼大小 * @argument qrText 二維碼中間顯示文字 * @argument qrTextSize 二維碼中間顯示文字大小(默認(rèn)16px) */ const handleQrcode = () => { let dom = canvas.value as HTMLCanvasElement; QRCode.toDataURL(props.qrUrl, qrCodeOption) .then((url: string) => { // 畫二維碼里的logo// 在canvas里進(jìn)行拼接 const ctx = dom.getContext("2d") as CanvasRenderingContext2D; const image = new Image(); image.src = url; setTimeout(() => { ctx.drawImage(image, (props.width - props.qrSize) / 2, 0, props.qrSize, props.qrSize); if (props.qrText) { //設(shè)置字體 ctx.font = "bold " + props.qrTextSize + "px Arial"; let tw = ctx.measureText(props.qrText).width; // 文字真實(shí)寬度 let ftop = props.qrSize - props.qrTextSize; // 根據(jù)字體大小計算文字top let fleft = (props.width - tw) / 2; // 根據(jù)字體大小計算文字left ctx.fillStyle = "#fff"; ctx.textBaseline = "top"; //設(shè)置繪制文本時的文本基線。 ctx.fillStyle = "#333"; ctx.fillText(props.qrText, fleft, ftop); } }, 0); }) .catch((err: Error) => { console.error(err); }); }; onMounted(() => { handleQrcode(); }); </script> <style scoped></style>
思考和優(yōu)化setTimeout
改為Promise
到這里二維碼的功能基本可以使用了,但是我在想為什么這里需要使用到setTimeout
呢?
如果是nextTick
行不行?答案是不行的,原因是nextTick
是微任務(wù),實(shí)在DOM刷新之前就執(zhí)行了,而setTimeout
在之后執(zhí)行。
可以注意到代碼中有新建Image
方法,圖片加載是異步的,所以有更好的處理方法嗎?
可以改用Promise
,在圖片的onload
方法中返回圖片就可以了,所以改寫下handleQrcode
const handleQrcode = () => { let dom = canvas.value as HTMLCanvasElement; QRCode.toDataURL(props.qrUrl, qrCodeOption) .then((url: string) => { // 畫二維碼里的logo// 在canvas里進(jìn)行拼接 const ctx = dom.getContext("2d") as CanvasRenderingContext2D; const image = new Image(); image.src = url; new Promise<HTMLImageElement>((resolve) => { image.onload = () => { resolve(image); }; }).then((img: HTMLImageElement) => { // console.log(img, ctx) ctx.drawImage(img, (props.width - props.qrSize) / 2, 0, props.qrSize, props.qrSize); if (props.qrText) { //設(shè)置字體 ctx.font = "bold " + props.qrTextSize + "px Arial"; let tw = ctx.measureText(props.qrText).width; // 文字真實(shí)寬度 let ftop = props.qrSize - props.qrTextSize; // 根據(jù)字體大小計算文字top let fleft = (props.width - tw) / 2; // 根據(jù)字體大小計算文字left ctx.fillStyle = "#fff"; ctx.textBaseline = "top"; //設(shè)置繪制文本時的文本基線。 ctx.fillStyle = "#333"; ctx.fillText(props.qrText, fleft, ftop); } }); }) .catch((err: Error) => { console.error(err); }); };
二維碼下載
有了二維碼就需要下載,補(bǔ)充下載方法,在組件內(nèi)部加
直接使用canvas toDataURL
方法轉(zhuǎn)成Base64
//保存圖片 const savePic = () => { let dom = canvas.value as HTMLCanvasElement; let a = document.createElement("a"); //將二維碼面板處理為圖片 a.href = dom.toDataURL("image/png", 0.5); a.download = props.qrUrl + ".png"; a.click(); }; defineExpose({ savePic });
父組件調(diào)用
全局注冊
可以把組件注冊為全局組件,可以參考文章Vue項(xiàng)目中的實(shí)用技巧記錄
其中包括webpack
和vite
遍歷vue
文件注冊全局組件
調(diào)用組件
<template> <div class="container"> <QRcode /> </div> </template>
效果如圖
多二維碼遍歷下載
上面補(bǔ)充的下載方法中,需要使用defineExpose
,不然會調(diào)用不到子組件方法
<template> <div> <QRcode v-for="item in qrcodeList" ref="qrcode" :key="item.id" :qr-url="item.label" :qr-text="item.label" /> <el-button @click="downloadAll">downlaod</el-button> </div> </template> <script setup> import { reactive, ref } from "vue"; const qrcode = ref(); const qrcodeList = reactive([ { id: 1, label: "山卡拉OK" }, { id: 2, label: "伍六七" }, { id: 3, label: "梅小姐" }, { id: 4, label: "雞大保" }, { id: 5, label: "小飛雞" } ]); const downloadAll = () => { qrcode.value.map((item: any) => { item.savePic(); }); }; </script>
Option Api案例
Option Api的案例如下
src/components/QRcodeOption.vue · LWH/vite-vue3-project – 碼云 – 開源中國 (gitee.com)
src/views/qrcode/qrcode2.vue · LWH/vite-vue3-project – 碼云 – 開源中國 (gitee.com)
(學(xué)習(xí)視頻分享:web前端開發(fā)、編程基礎(chǔ)視頻)