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.
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>
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');
}
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();
}
Accessing webcam requires your site to be served via HTTPS or on localhost
. Browsers block access otherwise.
canvas
or filtersface-api.js
or TensorFlow.js
for face detection