Skip to main content

Animate Position Tutorial

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

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);

const circle = new Konva.Circle({
x: 50,
y: window.innerHeight / 2,
radius: 30,
fill: 'red',
stroke: 'black',
strokeWidth: 4,
});
layer.add(circle);

const amplitude = 100;
const period = 2000; // in milliseconds


const anim = new Konva.Animation(function(frame) {
circle.x(
amplitude _ Math.sin((frame.time _ 2 \* Math.PI) / period) +
window.innerWidth / 2
);
}, layer);

anim.start();