Skip to main content

Angular Konva 简单动画教程

Konva 提供了两个主要的动画工具:node.to() 用于简单过渡,Konva.Animation 用于逐帧更新。

此示例直接使用 Konva.Animation 在视图初始化后以正弦波方式移动圆形。

说明:演示使红色圆形持续左右移动。

了解更多详情,请参阅 动画文档节点 API 参考

简单动画示例

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