react项目中使用html5-qrcode
1、安装html5-qrcode
npm install html5-qrcode
2、引入html5-qrcode库
import { Html5QrcodeScanner, Html5Qrcode } from "html5-qrcode";
3、示例写法
let html5Qrcode;const getCamera = () => {Html5Qrcode.getCameras().then((devices) => {if (devices && devices.length) {html5Qrcode = new Html5Qrcode("reader");start(); //打开相机}}).catch((error) => {html5Qrcode = new Html5Qrcode("reader");alert("您需要开启相机权限!");});};const start = () => {html5Qrcode.start({facingMode: "environment",//默认使用后置摄像头},{fps: 5,qrbox: {//扫码框的大小width: 250,height: 250,},aspectRatio: 1.7777778,//显示的比例},(decodedText, decodeResult) => {console.log(decodeResult);}).catch((error) => {alert(error);});};const stop = () => {html5Qrcode.stop().then(() => {});};
如果使用默认扫码引入Html5QrcodeScanner
注意:调试时候浏览器必须是在localhost或者是https协议下