Skip to main content

Angular Konva Simple Animations Tutorial

Konva provides two main animation tools: node.to() for simple transitions and Konva.Animation for frame-by-frame updates.

This example uses Konva.Animation directly to move a circle in a sine wave after the view initializes.

Instructions: The demo continuously animates the red circle left and right.

For more details, see the Animation docs and the Node API Reference.

Simple Animation Example

import { Component, ViewChild, OnInit, OnDestroy } from '@angular/core';
import { StageConfig } from 'konva/lib/Stage';
import { CircleConfig } from 'konva/lib/shapes/Circle';
import Konva from 'konva';

import {
CoreShapeComponent,
StageComponent,
} from 'ng2-konva';

@Component({
selector: 'app-root',
standalone: true,
template: `
<ko-stage [config]="configStage">
<ko-layer>
<ko-circle #circle [config]="configCircle"></ko-circle>
</ko-layer>
</ko-stage>
`,
imports: [StageComponent, CoreShapeComponent],
})
export default class App implements OnInit, OnDestroy {
@ViewChild('circle') circle!: any;
private animation: any = null;

public configStage: StageConfig = {
width: window.innerWidth,
height: window.innerHeight,
};
public configCircle: CircleConfig = {
x: 100,
y: 100,
radius: 50,
fill: 'red',
stroke: 'black',
strokeWidth: 4
};

ngAfterViewInit() {
const circle = this.circle.getNode();
this.animation = new Konva.Animation((frame: any) => {
const time = frame.time;
const x = 100 + Math.sin(time / 1000) * 100;
circle.x(x);
}, circle.getLayer());

this.animation.start();
}

ngOnDestroy() {
if (this.animation) {
this.animation.stop();
}
}
}