Basic Tweening Tutorial
To tween properties with Konva, we can instantiate a Konva.Tween object and then start the tween by calling play().
Any numeric property of a Shape, Group, Layer, or Stage can be transitioned, such as:
x,y(position)rotationwidth,height,radiusstrokeWidthopacityscaleX,scaleYoffsetX,offsetY
For a full list of attributes and methods, check out the Konva.Tween documentation.
Instructions: Click the circle to start a simple linear animation.
- Vanilla
- React
- Vue
import Konva from 'konva';
const width = window.innerWidth;
const height = window.innerHeight;
const stage = new Konva.Stage({
container: 'container',
width: width,
height: height,
});
const layer = new Konva.Layer();
const circle = new Konva.Circle({
x: 100,
y: height / 2,
radius: 70,
fill: 'red',
stroke: 'black',
strokeWidth: 4,
});
layer.add(circle);
stage.add(layer);
circle.on('click tap', () => {
// simple tween
const tween = new Konva.Tween({
node: circle,
duration: 1,
x: width - 100,
easing: Konva.Easings.Linear,
});
tween.play();
});
import Konva from 'konva';
import { Stage, Layer, Circle } from 'react-konva';
import { useEffect, useRef } from 'react';
const App = () => {
const circleRef = useRef();
const tweenRef = useRef();
useEffect(() => {
return () => tweenRef.current?.destroy();
}, []);
const handleClick = () => {
tweenRef.current?.destroy();
tweenRef.current = new Konva.Tween({
node: circleRef.current,
duration: 1,
x: window.innerWidth - 100,
easing: Konva.Easings.Linear,
});
tweenRef.current.play();
};
return (
<Stage width={window.innerWidth} height={window.innerHeight}>
<Layer>
<Circle
ref={circleRef}
x={100}
y={window.innerHeight / 2}
radius={70}
fill="red"
stroke="black"
strokeWidth={4}
onClick={handleClick}
onTap={handleClick}
/>
</Layer>
</Stage>
);
};
export default App;
<template>
<v-stage :config="stageSize">
<v-layer>
<v-circle
:config="circleConfig"
@click="handleClick"
@tap="handleClick"
ref="circleRef"
/>
</v-layer>
</v-stage>
</template>
<script setup>
import { ref } from 'vue';
import Konva from 'konva';
const stageSize = {
width: window.innerWidth,
height: window.innerHeight
};
const circleConfig = {
x: 100,
y: window.innerHeight / 2,
radius: 70,
fill: 'red',
stroke: 'black',
strokeWidth: 4
};
const circleRef = ref(null);
const handleClick = () => {
const tween = new Konva.Tween({
node: circleRef.value.getNode(),
duration: 1,
x: window.innerWidth - 100,
easing: Konva.Easings.Linear,
});
tween.play();
};
</script>