如何设置html5-qrcode扫码器启动时默认使用手机后置摄像头
可以实现扫描器启动时默认调用智能手机后置摄像头,你只需要调整Html5QrcodeScanner的初始化配置即可,常用修改方式如下:
方案1:简单配置优先调用后置摄像头
直接在初始化配置中新增preferFrontCamera参数,设为false即可优先调用后置摄像头,修改后的完整代码如下:
function onScanSuccess(decodedText, decodedResult) { // handle the scanned code as you like, for example: document.getElementById('text').value = decodedText; console.log(`Code matched = ${decodedText}`, decodedResult); } function onScanFailure(error) { // handle scan failure, usually better to ignore and keep scanning. // for example: console.warn(`Code scan error = ${error}`); } let html5QrcodeScanner = new Html5QrcodeScanner( "reader", { fps: 10, qrbox: 250, // 新增配置项,设为false优先调用后置摄像头 preferFrontCamera: false }, /* verbose= */ false); html5QrcodeScanner.render(onScanSuccess, onScanFailure);
方案2:精确指定摄像头类型(兼容特殊机型)
如果方案1在部分机型不生效,可以通过videoConstraints参数强制指定调用后置摄像头:
let html5QrcodeScanner = new Html5QrcodeScanner( "reader", { fps: 10, qrbox: 250, videoConstraints: { facingMode: "environment" } }, /* verbose= */ false);
如果需要严格要求必须使用后置摄像头、无后置摄像头时直接抛出错误,可以把facingMode的值改为{ exact: "environment" },普通场景使用上述写法即可,设备没有后置摄像头时会自动 fallback 到可用的摄像头。
内容的提问来源于stack exchange,提问作者Mariusz
相关产品推荐
相关产品推荐

