基础插值动画教程
要使用 Konva 插值属性,我们可以实例化一个 Konva.Tween
对象,然后通过调用 play()
开始插值动画。
Shape
、Group
、Layer
或 Stage
的任何数值属性都可以进行插值动画,例如:
x
、y
(位置)rotation
width
、height
、radius
strokeWidth
opacity
scaleX
、scaleY
offsetX
、offsetY
有关属性和方法的完整列表,请查看 Konva.Tween 文档。
说明:点击圆圈以开始简单的线性动画。
- 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', () => { // 简单插值动画 const tween = new Konva.Tween({ node: circle, duration: 1, x: width - 100, easing: Konva.Easings.Linear, }); tween.play(); });
import { Stage, Layer, Circle } from 'react-konva'; import { useRef } from 'react'; const App = () => { const circleRef = useRef(); const handleClick = () => { const tween = new Konva.Tween({ node: circleRef.current, duration: 1, x: window.innerWidth - 100, easing: Konva.Easings.Linear, }); tween.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>