React-konva - 使用鼠标单击将圆与线连接起来

React-konva - Conneting Circle with a Line using mouse click

我正在使用 react-konva,并且我有两个 Circle 组件,我想将其连接到 Line。我已经通过硬编码实现了这一点,但我想让它具有交互性。

我的目标:当我单击 Circle 组件时,它会创建一个 Line 组件。然后,如果我点击另一个 Circle,两者都会被那个 Line.

连接起来

我的问题:我不知道该怎么做。我乐于接受想法。

有很多方法可以实现它。你可以这样做:

import React from "react";
import { render } from "react-dom";
import { Stage, Layer, Circle, Line, Text } from "react-konva";

function generateShapes() {
  const shapes = [];
  for (var i = 0; i < 10; i++) {
    shapes.push({
      id: i,
      x: Math.random() * window.innerWidth,
      y: Math.random() * window.innerHeight
    });
  }
  return shapes;
}

const INITIAL_SHAPES = generateShapes();

const App = () => {
  const [shapes, setShapes] = React.useState(INITIAL_SHAPES);
  const [connectors, setConnectors] = React.useState([]);

  const [fromShapeId, setFromShapeId] = React.useState(null);

  return (
    <Stage width={window.innerWidth} height={window.innerHeight}>
      <Layer>
        {connectors.map(con => {
          const from = shapes.find(s => s.id === con.from);
          const to = shapes.find(s => s.id === con.to);

          return (
            <Line
              key={con.id}
              points={[from.x, from.y, to.x, to.y]}
              stroke="black"
            />
          );
        })}
        {shapes.map(shape => (
          <Circle
            x={shape.x}
            y={shape.y}
            key={shape.id}
            fill={fromShapeId === shape.id ? "red" : "green"}
            radius={20}
            shadowBlur={10}
            onClick={() => {
              if (fromShapeId) {
                const newConnector = {
                  from: fromShapeId,
                  to: shape.id,
                  id: connectors.length
                };
                setConnectors(connectors.concat([newConnector]));
                setFromShapeId(null);
              } else {
                setFromShapeId(shape.id);
              }
            }}
          />
        ))}
        <Text text="Click on on circle then on another to connect them" />
      </Layer>
    </Stage>
  );
};

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

演示:https://codesandbox.io/s/react-konva-connecting-shapes-demo-usr05