Activate webcam on click. Help!

Hello, as you’ve already seen, I want to create a script to activate a webcam when a button is clicked. I’ve managed to create a script but it just starts when refreshing or loading the page but I want it to only activate when a button is clicked. Here’s the code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="PhoneProject.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <title>Document</title>
</head>
<body>
        <!-- Stream video via webcam -->
        <div class="video-wrap">
            <video id="video" playsinline autoplay></video>
        </div>

        <!-- Trigger canvas web API -->
        <div class="controller">
            <button id="snap">Capture</button>
        </div>

        <!-- Webcam video snapshot -->
        <canvas id="canvas" width="100" height="100"></canvas>
    </div>
    
    <script>
      'use strict';
  
  const video = document.getElementById('video');
  const canvas = document.getElementById('canvas');
  const snap = document.getElementById("snap");
  const errorMsgElement = document.querySelector('span#errorMsg');
  
  const constraints = {
      audio: true,
      video: {
          width: 300, height: 400
      }
  };
  
  // Access webcam
  async function init() {
      try {
          const stream = await navigator.mediaDevices.getUserMedia(constraints);
          handleSuccess(stream);
      } catch (e) {
          errorMsgElement.innerHTML = `navigator.getUserMedia error:${e.toString()}`;
      }
  }
  
  // Success
  function handleSuccess(stream) {
      window.stream = stream;
      video.srcObject = stream;
  }
  
  // Load init
  init();
  
  // Draw image
  var context = canvas.getContext('2d');
  snap.addEventListener("click", function() {
      context.drawImage(video, 0, 0, 640, 480);
  });
  </script>
</body>
</html>

Can’t you just put the init inside a click event listener?

Could you give me an example code, please?

You already have a button with a click event listener, you would do the same for this new button and just call init() inside the handler.

const startBtn = document.querySelector('#startBtn');

startBtn.addEventListener('click', () => {
  init();
});

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.