Search code examples
javascriptreactjsfrontendkonvajsreact-konva

Animating a GIF on Canvas using react-konva


I am trying to create a UI for an application using react. I have am using react-konva for creating a 2D canvas. I have figured out how to import an image onto this canvas but am having trouble trying to animate a gif. There is documentation for how to do it in konva but I can't seem to be able to convert it to react-konva.

The documentation to do it in konva is given here.


Solution

  • import React from "react";
    import { render } from "react-dom";
    import { Stage, Layer, Image } from "react-konva";
    // gifler will be imported into global window object
    import "gifler";
    
    const GIF = ({ src }) => {
      const imageRef = React.useRef(null);
      const canvas = React.useMemo(() => {
        const node = document.createElement("canvas");
        return node;
      }, []);
    
      React.useEffect(() => {
        // save animation instance to stop it on unmount
        let anim;
        window.gifler(src).get(a => {
          anim = a;
          anim.animateInCanvas(canvas);
          anim.onDrawFrame = (ctx, frame) => {
            ctx.drawImage(frame.buffer, frame.x, frame.y);
            imageRef.current.getLayer().draw();
          };
        });
        return () => anim.stop();
      }, [src, canvas]);
    
      return <Image image={canvas} ref={imageRef} />;
    };
    
    class App extends React.Component {
      render() {
        return (
          <Stage width={window.innerWidth} height={window.innerHeight}>
            <Layer>
              <GIF src="https://konvajs.org/assets/yoda.gif" />
            </Layer>
          </Stage>
        );
      }
    }
    
    render(<App />, document.getElementById("root"));
    

    Demo: https://codesandbox.io/s/react-konva-gif-animation-p86qr