HTML:
<zxing-scanner
[device]="selectedDevice"
(scanSuccess)="onQrCodeScanComplete($event)"
style="width: 100%; max-height: 50vh;">
</zxing-scanner>
I have this zxing scanner in my component for an angular project. I need it to automatically choose the proper camera based on how distant you are from the objective. This is because some people that have, for example, an iPhone 15 Pro have issues with the scanner not choosing the camera which focuses on really close distances. is there a way to constantly automatically choose the right camera (and not just at the beginning, just like the default camera app does, so adjust it while the camera is open) and store it in the selectedDevice
variable?
HTML:
<zxing-scanner
[device]="selectedDevice"
(scanSuccess)="onQrCodeScanComplete($event)"
style="width: 100%; max-height: 50vh;">
</zxing-scanner>
I have this zxing scanner in my component for an angular project. I need it to automatically choose the proper camera based on how distant you are from the objective. This is because some people that have, for example, an iPhone 15 Pro have issues with the scanner not choosing the camera which focuses on really close distances. is there a way to constantly automatically choose the right camera (and not just at the beginning, just like the default camera app does, so adjust it while the camera is open) and store it in the selectedDevice
variable?
1 Answer
Reset to default 0You can use built-in (camerasFound)
event provided by ZXing to manage camera selection.
The (camerasFound)
event emits an array of MediaDeviceInfo objects, which represent the available cameras. You can filter through the available cameras based on preferred labels or other properties of the MediaDeviceInfo objects or create dropdown modal to allow users to select device on their own. Then, bind it to the [device]
input of ZXing component, which would trigger onChange.
Also, you can use [enable]
property to prevent ZXing scanner from initializing the default camera until a specific device is selected.
I also recommend setting the [autofocusEnabled]="true"
property. Enabling autofocus significantly improves the scanning quality.
Alliteratively, you can disable ZXing autostart and manage devices from browser API directly - see MediaDevices: getUserMedia()
<zxing-scanner
[autofocusEnabled]="true"
[enable]="selectedDevice != null"
(camerasFound)="chooseDevice($event)"
[device]="selectedDevice">
</zxing-scanner>
import {Component} from '@angular/core';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.scss']
})
export class HomeComponent {
selectedDevice: MediaDeviceInfo | undefined;
preferredLabels = ['myCamera'];
chooseDevice(deviceInfo: MediaDeviceInfo[]) {
const device = deviceInfo.find(info => this.preferredLabels.includes(info.label));
if (device != null) {
this.selectedDevice = device;
}
}
}