如何使用ngx-scanner-qrcode Angular库切换默认摄像头为后置
在ngx-scanner-qrcode中默认切换到后置摄像头的解决方案
直接用deviceActive: 1指定索引的方式不可靠,因为设备列表的顺序不固定,没法精准定位到后置摄像头。更稳妥的做法是主动获取设备列表,筛选出后置摄像头后通过deviceId指定,具体实现如下:
1. 模板配置
<ngx-scanner-qrcode #action="scanner" [config]="scannerConfig" (event)="handleScanResult($event)"></ngx-scanner-qrcode>
2. 组件逻辑实现
import { Component, ViewChild } from '@angular/core'; import { NgxScannerQrcodeComponent, ScannerQRCodeConfig, ScannerQRCodeResult } from 'ngx-scanner-qrcode'; @Component({ selector: 'app-qr-scanner', templateUrl: './qr-scanner.component.html', styleUrls: ['./qr-scanner.component.css'] }) export class QrScannerComponent { @ViewChild('action') scanner!: NgxScannerQrcodeComponent; scannerConfig: ScannerQRCodeConfig = {}; ngAfterViewInit() { // 获取所有可用的媒体输入设备 this.scanner.listDevices().then((devices: MediaDeviceInfo[]) => { // 筛选后置摄像头:匹配标签中的"back"(英文设备)或"后置"(中文设备) const rearCamera = devices.find(device => device.kind === 'videoinput' && (device.label.toLowerCase().includes('back') || device.label.includes('后置')) ); if (rearCamera) { // 配置并启动后置摄像头 this.scannerConfig = { deviceId: rearCamera.deviceId }; this.scanner.start(this.scannerConfig); } }); } handleScanResult(result: ScannerQRCodeResult[]) { // 处理扫描得到的二维码数据 console.log('扫描结果:', result); } }
关键说明
listDevices()方法可获取当前设备的所有媒体输入设备,从中筛选出类型为videoinput的摄像头设备- 通过设备标签(
label)判断是否为后置摄像头,适配不同语言的设备标识 - 用
deviceId指定摄像头比索引更可靠,避免设备列表顺序变化导致的错误
内容的提问来源于stack exchange,提问作者Sam Tomashi
相关产品推荐
相关产品推荐

