DEV Community

Cover image for How to use the webcam with Svelte JS
Nelson Hernández
Nelson Hernández

Posted on • Edited on

How to use the webcam with Svelte JS

For this we use the binding property called this allows you to obtain a reference to the rendered elements such as Canva, Video, etc.

<script>
  let videoSource = null;
  let loading = false;
  const obtenerVideoCamara = async () => {
    try {
      loading = true;
      const stream = await navigator.mediaDevices.getUserMedia({
        video: true,
      });
      videoSource.srcObject = stream;
      videoSource.play();
      loading = false;
    } catch (error) {
      console.log(error);
    }
  };
</script>

<div>
  {#if loading}
    <h1>LOADING</h1>
  {/if}
  <!-- svelte-ignore a11y-media-has-caption -->
  <video bind:this={videoSource} />
  <button on:click={obtenerVideoCamara}>CLICK</button>
</div>
Enter fullscreen mode Exit fullscreen mode

GitHub

https://github.com/NelsonCode/webcam-svelte

Top comments (0)