Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 863
Kristian Vitozev Avatar asked Apr 29 '13 07:04

Kristian Vitozev


1 Answers

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;
like image 187
3 revs, 3 users 71% Avatar answered Sep 18 '22 02:09

3 revs, 3 users 71%