Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Svelte example? #354

Open
ralyodio opened this issue Nov 17, 2021 · 6 comments · May be fixed by #978
Open

Svelte example? #354

ralyodio opened this issue Nov 17, 2021 · 6 comments · May be fixed by #978

Comments

@ralyodio
Copy link

Can we add a svelte example?

@mebjas
Copy link
Owner

mebjas commented Dec 12, 2021

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

@paulbdavis
Copy link

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
Copy link

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
Copy link
Owner

mebjas commented May 7, 2022

@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
Copy link

myleftshoe commented May 8, 2022 via email

@parker-codes
Copy link

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"
/>

@Crazyglue Crazyglue linked a pull request Feb 7, 2025 that will close this issue
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.

5 participants