scale HTML5 Video and break aspect ratio to fill whole site

后端 未结 9 2121
爱一瞬间的悲伤
爱一瞬间的悲伤 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).

提交回复
热议问题