2

I'm trying to get width and height of video stream in html and js and it returns always zero, I dont want specify width and height in video tag, and always have what natural device video width and height is then check it's height and width is js, heres the code :

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<video autoplay="true"></video>
<script>
    let video = document.querySelector("video")
    navigator.mediaDevices.getUserMedia({video: true})
        .then((stream) => {
            video.srcObject = stream
        })

    function vid() {
        let vidCheck = document.querySelector("video")
        console.log(vidCheck.videoWidth) // returns 0
        console.log(vidCheck.videoWidth)//returns 0
    }

    vid()
</script>
</body>
</html>
bdei
  • 43
  • 1
  • 4
  • will this help ? https://stackoverflow.com/questions/4129102/html5-video-dimensions – KcH Jul 08 '20 at 03:42

4 Answers4

3

You're using the correct properties. You simply need to wait for the video to be playing for it to have a size:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Title</title>
  </head>
  <body>
    <video autoplay="true"></video>
    <script>
      let video = document.querySelector("video");
      navigator.mediaDevices.getUserMedia({ video: true }).then((stream) => {
        video.srcObject = stream;
      });

      video.addEventListener("playing", () => {
        console.log(video.videoWidth);
        console.log(video.videoHeight);
      });
    </script>
  </body>
</html>

blex
  • 24,941
  • 5
  • 39
  • 72
0

You can get the dimensions of an element by either its html attribute or its CSS properties using the following with your example.

Get width: vidCheck.offsetWidth

Get height: vidCheck.offsetHeight

Bren
  • 605
  • 4
  • 15
0

Just seek the video and you'll be able to read the variables:

video.currentTime = 1;
console.log(video.videoWidth);
console.log(video.videoWidth);
Nelson Teixeira
  • 6,297
  • 5
  • 36
  • 73
0

this code return 640 width and 480 height :

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Title</title>
  </head>
  <body>
    <video autoplay="true"></video>
    <script>
      let video = document.querySelector("video");
      navigator.mediaDevices.getUserMedia({ video: true }).then((stream) => {
        video.srcObject = stream;
      });

      video.addEventListener("playing", () => {
        console.log(video.videoWidth);
        console.log(video.videoHeight);
      });
    </script>
  </body>
</html>

But this code snippet returns different thing 300 and 150 :

Get width: vidCheck.offsetWidth

Get height: vidCheck.offsetHeight

to me looks like first one is correct but don't know the reason of difference .

bdei
  • 43
  • 1
  • 4
  • The natural size is the webcam's resolution. The offset size is the size you diplay it in the html – blex Jul 09 '20 at 08:47