【发布时间】:2021-08-14 02:30:22
【问题描述】:
伙计们,我不知道如何在两个被拖动的圆圈和一个圆圈之间建立一条连接线。我想一种方法是更新被拖动的圆圈的实际坐标,但我也在努力实现它。谁能帮帮我???
import React from "react";
import { render } from "react-dom";
import { Stage, Layer, Star, Line, Text } from "react-konva";
function generateShapes() {
return [...Array(10)].map((_, i) => ({
id: i.toString(),
x: Math.random() * window.innerWidth,
y: Math.random() * window.innerHeight,
rotation: Math.random() * 180,
isDragging: false
}));
}
const INITIAL_STATE = generateShapes();
const App = () => {
const [stars, setStars] = React.useState(INITIAL_STATE);
const [connectors, setConnectors] = React.useState([]);
const [fromShapeId, setFromShapeId] = React.useState(null);
const handleDragStart = (e) => {
const id = e.target.id();
setStars(
stars.map((star) => {
return {
...star,
isDragging: star.id === id
};
})
);
};
const handleDragEnd = (e) => {
setStars(
stars.map((star) => {
return {
...star,
isDragging: false
// update coordinate of the star
};
})
);
};
return (
<Stage width={window.innerWidth} height={window.innerHeight}>
<Layer>
{connectors.map((con) => {
const from = stars.find((s) => s.id === con.from);
const to = stars.find((s) => s.id === con.to);
return (
<Line
key={con.id}
points={[from.x, from.y, to.x, to.y]}
stroke="black"
/>
);
})}
<Text text="Try to drag a star" />
{stars.map((star) => (
<Star
key={star.id}
id={star.id}
x={star.x}
y={star.y}
numPoints={5}
innerRadius={20}
outerRadius={40}
fill={fromShapeId === star.id ? "red" : "green"}
opacity={0.8}
draggable
rotation={star.rotation}
shadowColor="black"
shadowBlur={10}
shadowOpacity={0.6}
shadowOffsetX={star.isDragging ? 10 : 5}
shadowOffsetY={star.isDragging ? 10 : 5}
scaleX={star.isDragging ? 1.2 : 1}
scaleY={star.isDragging ? 1.2 : 1}
onDragStart={handleDragStart}
onDragEnd={handleDragEnd}
onClick={() => {
if (fromShapeId) {
const newConnector = {
from: fromShapeId,
to: star.id,
id: connectors.length
};
setConnectors(connectors.concat([newConnector]));
setFromShapeId(null);
} else {
setFromShapeId(star.id);
}
}}
/>
))}
</Layer>
</Stage>
);
};
render(<App />, document.getElementById("root"));
我的第一次尝试是创建一个函数,通过使用 var x = e.clientX 和 var y = e.clientY 创建一个函数,当星星停止被拖动时检测它的位置。但是,它们都是未定义的。我想也许我必须创建某种数组来存储每颗星的坐标并在移动时更新该星的坐标。尽管如此,我真的不知道如何实现代码:/
【问题讨论】:
标签: reactjs react-hooks konva