Skip to main content

旋转动画教程

要使用 Konva 制作形状的旋转动画,我们可以通过 Konva.Animation 创建一个新的动画,并定义一个函数,在每个动画帧中修改形状的旋转角度。

在本教程中,我们将让一个蓝色矩形绕左上角旋转,让一个黄色矩形绕其中心旋转,并让一个红色矩形绕外部的某个点旋转。

如需查看完整的属性和方法列表,请参阅 Konva.Animation 文档

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 rectangle - rotate around top-left corner
const blueRect = new Konva.Rect({
x: 50,
y: 50,
width: 100,
height: 50,
fill: '#00D2FF',
stroke: 'black',
strokeWidth: 4,
offset: {
x: 0,
y: 0,
},
});

// yellow rectangle - rotate around center
const yellowRect = new Konva.Rect({
x: 200,
y: 50,
width: 100,
height: 50,
fill: 'yellow',
stroke: 'black',
strokeWidth: 4,
offset: {
x: 50,
y: 25,
},
});

// red rectangle - rotate around point outside shape
const redRect = new Konva.Rect({
x: 350,
y: 50,
width: 100,
height: 50,
fill: 'red',
stroke: 'black',
strokeWidth: 4,
offset: {
x: -50,
y: 25,
},
});

layer.add(blueRect);
layer.add(yellowRect);
layer.add(redRect);

const angularSpeed = 90;
const anim = new Konva.Animation(function(frame) {
const angleDiff = (frame.timeDiff * angularSpeed) / 1000;
blueRect.rotate(angleDiff);
yellowRect.rotate(angleDiff);
redRect.rotate(angleDiff);
}, layer);

anim.start();