Getting a Video''s Aspect Ratio with loadedmetadata in JavaScript

Tech Sharing 2023-12-11
Getting a Video''s Aspect Ratio with loadedmetadata in JavaScript

Create a video element and listen for loadedmetadata; once metadata loads, read videoWidth/videoHeight and divide to get the aspect ratio.

1. Create a

2. Listen for loadedmetadata, fired after metadata loads, when the video''s width and height become available.

3. Compute the aspect ratio, usually width divided by height.

// create the video element
var video = document.createElement('video');

// set the source
video.src = 'path/to/your/video.mp4'; // replace with your path

// load metadata
video.addEventListener('loadedmetadata', function() {
  var width = video.videoWidth;
  var height = video.videoHeight;
  var aspectRatio = width / height;
  console.log('Aspect ratio:', aspectRatio);
});

// to display the video, append it to the DOM
// document.body.appendChild(video);