Is it possible to detect the aspect ratio of an HTML5 video element?
I know the video will just shrink to fit in the <video>
element's dimensions, but I want to detect the aspect ratio of the source video.
That way you could remove any black bars.
Sorry I don't see this answered anywhere else.
You can calculate the aspect ratio of a video by dividing the video's width by its height. However, to calculate the video resolution, you'll multiply the video's width by its height. A video with three different resolutions like 720p, 1080p, and 2160p can all have the same aspect ratio of 16:9.
In the HTML, put the player <iframe> in a <div> container. In the CSS for the <div>, add a percentage value for padding-bottom and set the position to relative, this will maintain the aspect ratio of the container. The value of the padding determines the aspect ratio. ie 56.25% = 16:9.
As another example, a portrait-style image might have a ratio of 2:3. With this aspect ratio, the height is 1.5 times longer than the width. So the image could be 500px × 750px, 1500px × 2250px, etc.
Pasting from another StackOverflow answer: https://stackoverflow.com/a/4129189/1353189
<video id="foo" src="foo.mp4"></video>
var vid = document.getElementById("foo");
vid.videoHeight; // returns the intrinsic height of the video
vid.videoWidth; // returns the intrinsic width of the video
Source (HTML5 spec): http://www.w3.org/TR/html5/video.html#video
You can then calculate the aspect ratio by dividing the width by the height.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With