Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting width and height of html video stream in js

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>
like image 314
bdei Avatar asked Sep 19 '25 01:09

bdei


1 Answers

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>

like image 181
blex Avatar answered Sep 20 '25 16:09

blex