I want to use a 4:3 video as a background on a site, but setting the width and height to 100% doesnt work, since the aspect ratio is kept intact, so the video doesnt fill th
After some struggling, this is what I ended up with. It will automatically scale the video in the right moment.
var videoTag = $('video').get(0);
videoTag.addEventListener("loadedmetadata", function(event) {
videoRatio = videoTag.videoWidth / videoTag.videoHeight;
targetRatio = $(videoTag).width() / $(videoTag).height();
if (videoRatio < targetRatio) {
$(videoTag).css("transform", "scaleX(" + (targetRatio / videoRatio) + ")");
} else if (targetRatio < videoRatio) {
$(videoTag).css("transform", "scaleY(" + (videoRatio / targetRatio) + ")");
} else {
$(videoTag).css("transform", "");
}
});
Just put that code in a $(document).ready()
block.
Tested on Chrome 53 , Firefox 49, Safari 9, IE 11 (IE does scale the video correctly, but might do other funny stuff around it though).
I use this to fill either width OR height... (requires jQuery) This KEEPS the aspect ratio and fills the div. I know the question was to break the aspect ration, but it isn't necessary.
var fillVideo = function(vid){
var video = $(vid);
var actualRatio = vid.videoWidth/vid.videoHeight;
var targetRatio = video.width()/video.height();
var adjustmentRatio = targetRatio/actualRatio;
var scale = actualRatio < targetRatio ? targetRatio / actualRatio : actualRatio / targetRatio;
video.css('-webkit-transform','scale(' + scale + ')');
};
as long as the <video>
has width and height set to 100%
and your container div has css overflow:hidden
just pass it the video tag.
var vid = document.getElementsByTagName("video")[0];
fillVideo(vid);
The correct CSS option for this is object-fit: contain;
The following example will stretch a background image across the width of the screen (while BREAKING the aspect ratio), and maintaining a constant fixed height.
body {
background-image:url(/path/to/background.png)
background-repeat: no-repeat;
background-position: top center;
background-size: 100% 346px;
object-fit: contain;
}
For a video in the OP's context it would then be:
video#vidtest {
width: 100%;
height: 100%;
object-fit: contain;
}