The MediaDevices API can be used to access media input devices from the browser, including cameras and microphones. The browser requests permission from the user before accessing the input device.
The following client-side code example demonstrates how to display video from a user's camera in a <video>
element with the id myVideo on the page:
// Request access to a camera
navigator.mediaDevices.getUserMedia({video: true})
.then(function(mediaStream) {
// Once access has been granted
// set the acquired stream to the video element with the id myVideo
var video = document.querySelector('#myVideo');
video.srcObject = mediaStream;
// Set the video element to play once the stream has loaded
video.onloadedmetadata = function(e) {
video.play();
};
})
// If something goes wrong or the user denies access, catch the error
.catch(function(err) { console.log(err.name + ": " + err.message); });
Additionally, the API can request to use either a front or rear facing camera by specifiying a facingMode
constraint.
See the MDN for more details.