github地址: https://github.com/mebjas/html5-qrcode

官网:https://scanapp.org/html5-qrcode-docs/

导入链接:https://unpkg.com/html5-qrcode

github上有详细的介绍,在框架支持中也有一些案例,可以点击链接去看不同的框架中,怎么去使用 上面的这些demo都是不能自定义的,使用的是Html5QrcodeScanner,在这里,想要自定义的话,使用的是Html5Qrcode 在开始之前,需要注意的是,你的访问链接需要是https开头,如果不是的话,是不能使用webRTC的,也就没有获取摄像头的权限了。(ps:如果没有自己的服务器,vue项目配置devserve里的https=true,访问链接也可以使用https开头了,这时候,也可以在手机上使用了) 我这里的demo并没有使用任何的框架,但其实大多数都是一个操作,变通一下就可以了。 html

js

let html5QrCode = null;

// 获取摄像头权限

const getCameras = () => {

Html5Qrcode.getCameras()

.then((devices) => {

// 返回的是你的摄像设备列表,手机有两个摄像头,电脑返回一个摄像头

// 初始化扫描程序,在这里需要传递标签的id,第二个参数用来控制识别类型(没用过)

html5QrCode = new Html5Qrcode("reader");

start();

})

.catch((err) => {

html5QrCode = new Html5Qrcode("reader")

})

}

// 开始扫描相机给的二维码

const start = () => {

document.querySelector('button').style.display = 'none';

html5QrCode.start(

// environment后置摄像头 user前置摄像头 也可以传递获取摄像头时的id

// 也可以是这样的{ deviceId: { exact: cameraId} }

{ facingMode: "environment" },

{

fps: 20, // 可选,每秒帧扫描二维码

qrbox: { width: 250, height: 250 }, // 可选,如果你想要有界框UI

aspectRatio: 1.777778 // 可选,视频馈送需要的纵横比,(4:3--1.333334, 16:9--1.777778, 1:1--1.0)传递错误的纵横比会导致视频不显示

},

(decodedText, decodedResult) => {

// 成功的回调函数

document.getElementById('msg').innerText = decodedText;

stop();

})

// 这里应该还有一个错误回调函数(没有识别到的时候会执行,太频繁了,没写)

}

// 停止摄像头

const stop = () => {

html5QrCode.stop()

.then((suc) => {

console.log("关闭摄像头")

})

.catch((err) => {

console.log("关闭摄像头的时候报错了")

})

}

css

* {

padding: 0;

margin: 0;

}

html,

body {

height: 100%;

}

p {

position: fixed;

top: 50%;

left: 50%;

transform: translate(-50%, -50%);

z-index: 4;

}

button {

position: fixed;

top: 50%;

left: 50%;

transform: translate(-50%, -50%);

z-index: 3;

}

.qrcode {

display: flex;

top: 0;

left: 0;

height: 100vh;

}

#reader {

position: fixed;

top: 50%;

transform: translateY(-50%);

width: 100%;

height: 100%;

pointer-events: none;

}

#reader video {

height: 100%;

width: 100%;

display: block;

object-fit: cover;

}

下面是官网对Html5Qrcode的方法介绍

constructor:https://scanapp.org/html5-qrcode-docs/docs/apis/classes/Html5Qrcode#constructor start:https://scanapp.org/html5-qrcode-docs/docs/apis/classes/Html5Qrcode#start stop:https://scanapp.org/html5-qrcode-docs/docs/apis/classes/Html5Qrcode#stop

中途遇到了一个小错误(关于IOS和Android)

在使用的时候,我把js下载下来,放到服务器了,这里我的html导入包的链接是 http://~~~/html5-qrcode.js,然后发现Android可以用,IOS不能用,IOS不会弹出要获取摄像头的提示,这时候,只要把导入的js文件改成https开头就好了

参考链接

评论可见,请评论后查看内容,谢谢!!!
 您阅读本篇文章共花了: