为移动设备(jam3)调整内联视频大小以实现对象适配:封面

Inline video resize for mobile (jam3) to achieve object-fit: cover

本文关键字:实现 对象 封面 视频 移动 jam3 调整      更新时间:2023-09-26

我正在尝试https://github.com/Jam3/ios-video-test为我的目的工作。

我想让视频缩放并覆盖移动设备和桌面上的整个视口,就像一个适合对象的东西:覆盖或高度:100%和宽度自动(目前它缩放以适合宽度)

我改变了这个。。。

 resize()
  window.addEventListener('resize', resize, false)
  function resize () {
    var width = document.documentElement.clientWidth
    var height = document.documentElement.clientHeight
    letterbox(canvas, [
      width, height
    ], canvasVideo.video)
  }
  // resize and reposition canvas to form a letterbox view
  function letterbox (element, parent, video) {
    var aspect = video.videoWidth / video.videoHeight
    var pwidth = parent[0]
    var pheight = parent[1]
    var width = pwidth
    var height = Math.round(width / aspect)
    var y = Math.floor(pheight - height) / 2
    // this is a fix specifically for full-screen on iOS9
    // without it, the status bars will not hide... O.o
    if (canvasVideo.fallback) height += 1
    element.style.top = y + 'px'
    element.style.width = width + 'px'
    element.style.height = height + 'px'
  }

破解这个(我不会撒谎,我真的对自己在做什么知之甚少)。。。

   var width = Math.round(height / aspect)
   var height = pheight
   var y = Math.floor(pheight - height) / 2

它只在一定程度上起作用(在移动设备上很好,但它并没有真正覆盖宽的桌面视口)

非常感谢你的帮助!

因此,如果有人遇到类似问题,解决方案是…

  // resize and reposition canvas to form a letterbox view
  function letterbox (element, parent, video) {
    var aspect = video.videoWidth / video.videoHeight
    var parentWidth = parent[0]
    var parentHeight = parent[1]
    var parentAspectRatio = parentWidth / parentHeight
    var childWidth = video.videoWidth
    var childHeight = video.videoHeight
    var childAspectRatio = childWidth / childHeight
    var targetWidth = 0
    var targetHeight = 0
    if (parentAspectRatio > childAspectRatio) {

      targetWidth = parentWidth
      targetHeight = targetWidth / childAspectRatio
    } else {

     targetHeight = parentHeight
     targetWidth = targetHeight * childAspectRatio
    }
    element.style.width = targetWidth + 'px'
    element.style.height = targetHeight + 'px'
    element.style.left = -(targetWidth - parentWidth) / 2 + 'px'
    element.style.top = -(targetHeight - parentHeight) / 2 + 'px'
  }