0

嘿,我是新来的反应康瓦。我正在创建一个项目,我希望一个矩形围绕一个对象旋转。任何人都可以告诉我如何实现这一目标。任何帮助深表感谢

    <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>
4

2 回答 2

1

您可以根据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

于 2021-09-29T16:16:37.177 回答
1

您可以使用.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}
/>
于 2021-09-29T19:30:20.880 回答