Learn to Code via Tutorials on Repl.it!

← Back to all posts
Capture webcam video on webpage
remarkablemark (18)

Add <video> element with the autoplay attribute enabled:

<!-- index.html -->
<video autoplay></video>

Stream the video media using MediaDevices.getUserMedia():

// script.js
var constraints = { video: true };
var video = document.querySelector('video');
navigator.mediaDevices.getUserMedia(constraints).then(function(stream) {
  video.srcObject = stream;
});

Full example (see demo and code), which is inspired by the article "Capture Audio and Video in HTML5":

<!-- index.html -->
<video autoplay></video>
<script>
  var constraints = { video: true };
  var video = document.querySelector('video');
  navigator.mediaDevices.getUserMedia(constraints).then(function(stream) {
    video.srcObject = stream;
  });
</script>

This article was originally published on remarkablemark.org on December 17, 2020.