Skip to main content

How to display video on Canvas

To draw a video on a canvas, we can use a <video> DOM element similar to an <img> element, but we have to frequently redraw the layer. For this purpose, we can use Konva.Animation. As an alternative, you can use requestAnimationFrame and just call layer.draw().

Also take a look at this post for additional information: Case Study: Video Editor for Stream

The demo below shows how to display a video on canvas with play/pause controls. You can also drag and drop the video around the 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');
video.src =
  'https://upload.wikimedia.org/wikipedia/commons/transcoded/c/c4/Physicsworks.ogv/Physicsworks.ogv.240p.vp9.webm';

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);
});

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

The demo shows how to:

  1. Create a video element and use it as the source for a Konva.Image
  2. Implement play/pause controls for the video
  3. Use Konva.Animation to continuously update the layer while the video is playing
  4. Make the video draggable on the canvas
  5. Display loading and play status messages
  6. Handle video metadata to set the correct dimensions

Try playing the video and dragging it around the canvas. The video will continue playing while you move it.