Stretch html5 video without keeping aspect ratio i

2019-05-11 04:00发布

HTML5 videos have intrinsic aspect ratios and tend to keep it, no matter what your CSS tells them to do.

I have a responsive video container that isn't 16:9, and I'd like the videos inside it to stretch to 100% width and 100% height, even if it breaks their original aspect ratio.

I've read about the CSS object-fit: fill property, which would solve my problem, but there's still a long way to go before modern browsers support it. So I guess I must turn to JavaScript to achieve what I need.

I came across this fiddle:

http://jsfiddle.net/MxxAv/

function scaleToFill(videoTag) {
 var $video = $(videoTag),
    videoRatio = videoTag.videoWidth / videoTag.videoHeight,
    tagRatio = $video.width() / $video.height();
 if (videoRatio < tagRatio) {
        $video.css('-webkit-transform','scaleX(' + tagRatio / videoRatio  + ')')
 } else if (tagRatio < videoRatio) {
        $video.css('-webkit-transform','scaleY(' + videoRatio / tagRatio  + ')')
 }
}

$(function () {
 $("#testVideo").click(function(evt) {
    scaleToFill(document.getElementsByTagName("video")[0]);
 });
});

However, I can't seem to get this code to work. The console tells me the videoWidth property cannot be read.

1条回答
混吃等死
2楼-- · 2019-05-11 04:40

Quote from the HTML5 spec for <video> tags:

Video content should be rendered inside the element's playback area such that the video content is shown centered in the playback area at the largest possible size that fits completely within it, with the video content's aspect ratio being preserved. Thus, if the aspect ratio of the playback area does not match the aspect ratio of the video, the video will be shown letterboxed or pillarboxed. Areas of the element's playback area that do not contain the video represent nothing.

As for videoWidth specifically, it seems to be supported by all major browsers, so I'm not sure what your problem is there.

To the best of my knowledge, the CSS transforms as shown in the jsfiddle you linked are not standardised in terms of their effect when it comes to <video>, but they all worked for me in IE10, and latest Chrome and Firefox. I wonder, however, if you tried to use the jsfiddle on a browser that wasn't Chrome. The script you supplied only adds webkit transforms, so I have modified it to make transforms on other renderers and increased the ratio so as to make the effect more apparent.

Have a look at this new one. Hopefully it's what you wanted. In addition, here is a pure CSS one, as javascript really isn't required to make those changes unless you need to calculate the new ratio for some reason and can't have it static. The only issue is that the controls go out of sight, so I added an autoplay attribute.

查看更多
登录 后发表回答