-
Notifications
You must be signed in to change notification settings - Fork 1
/
script.js
71 lines (59 loc) · 2.43 KB
/
script.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
'use strict';
let videoElement;
let resultElement;
let html5QrCode; // Declare the Html5Qrcode instance
// Initialize elements
function initElement() {
videoElement = document.getElementById('videoElement'); // Access the video tag
resultElement = document.getElementById('result'); // The element where the scanned QR code text will be displayed
}
// Start the camera feed inside the video element
function startCameraFeed() {
navigator.mediaDevices.getUserMedia({ video: true })
.then(function (stream) {
videoElement.srcObject = stream;
videoElement.play(); // Play the camera feed
startQRScanner(); // Start scanning after the camera is ready
})
.catch(function (err) {
console.error("Error accessing camera: " + err);
resultElement.innerHTML = "Error accessing camera: " + err.message;
});
}
// Start the QR code scanner
function startQRScanner() {
// Create a new Html5Qrcode instance
html5QrCode = new Html5Qrcode("qr-reader");
// Success callback when a QR code is successfully scanned
const qrCodeSuccessCallback = (decodedText, decodedResult) => {
console.log(`Decoded Text: ${decodedText}`);
resultElement.innerHTML = `Scanned USN: ${decodedText}`; // Display the scanned text (QR code content)
};
// Error callback if the QR code scan fails or no code is detected
const qrCodeErrorCallback = (errorMessage) => {
console.log(`QR Code scanning failed: ${errorMessage}`); // Log for debugging
};
// Start scanning for QR codes
html5QrCode.start(
{ facingMode: "environment" }, // Use the back camera
{
fps: 10, // Frames per second to scan
qrbox: { width: 250, height: 250 } // Size of the QR scan area
},
qrCodeSuccessCallback,
qrCodeErrorCallback
).catch(err => {
console.error("Unable to start scanning: ", err);
resultElement.innerHTML = "Unable to start scanning: " + err.message;
});
}
document.addEventListener('DOMContentLoaded', () => {
initElement();
// Delay start of the QR scanner until Html5Qrcode is defined
if (typeof Html5Qrcode !== 'undefined') {
startCameraFeed(); // Start the camera feed when the page loads
} else {
console.error("Html5Qrcode is not loaded.");
resultElement.innerHTML = "Error: QR code scanner not initialized.";
}
});