强制HTML视频元素的常量维度,无论源

时间:2015-09-08 11:47:27

标签: javascript css html5 video

我正在尝试做一个不那么简单的任务。我想在一个HTML5页面中有一个具有恒定宽度和高度(窗口的)的视频元素,它可以管理源视频的尺寸和宽高比,最好显示,也就是说完全覆盖的窗口视频,没有滚动条。

我写了这个javascript代码:

 $("video").bind("loadedmetadata", function () {
      var screenSize = {}, videoSize = {};
      videoSize["width"] = this.videoWidth;
      videoSize["height"] = this.videoHeight;
      screenSize["height"] = $( window ).height();
      screenSize["width"] = $( window ).width();

      var ratio_screen = screenSize["width"]/screenSize["height"];
      var ratio_video = videoSize["width"]/videoSize["height"];

        if (ratio_video > ratio_screen) {
          $("video").height(screenSize["height"]);
          $("video").width(screenSize["height"]*ratio_screen);
        } 
        else 
          {
          $("video").width(screenSize["width"]);
          $("video").height(screenSize["width"]/ratio_screen);
            }

        });

目前,我有一个视频元素,几乎适合窗口(我仍然有一个边框或边距,检查员说它是html元素的一部分)。但源视频适合视频元素!作为我的测试视频比屏幕更宽的一个例子,我在视频上方和下面都有黑色条带。

如何管理此项以“缩放”视频。我是否必须将缩放因子应用于视频元素,或者可以在源视频级别进行somenthing。

由于

1 个答案:

答案 0 :(得分:0)

最后这段代码起作用了:

$("video").on('canplay',function() {
  $("video").bind("loadedmetadata", function () {
      var screenSize = {}, videoSize = {};

      videoSize["width"] = this.videoWidth;
      videoSize["height"] = this.videoHeight;
      screenSize["height"] = $( window ).height();
      screenSize["width"] = $( window ).width();

      var ratio_screen = screenSize["width"]/screenSize["height"];
      var ratio_video = videoSize["width"]/videoSize["height"];

      if (ratio_video > ratio_screen) {
        $("video").css("-webkit-transform", "scale("+ratio_video/ratio_screen+")");
        $("video").height(screenSize["height"]);
        $("video").width(screenSize["height"]*ratio_screen);
      } else {
        $("video").css("-webkit-transform", "scale("+ratio_video/ratio_screen+")");
        $("video").width(screenSize["width"]);
        $("video").height(screenSize["width"]/ratio_screen);
      }
  });
});

如果宽高比不适合屏幕之一,则会导致显示视频,填满整个屏幕,而不会拉伸视频。 请注意,我的视频元素在循环中播放多个源。播放的第一个视频不适用于此调整大小功能(我必须对此进行处理,以确保启动时有效)。