mirror of
https://github.com/StefBuwalda/cal_counter.git
synced 2025-10-30 03:10:00 +00:00
Updated the camera selection logic to prioritize devices labeled as 'back' or 'rear' when initializing the video input for scanning. Falls back to the first available device if no rear camera is found.
62 lines
2.4 KiB
HTML
62 lines
2.4 KiB
HTML
{% extends "base.html" %}
|
|
|
|
{% block content %}
|
|
<div class="container py-5">
|
|
<div class="text-center mb-4">
|
|
<h1 class="fw-bold">Barcode Scanner</h1>
|
|
<p class="text-muted">Use your camera to scan barcodes</p>
|
|
</div>
|
|
|
|
<div class="d-flex justify-content-center mb-4">
|
|
<video id="video" class="border rounded shadow-sm" style="width: 100%; max-width: 500px;" autoplay
|
|
muted></video>
|
|
</div>
|
|
|
|
<div class="d-flex justify-content-center">
|
|
<button id="startButton" class="btn btn-primary px-4">Start Scanning</button>
|
|
<button id="stopButton" class="btn btn-danger px-4 ms-3">Stop</button>
|
|
</div>
|
|
</div>
|
|
|
|
|
|
<script type="module">
|
|
import { BrowserMultiFormatReader } from 'https://cdn.jsdelivr.net/npm/@zxing/library@0.21.3/+esm';
|
|
|
|
// constants
|
|
const codeReader = new BrowserMultiFormatReader();
|
|
const videoElement = document.getElementById('video');
|
|
|
|
|
|
// Start scanning for barcode
|
|
document.getElementById('startButton').addEventListener('click', async () => {
|
|
console.log('[DEBUG] Start button clicked')
|
|
try {
|
|
await navigator.mediaDevices.getUserMedia({ video: true });
|
|
// Use stream with video.srcObject = stream
|
|
} catch (err) {
|
|
alert("No camera found or no camera permission");
|
|
console.error("Could not access the camera:", err);
|
|
return;
|
|
}
|
|
console.log('[DEBUG] Permission given and at least one device present');
|
|
const devices = await codeReader.listVideoInputDevices();
|
|
console.log('[DEBUG] Cameras found:', devices);
|
|
const rearCamera = devices.find(device => device.label.toLowerCase().includes('back'))
|
|
|| devices.find(device => device.label.toLowerCase().includes('rear'))
|
|
|| devices[0]; // fallback
|
|
|
|
const selectedDeviceId = rearCamera?.deviceId;
|
|
await codeReader.decodeFromVideoDevice(selectedDeviceId, videoElement, async (result, err) => {
|
|
if (result) {
|
|
const codeText = result.getText();
|
|
const baseURL = "{{url_for('user.food_item', barcode='0')}}"
|
|
window.location.href = baseURL.replace("0", encodeURIComponent(codeText))
|
|
}
|
|
});
|
|
});
|
|
|
|
document.getElementById('stopButton').addEventListener('click', () => {
|
|
codeReader.reset();
|
|
});
|
|
</script>
|
|
{% endblock %} |