这个npm包自带样式,无需多做处理
需要注意的是,必须要https环境或者使用localhost访问才能调起摄像头,否则会报失败
本地模拟https可以配置webpack的devserver
首先在html中放置一个容器
<div id="reader" width="100%" height="600px"></div>
js部分
import { Html5Qrcode } from "html5-qrcode"
// 初始化
const html5QrCode = new Html5Qrcode("reader");
// 扫描到二维码成功的callback
const qrCodeSuccessCallback = (decodedText, decodedResult) => {
console.log(decodedText, decodedResult, 'success')
// 成功之后关闭扫码区域
html5QrCode.stop();
};
// 扫码的fps(fps越低,识别越快,单位秒)和扫码框的宽高配置
const config = { fps: 3, qrbox: { width: 300, height: 300 } };
// 开始执行 facingMode为调用前置或者后置摄像头 catch为扫码失败回调
html5QrCode.start({ facingMode: "environment" }, config, qrCodeSuccessCallback).catch(err => {console.log('err', err)});
微信中可能有各种恶心的限制,可以调用微信的sdk来扫一扫