import React, { useState ,useEffect} from 'react';
import { Stage, Layer, Rect, Line, Group } from 'react-konva';
const App = () => {
const [rectangles, setRectangles] = useState([
{ x: 50, y: 50, width: 100, height: 100 }, // 첫 번째 사각형
{ x: 200, y: 200, width: 100, height: 100 } // 두 번째 사각형
]);
const [controlPressed, setControlPressed] = useState(false);
const [linePoints, setLinePoints] = useState([
rectangles[0].x + rectangles[0].width / 2,
rectangles[0].y + rectangles[0].height / 2,
rectangles[1].x + rectangles[1].width / 2,
rectangles[1].y + rectangles[1].height / 2
]);
const handleDragMove = (index, e) => {
const newRectangles = rectangles.slice();
newRectangles[index] = {
...newRectangles[index],
x: e.target.x(),
y: e.target.y()
};
setRectangles(newRectangles);
updateLinePoints();
};
const handleTransform = (index, e) => {
const newRectangles = rectangles.slice();
const node = e.target;
const scaleX = node.scaleX();
const scaleY = node.scaleY();
newRectangles[index] = {
...newRectangles[index],
width: node.width() scaleX,
height: node.height() scaleY,
x: node.x() + (node.width() (1 - scaleX)) / 2,
y: node.y() + (node.height() (1 - scaleY)) / 2
};
setRectangles(newRectangles);
node.scaleX(1);
node.scaleY(1);
updateLinePoints();
};
const handleKeyDown = (e) => {
if (e.key === 'Control') {
setControlPressed(true);
}
};
const handleKeyUp = (e) => {
if (e.key === 'Control') {
setControlPressed(false);
}
};
useEffect(() => {
window.addEventListener('keydown', handleKeyDown);
window.addEventListener('keyup', handleKeyUp);
// 컴포넌트가 언마운트될 때 이벤트 리스너를 제거합니다.
return () => {
window.removeEventListener('keydown', handleKeyDown);
window.removeEventListener('keyup', handleKeyUp);
};
}, []); // 빈 배열을 전달하여 컴포넌트가 마운트될 때만 실행되도록 설정합니다.
const updateLinePoints = () => {
setLinePoints([
rectangles[0].x + rectangles[0].width / 2,
rectangles[0].y + rectangles[0].height / 2,
rectangles[1].x + rectangles[1].width / 2,
rectangles[1].y + rectangles[1].height / 2
]);
};
return (
{rectangles.map((rect, index) => (
<Rect
key={index}
x={rect.x}
y={rect.y}
width={rect.width}
height={rect.height}
stroke="red" // 테두리 색상 지정
strokeWidth={1} // 테두리 두께 지정
draggable={controlPressed}
onDragMove={(e) => handleDragMove(index, e)}
onTransformEnd={(e) => handleTransform(index, e)}
/>
))}
{linePoints.length > 0 && (
<Line
points={linePoints}
stroke="black"
strokeWidth={1}
pointerWidth={10} // 화살표의 너비를 설정합니다.
pointerLength={10} // 화살표의 길이를 설정합니다.
/>
)}
);
};
export default App;