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">
    <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="">
        <!-- Stream video via webcam -->
        <div class="video-wrap">
            <video id="video" playsinline autoplay></video>

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

        <!-- Webcam video snapshot -->
        <canvas id="canvas" width="100" height="100"></canvas>
      '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);
      } catch (e) {
          errorMsgElement.innerHTML = `navigator.getUserMedia error:${e.toString()}`;
  // Success
  function handleSuccess(stream) { = stream;
      video.srcObject = stream;
  // Load init
  // Draw image
  var context = canvas.getContext('2d');
  snap.addEventListener("click", function() {
      context.drawImage(video, 0, 0, 640, 480);

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', () => {

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