首页 > 解决方案 > 全屏居中 html5 视频直播

问题描述

我想从我的设备的摄像头获得全屏实时提要,但要居中。所以如果我的脸在中间,我希望在任何设备上我的脸都在中间(无论纵横比(横向<->纵向))

HTML:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Picture time!</title>
    <link rel="stylesheet" href="./style.css">
</head>

<body>
    <video id="video" autoplay="autoplay" onclick="snapshot()"></video>
    <canvas id="canvas" style="display: none"></canvas>

    <script src="./jquery.min.js"></script>
    <script src="./script.js"></script>
</body>

</html>

CSS:

body {
    margin: 0;
    padding: 0;
    width: 100vw;
    height: 100vh;
    overflow: hidden;
}

#video {
    position: absolute;
}

进行重新缩放的 JS 函数:

function rescaleEverthing(){
    var jqueryVideo = $("#video");
    var body = $("body");

    var videoWidth = jqueryVideo.width();
    var videoHeight = jqueryVideo.height();
    var bodyWidth = body.width();
    var bodyHeight = body.height();

    var videoRatio = videoWidth / videoHeight;
    var bodyRatio = bodyWidth / bodyHeight;

    if(vi)
    if(videoRatio > bodyRatio){
        jqueryVideo.css("height", "100%");
        jqueryVideo.css("transform", "translateX(-" + (videoWidth-bodyWidth)/2 + "px)");
    } else {
        jqueryVideo.css("width", "100%");
        jqueryVideo.css("transform", "translateY(-" + (videoHeight-bodyHeight)/2 + "px)");
    }
}

但是当你运行这个时,我的视频中间不在纵向模式时的中间

有人可以帮忙吗?谢谢!

标签: htmlcssvideocenterfullscreen

解决方案


你不需要 JS 来做,看看object-fit选项:

body {
  margin: 0;
  padding: 0;
  width: 100vw;
  height: 100vh;
  overflow: hidden;
  position:relative;
}

video {
  width:100%; height:100%;
  object-fit: contain;
}
<video video-player controls id="video_player" src="http://dash.akamaized.net/akamai/bbb/bbb_1280x720_60fps_6000k.mp4"></video>


推荐阅读