Get Width and Height of HTML5 Video using JavaScript? - 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)

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

If you are trying to define the size of your video with java script im not sure what you are actually trying to do, althought it seems to me like you just want it to be customizable like this example.
If we presume the video was embedded the code below might do the trick
// Find all YouTube videos
var $allVideos = $("iframe[src^='//www.youtube.com']"),
// The element that is fluid width
$fluidEl = $("body");
// Figure out and save aspect ratio for each video
$allVideos.each(function() {
$(this)
.data('aspectRatio', this.height / this.width)
// and remove the hard coded width/height
.removeAttr('height')
.removeAttr('width');
});
// When the window is resized
$(window).resize(function() {
var newWidth = $fluidEl.width();
// Resize all videos according to their own aspect ratio
$allVideos.each(function() {
var $el = $(this);
$el
.width(newWidth)
.height(newWidth * $el.data('aspectRatio'));
});
// Kick off one resize to fix all videos on page load
}).resize();
You can also refer to this page how it actually works and there is also an CSS and HTML example of dynamic video rescaling as well:
https://css-tricks.com/NetMag/FluidWidthVideo/Article-FluidWidthVideo.php

Related

Why doesn't $(window).resize() work for me?

I'm working on a project and my goal is to make a video player with an embeded iframe be responsive when viewing on different screen sizes. I figure the best way to do it is using resize function. However, every time in the many different configurations I've tried to use the resize function it does not work. I expect the text to log to the console after every time the screen is resized, but instead it is not logged at all or only once when the screen is loaded and never again.
Why is this happening.
I know my jQuery is right because I log other things in different functions (like the width and height).
window.onload = function() {
$(document).ready(function(){
console.log(' <-GoT Here. You FOOL!');
var iframe = $('iframe');
var videoplayerW = iframe.width(); //640
var videoplayerH = $('iframe').height(); //150
console.log(videoplayerW, videoplayerH, ' <-This The width and height of iframe.'); //560 and 315
var ytplayer = $('#ytplayer');
console.log(ytplayer.width(), ytplayer.height(), ' <-This is the ytplayer demonsions'); //undefined
iframe.each(function(){
$(this)
.attr('style', this.height, this.width)
.removeAttr('height')
.removeAttr('width');
});
console.log(iframe.width());
});
}
$(document).ready(function(){
$(window).resize(function(){
console.log('Should have a bunch of numbers');
});
});

jQuery Fluid Videos - in Wordpress

I'm using the script form this website.
https://css-tricks.com/NetMag/FluidWidthVideo/Article-FluidWidthVideo.php
// Find all YouTube videos
var $allVideos = $("iframe[src^='//www.youtube.com']"),
// The element that is fluid width
$fluidEl = $("body");
// Figure out and save aspect ratio for each video
$allVideos.each(function() {
$(this)
.data('aspectRatio', this.height / this.width)
// and remove the hard coded width/height
.removeAttr('height')
.removeAttr('width');
});
// When the window is resized
$(window).resize(function() {
var newWidth = $fluidEl.width();
// Resize all videos according to their own aspect ratio
$allVideos.each(function() {
var $el = $(this);
$el
.width(newWidth)
.height(newWidth * $el.data('aspectRatio'));
});
// Kick off one resize to fix all videos on page load
}).resize();
How can I take this jQuery script and modify with Wordpress? I'm putting it inside of a script tag at the bottom of my page on a document ready. In wordpress it says to use jQuery instead of $. How do I call my variables then as well as define them? Where does $fluidEl come from?

Resizing videoJS, container resized, but actual vid still original size

I am resizing my videojs player on window.resize
The black "video container", if you will, gets resized, but the actual video, stays the same size. It will now shrink inside its container (resized), or overlap its container (resized to smaller).
A page reload rebuilds the player and it plays within its new bounds.
How do I tell it to re-initialize on the new size, without a page reload.
What makes this extra interesting, is that it seems to work when running on my localhost, development web-server. Running it on on-line hosting, renders above issues.
function redrawVideoPlayer() {
var newHeight
var newWidth
newWidth = $(window).width() * 0.33;
newHeight = newWidth * 0.75;
$('#ytvidplayer').css('height', newHeight);
$('#ytvidplayer').css('width', newWidth);
//set related video div height eual to video height
$('#related_vids_scroller').css('height', newHeight);
var myVideo = videojs('ytvidplayer');
myVideo.width(newWidth).height(newHeight);
myVideo.load();
myVideo.play();
}
I think this is a cool way to maintain your video's aspect ratio even after resizing events. Let's break it down:
You'll need a resize function that takes in the known aspect ratio of your video (in my code it is the 'dimensionsize' parameter passed into a resizeVideoJS() function as a string like so: '1920x760'. The other parameters are the initialized videoJS video object 'video' and the browser window object 'win'.) I'm passing in parameters because my code is broken into two modules, one module that handles action and helper functions - like resizeVideo or togglePoster, etc. - and the other is a widget that initializes and binds events to the video object. The resizeVideoJS() function is defined in the actions module and called in the widget.
So here is the code:
function resizeVideoJS( video, win, dimensionSize ) {
var width,
aspectRatio;
video.pause();
aspectRatio = _calculateAspectratio( dimensionSize );
width = video.width() <= 0 ? win.innerWidth : video.width();
video.height( width * aspectRatio );
}
function _calculateAspectratio( videoDimensionsStr ) {
var parts;
parts = videoDimensionsStr.split( 'x' );
return parts[ 1 ] / parts[ 0 ];
}
Next, I simply create a _resizeCallbackHelper() function in my widget that checks against resize events and fires off whenever they occur (although I also use Lodash's throttle function with it because resize events can fire off rapidly).
function _resizeCallbackHelper( ) {
if ( config[ screensize ].dimensions && win.innerWidth !== screen.windowWidth ) {
videoPoster ? dom.hide( videoPoster ) : false;
screen = videoAction.setScreenSizeInfoVariables( win );
_setVideoDimensions();
videoAction.resizeVideoJS( video, win, dimensionSize );
config[ screensize ].poster ? _setVideoPoster() : false;
}
}
A little explanation about the above _resizeCallbackHelper() function:
config[screensize] is a configuration object I create from data-settings="" inside the video tag in my html. This has all the settings of the video, like video.muted() or even video.dimensions. I made this as an object of nested objects, so that it looks like { Desktop: { dimensions: '1920x760', muted: true }, Mobile : { dimensions: '760x320', muted: false } }. But you can do it however you want. I just like this because it allows for custom settings across different devices. I define my dimensions and screensize using the below _setVideoDimensions() function where screen is an object with booleans telling which screen type the video is loading in. As you can see config[screensize] becomes either config['MOBILE'] or config['TABLET'] or config['DESKTOP'] in order to load those settings:
function _setVideoDimensions() {
screensize = screen.isHandheld ? ( screen.isMobile || screen.isLargeMobileDevice ? 'MOBILE' : 'TABLET' ) : 'DESKTOP';
dimensionSize = config[ screensize ].dimensions || desktop.dimensions;
}
The 'win.innerWidth !== screen.windowWidth' in the resize helper function is a check against resize events that fire in tablets when scrolling, even though the screen does not actually resize. This is a good thing to understand and know happens when scrolling in most tablets. Then I fire off some events that need to happen on resize, including the resizeVideoJS() function from the videoAction module - and notice I make sure to set the new video dimensions first with _setVideoDimensions().
Finally, I make sure to call the resize helper function on the resize event like so:
resizeCallback = throttle( _resizeCallbackHelper, 2000 );
$.on( 'window', 'resize', resizeCallback );
I hope this helps anyone coming across this problem.

Getting the real HTML5 video width and height

I have a video element:
var video = window.content.document.createElement("video");
video.width = width;
video.height = height;
video.style.backgroundColor = "black";
window.content.document.body.appendChild(video);
And I'm retrieving it's source via getUserMedia() on Firefox:
window.navigator.getMedia = ( window.navigator.getUserMedia || window.navigator.webkitGetUserMedia || window.navigator.mozGetUserMedia || window.navigator.msGetUserMedia);
window.navigator.getMedia( //constraints, sucessCallback, errorCallback
{video: true, audio: false},
function(stream) {
if (window.navigator.mozGetUserMedia)
video.mozSrcObject = stream;
else
{
var vendorURL = window.URL || window.webkitURL;
video.src = vendorURL.createObjectURL(stream);
}
video.play();
},
function(err) {
console.log("Error: " + err);
}
);
The problem is I need to know the "active area" of video, and it's returning me 0:
video.onloadedmetadata = function(){
console.log(this.width + "x" +this.height);
console.log(this.videoWidth + "x" +this.videoHeight);
}
So, how can I retrieve the REAL values?:
There are two issues here:
video.videoWidth and video.videoHeight properties weren't getting set as soon as the loadedmetadata event fired. This was a bug in FireFox, which is now fixed (thanks to #Martin Ekblom for pointing out the bug).
The video itself doesn't take up the whole area of the video element, which none of the answers seem to have addressed. Instead, it scales to fit inside the element.
I don't think there's a direct way to get the dimensions of the active area, but after struggling with this myself, I wrote up a solution to calculate it from the values we do know:
function videoDimensions(video) {
// Ratio of the video's intrisic dimensions
var videoRatio = video.videoWidth / video.videoHeight;
// The width and height of the video element
var width = video.offsetWidth, height = video.offsetHeight;
// The ratio of the element's width to its height
var elementRatio = width/height;
// If the video element is short and wide
if(elementRatio > videoRatio) width = height * videoRatio;
// It must be tall and thin, or exactly equal to the original ratio
else height = width / videoRatio;
return {
width: width,
height: height
};
}
Essentially, we take the aspect ratio of the video element, the aspect ratio of the video, and the dimensions of video element, and use those to determine the area the video is occupying.
This assumes the video's fitting method hasn't been modified via CSS (not sure if that's even possible at this time, but the spec allows for it). For more details on that and a few other things, see the blog post I wrote ("Finding the true dimensions of an HTML5 video’s active area"), inspired by this question and its lack of complete answers.
It's interesting to note that while the spec specifically mentions the possible edges around a video (letterboxing and pillarboxing), I wasn't able to find any other mentions of it, apart from your question.
You should add a loadeddata event listener to the video, and try to read the size then, which is when enough information about the stream has been decoded and the dimensions can be accurately determined.
Still, it sometimes takes a bit in some cases to get the dimensions ready, so you might want to try several times (with delay) until it works.
That might be why it is not working for you but it's working for Sam.
Here's how I check the video size, with several attempts if required, in my gumhelper library:
https://github.com/sole/gumhelper/blob/master/gumhelper.js#L38
Notice how we try several times and if it doesn't work we "give up" and default to 640x480.
"loadeddata" should only fire once. It's better to use "timeupdate" to repeatedly check if the video width and height have been set, in particular with getUserMedia where you don't really pause the video, but go straight into playback.
Actually this seems to be a bug in FF:
https://bugzilla.mozilla.org/show_bug.cgi?id=926753

Determine when the actual width/height of an element is changed

I'm dealing with some modals that are opened up in an iframe (same domain, so no xss issues). One of the modals I have either hides or shows options based on things you do which grows or shrinks the form. Anyway, long story short I have the code that handles resizing the iframe based on the current height/width of the body on the inital load. The problem is that I'm not sure what event to tap into to determine that the body's actual size has changed after the initial load.
Why not add a setInterval()? Something like:
var originalWidth = {set original width}
var originalHeight = {set original height};
setInterval(function(){
var currentWidth = {grab new values};
var currentHeight = {grab new values};
if(originalWidth !== currentWidth){
//Change the width now...
//Next, set originalWidth to be the same as current for future checks
originalWidth = currentWidth;
}
//Now, do the same for original and current height
},100)

Categories