HTML5 Canvas Konva 动画教程
要使用 Konva 创建自定义动画,我们可以使用 Konva.Animation
构造函数,它接受两个参数:必需的更新函数,以及一个可选的图层或图层数组,
这些图层将在每个动画帧中进行更新。
动画函数会传入一个 frame 对象,其中包含一个 time 属性,表示动画已运行的毫秒数,
一个 timeDiff 属性,表示自上一帧以来经过的毫秒数,
以及一个 frameRate 属性,表示当前每秒的帧数。
更新函数不应重绘舞台或图层,因为动画引擎会智能地为我们处理这些操作。
更新函数只应包含更新 Node 属性的逻辑,
例如 position、rotation、scale、width、height、radius、colors 等。
创建动画后,我们可以随时使用 start() 方法启动它。
如需查看完整的属性和方法列表,请参阅 Konva.Animation 文档。
- Vanilla
- React
- Vue
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 rect = new Konva.Rect({
x: 50,
y: 50,
width: 50,
height: 50,
fill: 'green',
});
layer.add(rect);
const anim = new Konva.Animation(function(frame) {
const time = frame.time;
const timeDiff = frame.timeDiff;
const frameRate = frame.frameRate;
// Example: move rectangle in a circle
const radius = 50;
const x = radius * Math.cos(frame.time * 2 * Math.PI / 2000) + 100;
const y = radius * Math.sin(frame.time * 2 * Math.PI / 2000) + 100;
rect.position({ x, y });
}, layer);
anim.start();
import { Stage, Layer, Rect } from 'react-konva';
import { useEffect, useRef } from 'react';
const App = () => {
const rectRef = useRef(null);
useEffect(() => {
const anim = new Konva.Animation((frame) => {
const time = frame.time;
const timeDiff = frame.timeDiff;
const frameRate = frame.frameRate;
// Example: move rectangle in a circle
const radius = 50;
const x = radius * Math.cos(frame.time * 2 * Math.PI / 2000) + 100;
const y = radius * Math.sin(frame.time * 2 * Math.PI / 2000) + 100;
rectRef.current.position({ x, y });
}, rectRef.current.getLayer());
anim.start();
return () => {
anim.stop();
};
}, []);
return (
<Stage width={window.innerWidth} height={window.innerHeight}>
<Layer>
<Rect
ref={rectRef}
x={50}
y={50}
width={50}
height={50}
fill="green"
/>
</Layer>
</Stage>
);
};
export default App;
<template>
<v-stage :config="stageSize">
<v-layer ref="layerRef">
<v-rect
ref="rectRef"
:config="rectConfig"
/>
</v-layer>
</v-stage>
</template>
<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
import Konva from 'konva';
const stageSize = {
width: window.innerWidth,
height: window.innerHeight
};
const rectConfig = ref({
x: 50,
y: 50,
width: 50,
height: 50,
fill: 'green'
});
const layerRef = ref(null);
const rectRef = ref(null);
let anim = null;
onMounted(() => {
anim = new Konva.Animation((frame) => {
const time = frame.time;
const timeDiff = frame.timeDiff;
const frameRate = frame.frameRate;
// Example: move rectangle in a circle
const radius = 50;
const x = radius * Math.cos(frame.time * 2 * Math.PI / 2000) + 100;
const y = radius * Math.sin(frame.time * 2 * Math.PI / 2000) + 100;
rectRef.value.getNode().position({ x, y });
}, layerRef.value.getNode());
anim.start();
});
onUnmounted(() => {
if (anim) {
anim.stop();
}
});
</script>