h5端調用手機攝像頭實現掃一掃功能

2024年2月6日 16点热度 0人点赞

一、前言

最近有遇到一個需求,在h5瀏覽器中實現掃碼功能,其本質便是打開手機攝像頭定時拍照,特此做一個記錄。主要技術棧采用的是vue2,使用的開發工具是hbuilderX。

經過測試發現部分瀏覽器並不支持打開攝像頭,測試了果子,華子和米,發現誇克瀏覽器無法打開攝像頭實現功能。

h5調用攝像頭實現掃一掃隻能在https環境下,亦或者是本地調試環境!!

二、技術方案

經過一番了解之後,找到了兩個方案

1.使用html5-qrcode(對二維碼的精度要求較高,勝在使用比較方便,公司用的是vue2,因此最終采用此方案)

2.使用vue-qrcode-reader(對vue版本和node有一定要求,推薦vue3使用,這裡就不展開說了)

三、使用方式

當點擊中間的掃碼時,設置isScanning屬性為true,即可打開掃碼功能,代碼復制粘貼即可放心‘食用’。

使用之前做的準備

通過npm install html5-qrcode 下載包

引入 import { Html5Qrcode } from 'html5-qrcode';

html結構
<view class="reader-box" v-if="isScaning">
	<view class="reader" id="reader"></view>
</view>

所用數據
data(){
    return{
        html5Qrcode: null,
        isScaning: false,
    }
}

methods方法
openQrcode() {
    this.isScaning = true;
    Html5Qrcode.getCameras().then((devices) => {
    if (devices && devices.length) {
    this.html5Qrcode = new Html5Qrcode('reader');
    this.html5Qrcode.start(
        {
        facingMode: 'environment'
        },
        {
        focusMode: 'continuous', //設置連續聚焦模式
        fps: 5,       //設置掃碼識別速度
        qrbox: 280   //設置二維碼掃描框大小
        },
        (decodeText, decodeResult) => {
         if (decodeText) {	//這裡decodeText就是通過掃描二維碼得到的內容
            this.action(decodeText)  //對二維碼邏輯處理
            this.stopScan(); //關閉掃碼功能
        }
    },
        (err) => {
            // console.log(err);  //錯誤信息
         }
     );
    }
    });
},
stopScan() {
	console.log('停止掃碼')
	this.isScaning = false;
	if(this.html5Qrcode){
    this.html5Qrcode.stop();
	}
}

css樣式
.reader-box {
		position: fixed;
		top: 0;
		bottom: 0;
		left: 0;
		right: 0;
		background-color: rgba(0, 0, 0, 0.5);
	}
	.reader {
		width:100%;
		// width: 540rpx;
		// height: 540rpx;
		position: absolute;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
	}

四、最終效果

作者:極客轉
鏈接:
https://juejin.cn/post/7316795553798815783