openfoodfacts-client/www/src/lib/Scanner.svelte

68 lines
1.3 KiB
Svelte

<script>
import { Html5Qrcode } from 'html5-qrcode';
import { onMount } from 'svelte';
let codebar;
let scanning = false;
let html5Qrcode;
onMount(start);
function start() {
html5Qrcode = new Html5Qrcode('reader');
html5Qrcode.start(
{ facingMode: 'environment' },
{
fps: 10,
qrbox: { width: 250, height: 250 },
},
onScanSuccess,
onScanFailure
).catch((err) => {
console.debug("Could not start the scanner");
console.error(err);
onClose();
return;
});
scanning = true;
}
async function stop() {
await html5Qrcode.stop();
scanning = false;
onClose();
}
function onScanSuccess(decodedText, decodedResult) {
codebar = decodedText;
// alert(`Code matched = ${decodedText}`);
console.log(decodedResult);
onResult(codebar);
stop();
}
function onScanFailure(error) {
console.warn(`Code scan error = ${error}`);
}
export let onClose, onResult;
</script>
<reader id="reader"/>
{#if scanning}
<button title="Stop barcode scanning" on:click={stop}>stop</button>
{:else}
<button title="Start barcode scanning" on:click={start}>start</button>
{/if}
<style>
reader {
width: 100%;
min-height: 500px;
background-color: black;
}
</style>