How to display video on Canvas

Get last news, demos, posts from Konva

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

Instructions: click “play” button. You can drag&drop the image.

Konva Video Demoview raw
<!DOCTYPE html>
<html>
<head>
<script src="https://unpkg.com/[email protected]/konva.min.js"></script>
<meta charset="utf-8" />
<title>Konva GIF Demo</title>
<style>
body {
margin: 0;
padding: 0;
overflow: hidden;
background-color: #f0f0f0;
}
</style>
</head>

<body>
<button id="play">Play</button><button id="pause">Pause</button>
<div id="container"></div>
<script>
var width = window.innerWidth;
var height = window.innerHeight;

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

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

var video = document.createElement('video');
video.src =
'http://download.blender.org/peach/bigbuckbunny_movies/BigBuckBunny_320x180.mp4';

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

// update Konva.Image size when meta is loaded
video.addEventListener('loadedmetadata', function(e) {
image.width(video.videoWidth);
image.height(video.videoHeight);
});

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

document.getElementById('play').addEventListener('click', function() {
video.play();
anim.start();
});
document.getElementById('pause').addEventListener('click', function() {
video.pause();
anim.stop();
});
</script>
</body>
</html>
Next