skip to Main Content

How to get the rendered size of an HTML5 <video> element?

The videoWidth and videoHeight properties, suggested as a solution on other similar (but different!) questions, return the intrinsic width and height, so they are not the solution.

The width and height properties, which are supposed to return the width and height of the display area, return 0, for some reason.

const video = document.querySelector("video");
console.log(video.width); //0
console.log(video.height); //0
<video src="https://upload.wikimedia.org/wikipedia/commons/4/48/Fine-tuned-Bee-Flower-Coevolutionary-State-Hidden-within-Multiple-Pollination-Interactions-srep03988-s6.ogv" controls></video>

Any suggestions?

2

Answers


  1. "How to get the rendered size of an HTML5 element?"

    You can try clientWidth and clientHeight to get the on-screen display size.
    The advantage is that you don’t need to wait for any metadata loading event.
    It’s just there already.

    For testing, you could add a width="" property to the video tag and see if clientWidth / clientHeight are doing what you want, whenever the rendered width/height is also changed.

    Kindly confirm if this meets your expected result..?

    const video = document.querySelector("video");
    console.log("video DISPLAY SIZE:");
    console.log("clientWidth: " + video.clientWidth); //300
    console.log("clientHeight: " + video.clientHeight); //150
    <video width="300" src="https://upload.wikimedia.org/wikipedia/commons/4/48/Fine-tuned-Bee-Flower-Coevolutionary-State-Hidden-within-Multiple-Pollination-Interactions-srep03988-s6.ogv" controls></video>
    Login or Signup to reply.
  2. you can listen to the loadedmetadata event of HTMLMediaElement

    const video = document.querySelector("video");
    video.addEventListener('loadedmetadata', () => {
      const rect = video.getBoundingClientRect();
      console.log(rect.width, rect.height);
      console.log(video.videoWidth, video.videoHeight);
    });
    <video src="https://upload.wikimedia.org/wikipedia/commons/4/48/Fine-tuned-Bee-Flower-Coevolutionary-State-Hidden-within-Multiple-Pollination-Interactions-srep03988-s6.ogv" controls></video>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search