scanner.comComponent.html:
Код: Выделить всё
Scanned Barcode: {{ barcodeResult }}
Restart Scanner
Код: Выделить всё
import { Component, ElementRef, OnDestroy, OnInit } from '@angular/core';
// @ts-ignore
import Quagga from 'quagga';
@Component({
selector: 'app-scanner',
templateUrl: './scanner.component.html',
styleUrls: ['./scanner.component.css'],
})
export class ScannerComponent implements OnInit, OnDestroy {
barcodeResult: string = ''; // Variable to hold the scanned barcode value
constructor(private el: ElementRef) {}
ngOnInit(): void {
this.startScanner();
}
// Start the scanner
startScanner() {
this.barcodeResult = '';
// Set up QuaggaJS to start scanning from the webcam
navigator.mediaDevices
.getUserMedia({ video: { facingMode: 'environment' } })
.then((stream) = {
console.log('Camera access granted');
// Optional: You can also display the stream to the user for debugging
const videoElement = document.querySelector('video');
videoElement.srcObject = stream;
})
.catch((err) = {
console.error('Camera access denied:', err);
});
Quagga.init(
{
inputStream: {
name: 'Live',
type: 'LiveStream',
target: this.el.nativeElement.querySelector('#scanner-container'), // Target the video container
constraints: {
facingMode: 'environment', // Use the environment camera (back camera on mobile)
width: { ideal: 640 }, // Reduce the width of the video
height: { ideal: 480 }, // Reduce the height of the video
},
},
decoder: {
readers: ['code_128_reader', 'ean_reader', 'upc_reader', 'ean_13'], // Barcode types to scan
},
},
(err: any) = {
if (err) {
console.error('Error initializing Quagga', err);
return;
}
// Start the scanner once it's initialized
console.log('Quagga initialized successfully');
Quagga.start();
}
);
// Listen for the result of a scan
Quagga.onDetected((data: any) => {
console.log('Detection callback:', data);
if (data && data.codeResult && data.codeResult.code) {
this.barcodeResult = data.codeResult.code; // Update the scanned result
console.log('Scanned Barcode:', this.barcodeResult);
// Optionally, you can stop scanning after a successful scan:
Quagga.stop();
}
});
}
// Clean up when the component is destroyed
ngOnDestroy(): void {
Quagga.stop();
}
}
Код: Выделить всё
#scanner-container {
width: 100%;
height: 600px;
margin: 0 auto;
}
h3 {
color: green;
font-size: 1.2em;
}
Отсканирован образец штрих-кода
Вывод сканера
https://stackblitz.com/edit/angular-ngx ... index.html
Подробнее здесь: https://stackoverflow.com/questions/793 ... de-results