Skip to main content

How to animate GIF on Canvas

How to show animated GIF on canvas?

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 we will use gifler to parse and draw the gif. You can use any other library.

import Konva from 'konva';

// Load gifler library
const script = document.createElement('script');
script.src = 'https://unpkg.com/gifler@0.1.0/gifler.min.js';
document.head.appendChild(script);

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

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

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

script.onload = () => {
  gifler('/assets/yoda.gif').frames(canvas, onDrawFrame);
};

// draw resulted canvas into the stage as Konva.Image
const image = new Konva.Image({
  image: canvas,
});
layer.add(image);

Instructions: The demo shows an animated GIF rendered on canvas using the gifler library. The GIF is parsed and each frame is drawn onto a canvas, which is then used as the source for a Konva.Image shape.