Ever wanted to scan qr and barcodes using your mobile but didn't want to write a full blown native app just to get camera access?
Use your mobile browser! Html5 now supports it.
Open the demo in your mobile browser - chrome, safari, firefox all worked for me!
Honestly, I couldn't believe how easy it was! Check out the code:
<script>
import { Html5Qrcode } from 'html5-qrcode'
import { onMount } from 'svelte'
let scanning = false
let html5Qrcode
onMount(init)
function init() {
html5Qrcode = new Html5Qrcode('reader')
}
function start() {
html5Qrcode.start(
{ facingMode: 'environment' },
{
fps: 10,
qrbox: { width: 250, height: 250 },
},
onScanSuccess,
onScanFailure
)
scanning = true
}
async function stop() {
await html5Qrcode.stop()
scanning = false
}
function onScanSuccess(decodedText, decodedResult) {
alert(`Code matched = ${decodedText}`)
console.log(decodedResult)
}
function onScanFailure(error) {
console.warn(`Code scan error = ${error}`)
}
</script>
<style>
main {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 20px;
}
reader {
width: 100%;
min-height: 500px;
background-color: black;
}
</style>
<main>
<reader id="reader"/>
{#if scanning}
<button on:click={stop}>stop</button>
{:else}
<button on:click={start}>start</button>
{/if}
</main>
Special thanks to the author of the wonderful Html5Qrcode lib.
Honorable mention to quagga. No longer actively maintained, but there is an active fork quagga2.
asaf! thanks for reading🥰
[update]: the demo is not a pwa, but the scanner lib and camera access will work if you decide to make a pwa for your own project.
Top comments (0)