React Konva Rotation/Revolution 动画

React Konva Rotation/Revolution Animation

嘿,我是 React konva 的新手。我正在创建一个项目,其中我想要一个矩形围绕一个对象旋转。谁能告诉我如何实现这一目标。非常感谢任何帮助

    <div>
      <Stage width={500} height={500}>
        <Layer>
            <Rect ///<=this rect is the center object
              width={50}
              height={100}
              x={20}
              y={20}
              strokeWidth={2}
              stroke="red"
              fill="blue"
              opacity={1}         
            />
        
            <Rect ///<=this rect should revolve around it
              width={50}
              height={100}
              x={50}
              y={50}
              strokeWidth={2}
              stroke="black"
              fill="black"
              opacity={1}         
            />
        </Layer>
      </Stage>
      <Button onClick={handleRotate}>Start Rotation</Button>
    </div>

您可以使用Konva.Animation 来随意移动矩形。由您来计算形状的位置。

import React from "react";
import { render } from "react-dom";
import { Stage, Layer, Rect } from "react-konva";
import Konva from "konva";

const App = () => {
  const rectRef = React.useRef();
  const [animating, setAnimation] = React.useState(false);

  React.useEffect(() => {
    if (!animating) {
      return;
    }
    const node = rectRef.current;
    const anim = new Konva.Animation(
      (frame) => {
        const centerX = 200;
        const centerY = 200;
        const radius = 200;

        node.x(centerX + radius * Math.cos(frame.time / 1000));
        node.y(centerY + radius * Math.sin(frame.time / 1000));
      },
      [node.getLayer()]
    );
    anim.start();
    return () => anim.stop();
  }, [animating]);
  return (
    <>
      <button
        onClick={() => {
          setAnimation(!animating);
        }}
      >
        Toggle animation
      </button>
      <Stage width={window.innerWidth} height={window.innerHeight}>
        <Layer>
          <Rect
            x={200}
            y={200}
            width={100}
            height={100}
            fill="red"
            shadowBlur={10}
          />
          <Rect
            ref={rectRef}
            width={100}
            height={100}
            fill="blue"
            shadowBlur={10}
            // set default position
            // animation will overwrite it
            x={400}
            y={200}
          />
        </Layer>
      </Stage>
    </>
  );
};

render(<App />, document.getElementById("root"));

https://codesandbox.io/s/react-konva-animate-rotation-bxbtj

你可以使用节点

.rotate属性
const ref=useRef(null)

useEffect(() => {
  
    var rect= ref.current;
    var anim = new Konva.Animation((frame) => {
      rect?.rotate((frame.timeDiff *90) / 1000);
    }, rect?.getLayer());
    anim?.start();
    
  }, [input]);

<Rect
ref={ref}
/>