scale HTML5 Video and break aspect ratio to fill whole site

后端 未结 9 2065
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-29 06:31

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

相关标签:
9条回答
  • 2020-11-29 07:13

    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).

    0 讨论(0)
  • 2020-11-29 07:18

    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);
    
    0 讨论(0)
  • 2020-11-29 07:18

    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;
    }
    
    0 讨论(0)
提交回复
热议问题