How to animate GIF on Canvas

Get last news, demos, posts from Konva

You can’t directly insert GIF image into the canvas. But we can use external library to parse the gif and then we can draw it into the layer as Konva.Image shape.

In this demo I will use gifler to parse and draw the gif. You can use any other library.

Konva GIF demoview raw
<!DOCTYPE html>
<html>
<head>
<script src="https://unpkg.com/[email protected]/konva.min.js"></script>
<script src="https://unpkg.com/[email protected]/gifler.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>
<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 canvas = document.createElement('canvas');
// use external library to parse and draw gif animation
function onDrawFrame(ctx, frame) {
// update canvas size
canvas.width = frame.width;
canvas.height = frame.height;
// update canvas that we are using for Konva.Image
ctx.drawImage(frame.buffer, 0, 0);
// redraw the layer
layer.draw();
}

gifler('/assets/yoda.gif').frames(canvas, onDrawFrame);

// draw resulted canvas into the stage as Konva.Image
var image = new Konva.Image({
image: canvas
});
layer.add(image);
</script>
</body>
</html>
Next