Skip to main content

How to apply canvas animations with React and Konva?

Konva itself has two methods for animations: Tween and Animation. You can apply both of them to nodes manually.

For simple use cases we recommend using the node.to() method. For more complex animations take a look at the Complex react-konva animation demo.

The demo is using the refs API to access shape instances directly.

Instructions: Try to drag the rectangle to see it animate.

import React, { Component } from 'react';
import { Stage, Layer, Rect } from 'react-konva';

class MyRect extends React.Component {
  changeSize = () => {
    // to() is a method of `Konva.Node` instances
    this.rect.to({
      scaleX: Math.random() + 0.8,
      scaleY: Math.random() + 0.8,
      duration: 0.2,
    });
  };

  render() {
    return (
      <Rect
        ref={(node) => {
          this.rect = node;
        }}
        width={50}
        height={50}
        fill="green"
        draggable
        onDragEnd={this.changeSize}
        onDragStart={this.changeSize}
      />
    );
  }
}

const App = () => {
  return (
    <Stage width={window.innerWidth} height={window.innerHeight}>
      <Layer>
        <MyRect />
      </Layer>
    </Stage>
  );
};

export default App;