Kristian Vitozev
Kristian Vitozev

Reputation: 5971

Get width and height of HTML5 Video using native JavaScript

I am trying to get width and height of tag, I am using the following markup:

<div class="masked" id="video_container">
    <video id="video" loop="loop" muted="muted" tabindex="0" style="width: 100%; height: 100%;">
        <source src="..." type="..."</source>
        <source src="..." type="..."</source>
    </video>
</div>

The key part is that width and height attributes are both set to 100%, and when window is changed aspect ratio of video is saved, but I cannot get it's actual width and height.

I tried to get value using offsetWidth and offsetHeight properties, but they are return actual size of the video.

Edit:

This is the piece of code that working for me:

var videoActualWidth = video.getBoundingClientRect().width;
var videoActualHeight = video.getBoundingClientRect().height;

var aspect = videoActualWidth / videoActualHeight;

if (w / h > aspect) {
    video.setAttribute("style", "height: 100%");
} else {
    video.setAttribute("style", "width: 100%");
}

Thanks!

Upvotes: 8

Views: 22884

Answers (1)

Karim Lee
Karim Lee

Reputation: 41

This code will give you the dimensions of the video tag (not the dimensions of the video itself)

var video = document.getElementById("video");
var videotag_width = video.offsetWidth;
var videotag_height = video.offsetHeight;

This code will give you the dimensions of the video that is currently playing

var video = document.getElementById("video");
var video_height = video.videoHeight;
var video_width = video.videoWidth;

Upvotes: 19

Related Questions