Vue3中進(jìn)行二維碼的生成與解碼實(shí)現(xiàn)詳解
使用到的庫(kù)
最近在項(xiàng)目中需要使用到二維碼的生成解碼來(lái)進(jìn)行一些認(rèn)證操作,在此記錄一下我的學(xué)習(xí)過(guò)程。
npm i qrcode.vue --save // 用來(lái)生成二維碼的qr庫(kù) npm i jsqr --save // 用來(lái)解碼的庫(kù)
github地址:
生成二維碼的流程
我的需求是用二維碼來(lái)保存一個(gè)對(duì)象,對(duì)象中保存著許多復(fù)雜的信息,用戶(hù)首次填寫(xiě)完信息,獲取二維碼,下次只需要上傳二維碼就不用重復(fù)輸入信息了。
在我們的組件中導(dǎo)入這個(gè)庫(kù)
import QrcodeVue from 'qrcode.vue';
簡(jiǎn)單使用如下:
<template> <div> <qrcode-vue :value="value" :size="size" level="H"></qrcode-vue> </div> </template> <script setup> import QrcodeVue from 'qrcode.vue'; components: { QrcodeVue }; const value = JSON.stringify({name: 'limiang', age: 14}); //傳入的值,要求是字符串,需要將對(duì)象進(jìn)行轉(zhuǎn)換 const size = 200; //二維碼大小 </script>
頁(yè)面顯示:
二維碼的解碼過(guò)程
使用jsqr對(duì)二維碼進(jìn)行解碼我們了解一下它傳入的參數(shù),閱讀一下npm文檔:
npm地址:www.npmjs.com/package/jsq…
可以看到imageData參數(shù)要求的格式是Uint8clampedArray,它通常來(lái)自ImageData接口,因此我們將使用canvas來(lái)獲取這個(gè)數(shù)據(jù)。
實(shí)現(xiàn)思路
1:創(chuàng)建一個(gè)img實(shí)例,將img.src設(shè)置為我們的二維碼地址,這里我們用vant的上傳組件,在回調(diào)中獲取到file.content,是一個(gè)base64碼
img.src= file.content;
2:因?yàn)閳D片需要在加載完成之后才能使用,因此在img.onload中編寫(xiě)我們的解碼代碼
3:創(chuàng)建canvas畫(huà)布
// 將圖像繪制到canvas中 const canvas = document.createElement('canvas'); const ctx = canvas.getContext("2d"); ctx.drawImage(img, 0, 0, canvas.width, canvas.height); // 獲取圖像數(shù)據(jù) const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
4:這里的getImageData() 方法返回的就是Uint8clampedArray
5:最后,我們使用jsqr解碼
const qrdata = jsqr (imageData.data, imageData.width, imageData.height);
完整代碼:
<template> <div> <van-uploader :after-read="afterRead" /> </div> </template> <script setup> import jsqr from 'jsqr' function afterRead(file) { // 創(chuàng)建圖像元素 const img = new Image(); img.onload = () => { // 將圖像繪制到canvas中 const canvas = document.createElement('canvas'); const ctx = canvas.getContext("2d"); ctx.drawImage(img, 0, 0, canvas.width, canvas.height); // 獲取圖像數(shù)據(jù) const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height); //二維碼解碼 const qrdata = jsqr(imageData.data, imageData.width, imageData.height); //字符串轉(zhuǎn)對(duì)象 let option = JSON.parse(qrdata.data); console.log(option); } img.src= file.content; } </script>
以上就是簡(jiǎn)單的實(shí)現(xiàn)二維碼生成和解碼的過(guò)程,大家也可以將它們封裝成組件來(lái)使用。
更多關(guān)于Vue3二維碼生成解碼的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
解決Vue_localStorage本地存儲(chǔ)和本地取值問(wèn)題
這篇文章主要介紹了解決Vue_localStorage本地存儲(chǔ)和本地取值問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-07-07vue.js數(shù)據(jù)響應(yīng)式原理解析
這篇文章主要介紹了vue.js數(shù)據(jù)響應(yīng)式原理解析,文章圍繞主題展開(kāi)詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,需要的朋友可以參考一下2022-08-08Vue.js在數(shù)組中插入重復(fù)數(shù)據(jù)的實(shí)現(xiàn)代碼
這篇文章主要介紹了Vue.js在數(shù)組中插入重復(fù)數(shù)據(jù)的實(shí)現(xiàn)代碼,需要的朋友可以參考下2017-11-11vue中axios處理http發(fā)送請(qǐng)求的示例(Post和get)
本篇文章主要介紹了vue中axios處理http請(qǐng)求的示例(Post和get),這里整理了詳細(xì)的代碼,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-10-10