Navigator Media Devices
It is a read-only property that returns a Media Devices object, which helps us to access the connected media input devices like the camera and microphone.
Syntax:
let mediaDevices = navigator.mediaDevices;
Return value:
The singleton object MediaDevices. The members of this object are typically used directly, such as by executing navigator.mediaDevices.getUserMedia().
Example: In this example, we will use a navigator.mediaDevices to open a webcam.
HTML
<!DOCTYPE html> < html lang = "en" > < head > < meta charset = "UTF-8" > < meta name = "viewport" content = "width=device-width, initial-scale=1.0" > < title >Document</ title > < style > div { width: 500px; height: 400px; border: 2px solid black; position: relative; } video { width: 500px; height: 400px; object-fit: cover; } </ style > </ head > < body > < div > < video id = "vid" ></ video > </ div > < br /> < button id = "but" autoplay> Open WebCam </ button > </ body > < script > document.addEventListener("DOMContentLoaded", () => { let but = document.getElementById("but"); let video = document.getElementById("vid"); let mediaDevices = navigator.mediaDevices; vid.muted = true; but.addEventListener("click", () => { // Accessing the user camera and video. mediaDevices .getUserMedia({ video: true, audio: true, }) .then((stream) => { // Changing the source of video to current stream. video.srcObject = stream; video.addEventListener("loadedmetadata", () => { video.play(); }); }) .catch(alert); }); }); </ script > </ html > |
Output :
How to open web cam in JavaScript ?
In this article, we will see how to open a webcam and show a live video using JavaScript. For this, we are going to use Navigator Media Devices.
Contact Us