Skip to main content

HTML5 Canvas Konva Stop Animation Tutorial

To stop an animation with Konva, we can use the stop() method. To restart the animation, we can again call the start().

Instructions: Click on "Start" to start the animation and "Stop" to stop the animation.

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: stage.width() / 2,
y: stage.height() / 2,
radius: 30,
fill: 'red',
stroke: 'black',
strokeWidth: 4,
});
layer.add(circle);

// add buttons

const startBtn = document.createElement('button');
startBtn.textContent = 'Start Animation';
document.body.appendChild(startBtn);

const stopBtn = document.createElement('button');
stopBtn.textContent = 'Stop Animation';
document.body.appendChild(stopBtn);

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

const amplitude = 100;
const period = 2000;

startBtn.addEventListener('click', () => anim.start());
stopBtn.addEventListener('click', () => anim.stop());