Skip to main content

HTML5 Canvas Konva Scale Animation Tutorial

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

In this tutorial, we'll scale the x and y component of a blue hexagon, the y component of a yellow hexagon, and the x component of a red hexagon about an axis positioned on the right side of the shape.

Instructions: drag and drop the hexagons as they animate

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 hexagon - scale x and y

const blueHex = new Konva.RegularPolygon({
x: 50,
y: 50,
sides: 6,
radius: 20,
fill: '#00D2FF',
stroke: 'black',
strokeWidth: 4,
draggable: true
});

// yellow hexagon - scale y only

const yellowHex = new Konva.RegularPolygon({
x: 150,
y: 50,
sides: 6,
radius: 20,
fill: 'yellow',
stroke: 'black',
strokeWidth: 4,
draggable: true
});

// red hexagon - scale x only

const redHex = new Konva.RegularPolygon({
x: 250,
y: 50,
sides: 6,
radius: 20,
fill: 'red',
stroke: 'black',
strokeWidth: 4,
draggable: true
});

layer.add(blueHex);
layer.add(yellowHex);
layer.add(redHex);

const period = 2000;

const anim = new Konva.Animation(function(frame) {
const scale = Math.sin(frame.time _ 2 _ Math.PI / period) + 2;

// blue hex - scale x and y

blueHex.scale({ x: scale, y: scale });

// yellow hex - scale y only

yellowHex.scaleY(scale);

// red hex - scale x only

redHex.scaleX(scale);
}, layer);

anim.start();