mebjas / html5-qrcode

A cross platform HTML5 QR code reader. See end to end implementation at: https://scanapp.org
https://qrcode.minhazav.dev
Apache License 2.0
5.1k stars 982 forks source link

Svelte example? #354

Open ralyodio opened 3 years ago

ralyodio commented 3 years ago

Can we add a svelte example?

mebjas commented 2 years ago

Looking for svelte expert to write a example / blog article into this.

paulbdavis commented 2 years ago

Not a full post, but we just did this, here's a quick and dirty example

<div id="reader"></div>

<script>
import { onDestroy, onMount } from 'svelte'
import {Html5Qrcode as Scanner, Html5QrcodeSupportedFormats as ScannerFormats} from "html5-qrcode"

// set camera label you want here if you have more than one
const docCameraLabel = 'blah blah'

// expose barcode data to other components
let barcodeData = ''

async function getQRData (scanner, deviceID) {

  return new Promise((resolve, reject) => {
    return scanner.start(deviceID, {
      fps: 10,
    }, (decodedText, decodedResult) => {
      resolve(decodedText)
    }, (msg, err) => {
      if (msg.indexOf("NotFoundException") >= 0) {
        return
      }
      reject(err)
    })  
  })

}

async function getCamera () {
  const scanner = new Scanner("reader", {
    formatsToSupport: [
      ScannerFormats.QR_CODE,
      ScannerFormats.PDF_417,
    ]
  }, false);
  try {
    const videoInputDevices = await Scanner.getCameras()
    for (let dev of videoInputDevices) {

      // you can log the device label here to see what to use above,
      // or just use the first one, etc.
      // console.log(dev.label)

      if (dev.label === docCameraLabel) {
        const data = await getQRData(scanner, dev.id)
        scanner.stop()
        return data
      }
    }
  } catch (err) {
    scanner.stop()
    throw err
  }
}

onMount(() => {
  getCamera().then(data => {
    console.log(data)
    barcodeData = data
  }, console.error)
})

onDestroy(() => {
  scanner.stop()
})

</script>

<style>
</style>
myleftshoe commented 2 years ago

Made a svelte mvp before I saw this.

<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>
mebjas commented 2 years ago

@myleftshoe would you be interested in contributing this guide to https://github.com/scanapp-org/html5-qrcode-svelte

Similar to:

If interested we can also include your article in https://scanapp.org/blog/ (it's hosted using Github pages)

myleftshoe commented 2 years ago

Happy to contribute with your guidance or using "similar to" as template (let me know which). OR feel free to copy my code and use it as you like!

El sáb, 7 may 2022 a las 15:51, minhaz @.***>) escribió:

@myleftshoe https://github.com/myleftshoe would you be interested in contributing this guide to https://github.com/scanapp-org/html5-qrcode-svelte

Similar to:

If interested we can also include your article in https://scanapp.org/blog/ (it's hosted using Github pages)

— Reply to this email directly, view it on GitHub https://github.com/mebjas/html5-qrcode/issues/354#issuecomment-1120140984, or unsubscribe https://github.com/notifications/unsubscribe-auth/AHYZVYCNSPFRGROFER2EBK3VIYAG3ANCNFSM5IFWQ5TQ . You are receiving this because you were mentioned.Message ID: @.***>

parker-codes commented 1 year ago

Here's one I created in case it helps anyone:

<script lang="ts">
  import { onMount, createEventDispatcher } from 'svelte';
  import {
    Html5QrcodeScanner,
    type Html5QrcodeResult,
    Html5QrcodeScanType,
    Html5QrcodeSupportedFormats,
    Html5QrcodeScannerState,
  } from 'html5-qrcode';

  export let width: number;
  export let height: number;
  export let paused: boolean = false;

  interface QrCodeScannerEvent {
    detect: { decodedText: string };
    error: { message: string };
  }
  const dispatch = createEventDispatcher<QrCodeScannerEvent>();

  function onScanSuccess(decodedText: string, decodedResult: Html5QrcodeResult): void {
    dispatch('detect', { decodedText });
  }

  // usually better to ignore and keep scanning
  function onScanFailure(message: string) {
    dispatch('error', { message });
  }

  let scanner: Html5QrcodeScanner;
  onMount(() => {
    scanner = new Html5QrcodeScanner(
      'qr-scanner',
      {
        fps: 10,
        qrbox: { width, height },
        aspectRatio: 1,
        supportedScanTypes: [Html5QrcodeScanType.SCAN_TYPE_CAMERA],
        formatsToSupport: [Html5QrcodeSupportedFormats.QR_CODE],
      },
      false // non-verbose
    );
    scanner.render(onScanSuccess, onScanFailure);
  });

  // pause/resume scanner to avoid unintended scans
  $: togglePause(paused);
  function togglePause(paused: boolean): void {
    if (paused && scanner?.getState() === Html5QrcodeScannerState.SCANNING) {
      scanner?.pause();
    } else if (scanner?.getState() === Html5QrcodeScannerState.PAUSED) {
      scanner?.resume();
    }
  }
</script>

<div id="qr-scanner" class={$$props.class} />

And can use it like so:

<QrCodeScanner
  on:detect={(e) => send({ type: 'DETECT', code: e.detail.decodedText })}
  paused={!$state.matches('scanning')}
  width={320}
  height={320}
  class="w-full max-w-sm"
/>