DEV Community

loading...
Cover image for How to use the webcam with Svelte JS

How to use the webcam with Svelte JS

Nelson Adonis Hernandez
Frontend Developer & Creator Content
・1 min read

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

Example repository in Github 🔗

Discussion (0)