简体   繁体   中英

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!

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM