?一、前言
????????最近有遇到一個需求,在h5瀏覽器中實現(xiàn)掃碼功能,其本質便是打開手機攝像頭定時拍照,特此做一個記錄。主要技術棧采用的是vue2,使用的開發(fā)工具是hbuilderX。
????????經過測試發(fā)現(xiàn)部分瀏覽器并不支持打開攝像頭,測試了果子,華子和米,發(fā)現(xiàn)夸克瀏覽器無法打開攝像頭實現(xiàn)功能。
h5調用攝像頭實現(xiàn)掃一掃只能在https環(huán)境下,亦或者是本地調試環(huán)境??!
?二、技術方案
?經過一番了解之后,找到了兩個方案
?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', //設置連續(xù)聚焦模式
? ? ? ? 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%);
?? ?}
四、最終效果
文章來源:http://www.zghlxwxcb.cn/news/detail-839745.html
如有問題,歡迎指正,若此文對您有幫助,不要忘記收藏+關注!文章來源地址http://www.zghlxwxcb.cn/news/detail-839745.html
到了這里,關于h5端調用手機攝像頭實現(xiàn)掃一掃功能的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網!