Vue3中進行二維碼的生成與解碼實現(xiàn)詳解
使用到的庫
最近在項目中需要使用到二維碼的生成解碼來進行一些認證操作,在此記錄一下我的學習過程。
npm i qrcode.vue --save // 用來生成二維碼的qr庫 npm i jsqr --save // 用來解碼的庫
github地址:
生成二維碼的流程
我的需求是用二維碼來保存一個對象,對象中保存著許多復雜的信息,用戶首次填寫完信息,獲取二維碼,下次只需要上傳二維碼就不用重復輸入信息了。
在我們的組件中導入這個庫
import QrcodeVue from 'qrcode.vue';
簡單使用如下:
<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}); //傳入的值,要求是字符串,需要將對象進行轉(zhuǎn)換
const size = 200; //二維碼大小
</script>
頁面顯示:

二維碼的解碼過程
使用jsqr對二維碼進行解碼我們了解一下它傳入的參數(shù),閱讀一下npm文檔:
npm地址:www.npmjs.com/package/jsq…


可以看到imageData參數(shù)要求的格式是Uint8clampedArray,它通常來自ImageData接口,因此我們將使用canvas來獲取這個數(shù)據(jù)。

實現(xiàn)思路
1:創(chuàng)建一個img實例,將img.src設(shè)置為我們的二維碼地址,這里我們用vant的上傳組件,在回調(diào)中獲取到file.content,是一個base64碼
img.src= file.content;
2:因為圖片需要在加載完成之后才能使用,因此在img.onload中編寫我們的解碼代碼
3:創(chuàng)建canvas畫布
// 將圖像繪制到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)對象
let option = JSON.parse(qrdata.data);
console.log(option);
}
img.src= file.content;
}
</script>
以上就是簡單的實現(xiàn)二維碼生成和解碼的過程,大家也可以將它們封裝成組件來使用。
更多關(guān)于Vue3二維碼生成解碼的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Vue.js在數(shù)組中插入重復數(shù)據(jù)的實現(xiàn)代碼
這篇文章主要介紹了Vue.js在數(shù)組中插入重復數(shù)據(jù)的實現(xiàn)代碼,需要的朋友可以參考下2017-11-11
vue中axios處理http發(fā)送請求的示例(Post和get)
本篇文章主要介紹了vue中axios處理http請求的示例(Post和get),這里整理了詳細的代碼,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-10-10

