Skip to content

Instantly share code, notes, and snippets.

@mingyuchoo
Last active June 16, 2024 08:04
Show Gist options
  • Save mingyuchoo/1cf2a1ec7cfd8fd5ea5734394d77d414 to your computer and use it in GitHub Desktop.
Save mingyuchoo/1cf2a1ec7cfd8fd5ea5734394d77d414 to your computer and use it in GitHub Desktop.
Draw Red Straight Line using `react-konva`
/*
* npm install --save konva react-konva
*/
import React, { useState } from 'react';
import { Stage, Layer, Line } from 'react-konva';
function DrawingRedStraightLineApp() {
const [lines, setLines] = useState([]);
const [currentLine, setCurrentLine] = useState([]);
const handleMouseDown = (e) => {
const pos = e.target.getStage().getPointerPosition();
setCurrentLine([pos.x, pos.y, pos.x, pos.y]); // 시작 지점과 같은 지점에서 시작해 끝나는 초기 선을 설정
};
const handleMouseMove = (e) => {
if (currentLine.length === 0) return; // 마우스가 눌려 있지 않은 상태라면 아무 작업도 하지 않음
const stage = e.target.getStage();
const point = stage.getPointerPosition();
setCurrentLine([currentLine[0], currentLine[1], point.x, point.y]); // 시작점은 그대로 두고 마우스 위치를 끝점으로 설정
};
const handleMouseUp = () => {
setLines([...lines, currentLine]); // 완성된 선을 lines 배열에 추가
setCurrentLine([]); // 현재 선을 초기화
};
return (
<Stage
width={window.innerWidth}
height={window.innerHeight}
onMouseDown={handleMouseDown}
onMouseMove={handleMouseMove}
onMouseUp={handleMouseUp}
>
<Layer>
{lines.map((line, i) => (
<Line
key={i}
points={line}
stroke="#df4b26"
strokeWidth={5}
lineCap="round"
lineJoin="round"
/>
))}
{currentLine.length > 0 && (
<Line
points={currentLine}
stroke="#df4b26"
strokeWidth={5}
lineCap="round"
lineJoin="round"
/>
)}
</Layer>
</Stage>
);
}
export default DrawingRedStraightLineApp;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment