循环时HTML画布内的视频闪烁

时间:2019-02-20 08:53:06

标签: javascript html5 canvas video

我正在尝试在canvas内显示视频,并loop播放视频。循环播放视频时有时会出现此问题。在再次播放视频之前,视频会闪烁一帧。这不是一直发生,我也不知道发生了什么。

这是代码

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

canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

let src = "https://i.imgur.com/5ZiAeSX.mp4";
let video = document.createElement("video");
video.src = src;
video.muted = true;
video.play();

video.onended = () => {
  video.play();
};

function render() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.drawImage(video, 0, 0);

  requestAnimationFrame(render);
}

render();

您也可以尝试fiddle here

2 个答案:

答案 0 :(得分:1)

这是因为循环MediaElement绝不是无缝的操作。 当looping audio media时,这种声音尤其明显。

通常,当在

但是,由于您确实清除了画布,因此在您的情况下它变得非常明显,但是没有视频帧可以绘制在画布上。因此会引起大的白色闪光。

一个简单的解决方法是检查currentTime是否为0并在这段时间内不重绘:

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

canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

let src = "https://i.imgur.com/5ZiAeSX.mp4";
let video = document.createElement("video");
video.src = src;
video.muted = true;
video.play();

let missed_frames = 0; // only for demo
video.onended = () => {
  video.play();
  // only for demo
  setTimeout(() => {
  _log.textContent = 'missed ' + missed_frames +' frames while looping';
  missed_frames = 0;
  }, 200);
};


function render() {
  if(video.currentTime) {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
	  ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
  }
  // only for demo
  else {
    missed_frames++;
  }
  requestAnimationFrame(render);
}

render();
#_log { color: white; position: absolute; }
<pre id="_log"></pre>
<canvas></canvas>

如果您确实需要无缝循环,则更难的解决方法是使用MediaSource对象,但是如果不是真正需要的话,设置起来会很麻烦。

答案 1 :(得分:0)

您可以将viedo.loop设置为true,并在继续播放视频时避开该部分。

我已经通过这种方式完成了技巧:

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

canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

let src = "https://i.imgur.com/5ZiAeSX.mp4";
let video = document.createElement("video");
video.src = src;
video.muted = true;
video.videoHeight = '500px'; // returns the intrinsic height of the video
video.videoWidth =  '100px'; // returns the intrinsic width of the video
video.play();
video.loop = true

/* video.onended = () => {
  video.play();
}; */

function render() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.drawImage(video, 0, 0);

  requestAnimationFrame(render);
}

render();

这就是为什么您的视频闪烁,不循环,只是反复播放的原因。 试试看;)