likes
comments
collection
share

h5端调用手机摄像头实现扫一扫功能

作者站长头像
站长
· 阅读数 2

一、前言

最近有遇到一个需求,在h5浏览器中实现扫码功能,其本质便是打开手机摄像头定时拍照,特此做一个记录。主要技术栈采用的是vue2,使用的开发工具是hbuilderX。

经过测试发现部分浏览器并不支持打开摄像头,测试了果子,华子和米,发现夸克浏览器无法打开摄像头实现功能。

h5调用摄像头实现扫一扫只能在https环境下,亦或者是本地调试环境!!

h5端调用手机摄像头实现扫一扫功能

二、技术方案

经过一番了解之后,找到了两个方案

1.使用html5-qrcode(对二维码的精度要求较高,胜在使用比较方便,公司用的是vue2,因此最终采用此方案)

2.使用vue-qrcode-reader(对vue版本和node有一定要求,推荐vue3使用,这里就不展开说了)

三、使用方式

h5端调用手机摄像头实现扫一扫功能

当点击中间的扫码时,设置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%);
	}

四、最终效果

h5端调用手机摄像头实现扫一扫功能

如有问题,欢迎指正,若此文对您有帮助,不要忘记收藏+关注!