最近有个H5调用手机摄像头扫描二维码需求,网上看了很多,大多都是vue里边使用,这边测试在H5中以下两个可用,但是都有些限制,大家有比较好用的也可以多多交流。
注:需要https访问
1.html5-qrcode
这个大多数手机都支持,但是扫描二维码对焦不友好,对扫描要求不高的场景还是可以用的。
js地址:https://github.com/mebjas/html5-qrcode/releases
<div id="qr-reader" style="width:100%;"></div>
<script src="./js/html5-qrcode.min.js"></script>
<script>
var html5QrCode = null;
$(function () {
saoMa();
});
function saoMa() {
Html5Qrcode.getCameras()
.then(devices => {
if (devices && devices.length) {
start();
}
})
.catch(err => {
alert("启用相机失败," + err);
});
}
function start() {
html5QrCode = new Html5Qrcode('qr-reader');
html5QrCode
.start(
{
facingMode: "environment",
},
{
fps: 30, // 设置每秒多少帧
qrbox: { width: 250, height: 250 },
tryHarder: true,
videoConstraints: {// 提高输入视频的分辨率
width: { ideal: 1920 },
height: { ideal: 1080 },
facingMode: 'environment',// 必须保持一致不然会变为前置摄像头
},
autofocus:true,
colorDark: '#0000ff',
colorLight: '#ffffff',
visualFeedback:true,
halfSample:true,
},
qrCodeMessage => {
if (qrCodeMessage) {
// TODO 执行逻辑
alert(qrCodeMessage);
}
},
errorMessage => {
console.log(`QR Code no longer in front of camera.`);
}
)
.catch(err => {
console.log(`Unable to start scanning, error: ${err}`);
alert("扫码失败," + err);
});
}
function stop() {
html5QrCode
.stop()
.then(ignore => {
// QR Code scanning is stopped.
console.log('QR Code scanning stopped.');
})
.catch(err => {
// Stop failed, handle it.
console.log('Unable to stop scanning.' + err);
});
}
</script>
2.instascan
这个我测试小米手机可以,相对于上边扫码对焦更好点,但是苹果手机测试不显示摄像头。。
js地址:https://github.com/schmich/instascan/releases
<!DOCTYPE html>
<html>
<head>
<title>扫一扫</title>
<script type="text/javascript" src="../../js/instascan.min.js"></script>
<style>
html,body{
height:100%
}
</style>
</head>
<body>
<video id="preview" style="width:100%;"></video>
<script type="text/javascript">
let scanner = new Instascan.Scanner({
continuous: true,
video: document.getElementById('preview'),
mirror: false,
captureImage: false,
backgroundScan: true,
refractoryPeriod: 5000,
scanPeriod: 1,
facing: 'environment',
singleChannel: false,
locate: true,
debug: true,
activeTokens: ['code_128_reader']
});
scanner.addListener('scan', function (content) {
console.log(content);
alert(content);
// Do something with the content here
});
Instascan.Camera.getCameras().then(function (cameras) {
if (cameras.length > 0) {
scanner.start(cameras[cameras.length - 1]);
} else {
console.error('No cameras found.');
}
}).catch(function (e) {
console.error(e);
});
</script>
</body>
</html>