๐Ÿ“ธ Add Webcam Functionality to a Web Page

This tutorial shows how to add webcam features including live streaming, snapshot capture, and video recording to a webpage using JavaScript and the getUserMedia API. We'll also apply a neat UI using Bootstrap.

๐ŸŽฅ 1. Basic Webcam Setup

Use the navigator.mediaDevices.getUserMedia() API to access the user's webcam. Below is a simple HTML and JavaScript example:

<video id="webcam" autoplay playsinline></video>
<button onclick="startWebcam()">Start Webcam</button>

<script>
async function startWebcam() {
  try {
    const stream = await navigator.mediaDevices.getUserMedia({ video: true });
    document.getElementById('webcam').srcObject = stream;
  } catch (err) {
    console.error('Error:', err);
  }
}
</script>

๐Ÿ“ท 2. Snapshot Capture

You can capture a frame from the video using a canvas element:

function takeSnapshot() {
  const video = document.getElementById('webcam');
  const canvas = document.getElementById('snapshotCanvas');
  const context = canvas.getContext('2d');
  canvas.width = video.videoWidth;
  canvas.height = video.videoHeight;
  context.drawImage(video, 0, 0);
  const image = canvas.toDataURL('image/png');
}

๐ŸŽฌ 3. Video Recording

Use the MediaRecorder API to record the video stream:

let mediaRecorder, recordedChunks = [];

function startRecording() {
  mediaRecorder = new MediaRecorder(stream);
  mediaRecorder.ondataavailable = e => recordedChunks.push(e.data);
  mediaRecorder.onstop = () => {
    const blob = new Blob(recordedChunks, { type: 'video/webm' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = 'recording.webm';
    a.click();
  };
  mediaRecorder.start();
}

function stopRecording() {
  mediaRecorder.stop();
}

๐Ÿงช Try It Live


๐Ÿ” Security Note

Accessing webcam requires your site to be served via HTTPS or on localhost. Browsers block access otherwise.

๐Ÿš€ Extensions