Search code examples
javascripthtmlwebrtc

Displaying video using WebRTC in javascript


I am currently learning how to utilize WebRTC in javascript.
Here are the codes I wrote:

main.html

<!DOCTYPE html>
<header>
  <title>video and audio</title>
  <style>
    html {
      height: 100%;
    }
    body {
      min-height: 100%;
      height: 100%;
      margin: 0;
    }

    #video {
      height: 50%;
      width: 50%;
      border: 1px solid black;
    }
    #audio {
      height: 50%;
      width: 50%;
      border: 1px solid black;
    }
  </style>
</header>
<body>
  <div id="video"></div>
  <div id="audio"></div>
</body>
<script src="WebRTC.js" type="text/javascript"></script>
</html>

WebRTC.js

const constraints = {audio: true, video: {width: 1280, height: 70}}

navigator.mediaDevices.getUserMedia(constraints)
.then (
  (mediaStream) => {
    console.log('success')
    const video = document.querySelector('#video');
    video.srcObject = mediaStream;
    video.onloadedmetadata = () => {video.play();}
  })
.catch (
  console.log('unsuccessful')
)

When I open it, it asks me permission to access my camera, and the console returns "successful." So I think that the code is working fine However, the video is not displayed on the <div id="video">. I googled the solution, but I have come up with nothing yet. I would be appreciated it if you could help me find what I am missing here. Thank you very much.


Solution

  • It's not working because you are using a div tag instead of a video tag.

    Just use the video tag below.

    <video id="video"></video>