We often use webcams to broadcast video in real time via our computer. This broadcast can be viewed, saved and even shared via the Internet. As a rule, we need software to access the webcam and stream video. But you can also stream video on websites without using third-party software.
The HTML5 method getUserMedia()
, will help us to show a preview of the webcam video via Javascript. If your application needs to access the webcam to stream video, you can do it easily with HTML5 and Javascript with this tutorial. In short, we will show you how to access the webcam and capture video using HTML5 and Javascript.
getUserMedia() API
The getUserMedia()
method of the MediaDevices API helps you to produce a MediaStream containing the requested media types. You can use getUserMedia to open a dialog window to request permissions from the user to use their webcam to capture an image using HTML5 and Javascript.
The HTML
The following HTML code embeds a video element and draws an image on the page.
- We will use the HTML5 <video> element to embed a video on the page.
- We will use the <canvas> element to draw the capture of the webcam video on the page.
- The button (snap) will execute the generation of the image capture on the video.
<!-- 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="640" height="480"></canvas>
Javascript code
The following Javascript manages the process of streaming video through the webcam on the web page.
- The constants define the width and height of the video.
- The init() function initialises the getUserMedia() API.
- The handleSuccess() function streams the webcam video into the HTML element.
- We use the canvas API to draw the webcam capture.
'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: 1280, height: 720 } }; // 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); });