Skip to main content

Rotation Animation tutorial

To animate a shape's rotation with Konva, we can create a new animation with Konva.Animation, and define a function which modifies the shape's rotation with each animation frame.

In this tutorial, we'll rotate a blue rectangle about the top left corner, a yellow rectangle about its center, and a red rectangle about an outside point.

For a full list of attributes and methods, check out the Konva.Animation documentation.

import Konva from 'konva';

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

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

// blue rectangle - rotate around top-left corner

const blueRect = new Konva.Rect({
x: 50,
y: 50,
width: 100,
height: 50,
fill: '#00D2FF',
stroke: 'black',
strokeWidth: 4,
offset: {
x: 0,
y: 0,
},
});

// yellow rectangle - rotate around center

const yellowRect = new Konva.Rect({
x: 200,
y: 50,
width: 100,
height: 50,
fill: 'yellow',
stroke: 'black',
strokeWidth: 4,
offset: {
x: 50,
y: 25,
},
});

// red rectangle - rotate around point outside shape

const redRect = new Konva.Rect({
x: 350,
y: 50,
width: 100,
height: 50,
fill: 'red',
stroke: 'black',
strokeWidth: 4,
offset: {
x: -50,
y: 25,
},
});

layer.add(blueRect);
layer.add(yellowRect);
layer.add(redRect);

const angularSpeed = 90;
const anim = new Konva.Animation(function(frame) {
const angleDiff = (frame.timeDiff \* angularSpeed) / 1000;
blueRect.rotate(angleDiff);
yellowRect.rotate(angleDiff);
redRect.rotate(angleDiff);
}, layer);

anim.start();