Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Width and Height of HTML5 Video using JavaScript?

I've tried several answers found here.

This code works in Firefox and outputs the right size, but not in Chrome or IE.

Mainly I am trying to get just the width.

Example

I have the output the width under the video using 3 examples.

https://jsfiddle.net/a8a1o8k2/

JavaScript

https://stackoverflow.com/a/4129189/6806643

var vid1 = document.getElementById("video");
vid1.videoHeight; // returns the intrinsic height of the video
vid1.videoWidth; // returns the intrinsic width of the video

returns 0

https://stackoverflow.com/a/9333276/6806643

var vid2 = document.getElementById("video");
vid2.addEventListener( "loadedmetadata", function (e) {
    var width = this.videoWidth,
        height = this.videoHeight;
}, false );

returns 0

https://stackoverflow.com/a/16461041/6806643

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

sometimes returns the correct value
sometimes returns 300 (default player size if no video source)

like image 455
Matt McManis Avatar asked Mar 18 '26 11:03

Matt McManis


1 Answers

Edit: improved solution after I have actually read the crossbrowser issue.

The solution below should work on both Chrome and Firefox. The issue is that Firefox treats readyState differently than Chrome.

var vid2 = document.getElementById("video");
vid2.addEventListener("loadedmetadata", getmetadata);

if (vid2.readyState >= 2) {
    getmetadata(vid2);
}

function getmetadata(){
    document.getElementById('output2').innerHTML = "Test 2: " + vid2.videoWidth;
}

Updated JSFiddle

like image 189
nbo Avatar answered Mar 20 '26 02:03

nbo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!