跳到主要内容

如何在 Canvas 上显示视频

如需在 Canvas 上绘制视频,可以使用 <video> DOM 元素,其用法与 <img> 元素类似,但必须频繁重绘图层。为此,可以使用 Konva.Animation。也可以使用 requestAnimationFrame,并调用 layer.draw()

如需了解更多信息,另请参阅这篇文章:案例研究:流媒体视频编辑器

以下示例展示如何使用播放/暂停控件在 Canvas 上显示视频。你还可以在 Canvas 上拖放视频。

import Konva from 'konva';

// create buttons
const playButton = document.createElement('button');
playButton.textContent = 'Play';
playButton.id = 'play';
document.body.appendChild(playButton);

const pauseButton = document.createElement('button');
pauseButton.textContent = 'Pause';
pauseButton.id = 'pause';
document.body.appendChild(pauseButton);

const width = window.innerWidth;
const height = 300;

const stage = new Konva.Stage({
container: 'container',
width: width,
height: height,
});

const layer = new Konva.Layer();
stage.add(layer);

const video = document.createElement('video');

const image = new Konva.Image({
image: video,
draggable: true,
x: 50,
y: 20,
});
layer.add(image);

const text = new Konva.Text({
text: 'Loading video...',
width: stage.width(),
height: stage.height(),
align: 'center',
verticalAlign: 'middle',
});
layer.add(text);

const anim = new Konva.Animation(function () {
// do nothing, animation just needs to update the layer
}, layer);

// update Konva.Image size when meta is loaded
video.addEventListener('loadedmetadata', function () {
text.text('Press PLAY...');
image.width(video.videoWidth);
image.height(video.videoHeight);
});
video.src =
'https://upload.wikimedia.org/wikipedia/commons/transcoded/c/c4/Physicsworks.ogv/Physicsworks.ogv.240p.vp9.webm';

document.getElementById('play').addEventListener('click', function () {
text.destroy();
video.play();
anim.start();
});
document.getElementById('pause').addEventListener('click', function () {
video.pause();
anim.stop();
});

此示例展示如何:

  1. 创建视频元素,并将其用作 Konva.Image 的源
  2. 为视频实现播放/暂停控件
  3. 在视频播放时使用 Konva.Animation 持续更新图层
  4. 使视频可在 Canvas 上拖动
  5. 显示加载和播放状态消息
  6. 处理视频元数据以设置正确尺寸

尝试播放视频并在 Canvas 上拖动它。移动视频时,视频会继续播放。