Displaying and Capturing Video from Web Camera to HTML with WebRTC
Trying out WebRTC.
This is an updated version of the post from November 12, 2017, titled "Displaying Video from a Webcam to HTML via WebRTC Video Capture." Since iOS11, WebRTC has been compatible with mobile Safari. We created a demo in November 2017 that used a webcam to display and capture video in HTML. However, the JavaScript navigator.getUserMedia() method we used in the demo became deprecated, rendering video unviewable in iOS, Mac, and PC Safari browsers, among others. In this updated version, we recreated the demo using the new MediaDevices.getUserMedia() method, which replaces navigator.getUserMedia(). Audio is turned off, but you can view front and rear camera video/images on PC, tablet, and smartphone devices. For PCs, we've added a "Capture" button that allows you to download images (not available on mobile devices). Enjoy the videos/images with CSS filters. On PCs, you can drag the CSS filter controller if the browser's width is 992px or wider.
Code Examples
HTML
<!doctype html> <html lang="ja"> <style> #video { display: block; width: 100%; } </style> <head> <title>Title</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" type="text/css" href="style.css"> <body> <video id="video" autoplay playsinline></video> <script type="text/javascript" src="script.js"></script> </body> </html>
JavaScript
// For the front camera: var constraints = { audio: false, video: { facingMode: "user" } }; // For the rear camera: var constraints = { audio: false, video: { facingMode: { exact: "environment" } } }; navigator.mediaDevices.getUserMedia(constraints) .then(function(mediaStream) { var video = document.querySelector('video'); video.srcObject = mediaStream; video.onloadedmetadata = function(e) { video.play(); }; }) // Check for errors: .catch(function(err) { console.log(err.name + ": " + err.message); });
Credits
- Web Design Web Development WebRTC Coding
- Shozo Karato, AEDI Inc.