hub.eb?material_id=484&track_id=482

Accessing the Camera


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.

Steps


1

Create a form and insert a HTML Control and paste the following:

<video id="myVideo" width="320" height="240"></video>
2

Add a ready event handler to the Page Control and paste the code block from above.

3

Run the form and allow access to the camera when prompted.

Current Module

Related