Skip to main content

如何使用 React 和 Konva 实现画布动画?

Konva 本身提供两种动画方式: TweenAnimation。你可以手动将它们应用到节点上。

对于简单的使用场景,建议使用 node.to() 方法。对于更复杂的动画,可以参考 复杂的 react-konva 动画示例

该示例使用 refs API 直接访问形状实例。

操作指南:尝试拖拽矩形以查看动画效果。

import React, { useRef } from 'react';
import { Stage, Layer, Rect } from 'react-konva';

const MyRect = () => {
  const rectRef = useRef(null);

  const changeSize = () => {
    // to() 是 `Konva.Node` 实例的一个方法
    rectRef.current.to({
      scaleX: Math.random() + 0.8,
      scaleY: Math.random() + 0.8,
      duration: 0.2,
    });
  };

  return (
    <Rect
      ref={rectRef}
      width={50}
      height={50}
      fill="green"
      draggable
      onDragEnd={changeSize}
      onDragStart={changeSize}
    />
  );
};

const App = () => {
  return (
    <Stage width={window.innerWidth} height={window.innerHeight}>
      <Layer>
        <MyRect />
      </Layer>
    </Stage>
  );
};

export default App;