【问题标题】:How to get better performance out of Html 5 video via canvas?如何通过画布从 Html 5 视频中获得更好的性能?
【发布时间】:2016-02-07 20:42:37
【问题描述】:

我的页面上有一个与画布元素一起使用的视频标签。我在视频中遇到了一些紧张/口吃。就播放而言,Chrome(出乎意料)是最差的,但我测试过的所有主要浏览器都难以流畅播放。

代码如下:

//This deals with drawing the video (the init is inside of a component not shown here)
function OnInit(e, f) {
  setTimeout(function() {
    var a = document.getElementById("video"),
      b = document.getElementById("canvas"),
      c = b.getContext("2d");
    a.addEventListener("loadedmetadata", function() {
      b.width = a.videoWidth;
      b.height = a.videoHeight
    });
    a.addEventListener("play", function() {
      var a = this;
      (function d() {
        a.paused || a.ended || (c.drawImage(a, 0, 0), setTimeout(d, 1E3 / 30))
      })()
    }, 0)
  }, 10)
};

//This mostly to prep the video for mobile/tablets  
function mobile() {
  var a = document.getElementsByTagName("video")[0];
  navigator.userAgent.match(/Android/i) || navigator.userAgent.match(/webOS/i) || navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPad/i) || navigator.userAgent.match(/iPod/i) || navigator.userAgent.match(/BlackBerry/i) || navigator.userAgent.match(/Windows Phone/i) || navigator.userAgent.match(/Opera Mini/i) || window.matchMedia("(max-device-width: 960px)").matches ? (document.getElementById("canvas").style.display = "none", a.removeAttribute("autoplay"),
    a.removeAttribute("loop")) : a.removeAttribute("controls");
}
video {
  width: 100%;
  height: 600px;
  object-fit: fill;
  -o-object-fit: fill;
}
<div style="background-image: url('../video.jpg'); background-repeat: no-repeat; background-size: 100% 600px;">
  <canvas id="canvas" style="width: 100%; height: 600px;"></canvas>
  <video id="video" autoplay="autoplay" controls="controls" loop="loop" poster="video.jpg" oncanplaythrough="mobile()">
    <source src="video.mp4" type="video/mp4" />
    <source src="video.webm" type="video/webm" />
    <img src="video.jpg" height="600" style="width: 100%;" />
  </video>
</div>

我还会注意到视频大小约为 25 MB (mp4) 和 5 MB (webm)。我尝试过 requestAnimationFrame 而不是设置超时但我并没有真正看到区别(尽管它可能没有像它应该的那样实现)。如果有人有任何建议,或者如果有什么我可以做得更好的,我很乐意倾听。在升级硬件之前,我希望首先提高代码的性能。谢谢。

【问题讨论】:

  • 为什么要在画布内渲染视频,而不是用透明背景将画布覆盖在视频上?
  • 如果我这样做,您认为与我现在的做法相比,它会提高性能吗?这是第一个对我有用的解决方案,基本上是我坚持使用这种方法的原因。我目前拥有的视频无法使用信箱,我不确定它是否会使用叠加层。
  • 不要使用 setTimeout,requestAnimationFrame 是你需要的。请向我们展示您的尝试。 ctx.drawImage 是一个非常快的方法,浏览器应该可以毫无问题地处理它
  • setTimeout(d, 1E3 / 30) 叫什么?您不是也在此处缺少的d 函数中执行绘图吗?
  • @ Kaiido 好的,我会尝试 requestAnimationFrame,但是我应该摆脱上面的哪个“设置间隔”(或者我应该摆脱两者以支持 requestAnimationFrame)?

标签: javascript html video canvas


【解决方案1】:

事实证明(出于某种原因)当我切换视频元素中的源标签时,它的效果非常好。感谢你们的贡献和投入。我还放入了 requestAnimationFrame 而不是 setTimeout,但将 webm 视频放在 mp4 视频之前似乎可以解决问题。

【讨论】:

    猜你喜欢
    • 2016-06-07
    • 2011-02-09
    • 1970-01-01
    • 2011-04-06
    • 2020-07-07
    • 2013-02-04
    • 1970-01-01
    • 2014-02-13
    • 1970-01-01
    相关资源
    最近更新 更多