【问题标题】:How to keep an HTML5 video rendering when out of view?看不见时如何保持 HTML5 视频渲染?
【发布时间】:2020-01-16 16:01:46
【问题描述】:

在 Android 版 Chrome 上(以及桌面版 Chrome 上的设备模拟模式),当 <video> 滚动出视图时,浏览器似乎会暂停渲染。但我需要视频继续播放,因为我的代码不断地从视频中抓取帧以绘制到具有实时视频效果的<canvas>,即使源视频滚动,画布仍然可以向用户显示看不见。

下面是显示问题的 MCVE。编写 MCVE 是为了简单地将视频复制到画布上,而不应用视频效果。

问题在于,一旦视频元素滚动出视图,画布似乎就会冻结,因为它只是一遍又一遍地渲染相同的视频帧。

有没有办法让视频元素即使移出屏幕也能继续播放,或者有其他方法可以解决这个问题?

const video = document.querySelector("video");
const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");

function drawFrame() {
    // In the real code, video effects are applied here
    ctx.drawImage(video, 0, 0);
    requestAnimationFrame(drawFrame);
}
drawFrame();

if (video.readyState >= 2) setup();
else video.addEventListener("loadeddata", drawFrame);
.spacer {
  height: 200px;
}
<p>Video Element:</p>
<video src="https://thumbs.gfycat.com/ExemplaryShadowyBuffalo-mobile.mp4" width="640" height="360" autoplay muted loop></video>
<div class="spacer"></div>
<p>Canvas Output Element (with video effects in the real code):</p>
<canvas width="640" height="360"></canvas>

【问题讨论】:

    标签: google-chrome video html5-video video-processing chrome-for-android


    【解决方案1】:

    有声音的视频不会自动暂停,因此在某些情况下可以取消视频静音,但即使将音量设置为 0 也会使其表现为静音...所以您还必须体验一些噪音.

    但无论如何,您当前的视频在这里没有任何音频通道,因此简单地取消静音是行不通的。

    但是,您可以将绘图视频排除在 DOM 之外:

    // we do clone the visible element, and we keep that clone offscreen
    const video = document.querySelector("video").cloneNode();
    video.play();
    const canvas = document.querySelector("canvas");
    const ctx = canvas.getContext("2d");
    
    function drawFrame() {
        // In the real code, video effects are applied here
        ctx.drawImage(video, 0, 0);
        requestAnimationFrame(drawFrame);
    }
    drawFrame();
    
    if (video.readyState >= 2) setup();
    else video.addEventListener("loadeddata", drawFrame);
    .spacer {
      height: 200px;
    }
    <p>Video Element:</p>
    <video src="https://thumbs.gfycat.com/ExemplaryShadowyBuffalo-mobile.mp4" width="640" height="360" autoplay muted loop></video>
    <div class="spacer"></div>
    <p>Canvas Output Element (with video effects in the real code):</p>
    <canvas width="640" height="360"></canvas>

    【讨论】:

      猜你喜欢
      • 2018-08-12
      • 1970-01-01
      • 1970-01-01
      • 2011-09-19
      • 2016-02-20
      • 1970-01-01
      • 1970-01-01
      • 2014-10-15
      • 2018-07-10
      相关资源
      最近更新 更多