You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 00:42:06