Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save mingyuchoo/04c08472d3546e6efe9e3057419ef863 to your computer and use it in GitHub Desktop.
Save mingyuchoo/04c08472d3546e6efe9e3057419ef863 to your computer and use it in GitHub Desktop.
Draw Red Straight Line with Keyboard
/*
* npm install --save konva react-konva
*
* 's' - Mark as 'Start'
* 'c' - Cancel the mark as 'Start'
* 'e' - End of Line
*/
import React, { useState, useEffect } from 'react';
import { Stage, Layer, Line, Circle, Text } from 'react-konva';
const DrawingRedStraightLineWithKeyboardApp = () => {
const [lines, setLines] = useState([]);
const [currentPos, setCurrentPos] = useState({ x: 100, y: 100 });
const [drawing, setDrawing] = useState(false);
useEffect(() => {
const handleKeyDown = (event) => {
switch (event.key) {
case 'ArrowRight':
setCurrentPos({ ...currentPos, x: currentPos.x + 10 });
break;
case 'ArrowLeft':
setCurrentPos({ ...currentPos, x: currentPos.x - 10 });
break;
case 'ArrowUp':
setCurrentPos({ ...currentPos, y: currentPos.y - 10 });
break;
case 'ArrowDown':
setCurrentPos({ ...currentPos, y: currentPos.y + 10 });
break;
case 's': // 'S' key to start line
if (!drawing) {
setLines([...lines, { points: [currentPos.x, currentPos.y, currentPos.x, currentPos.y] }]);
setDrawing(true);
}
break;
case 'e': // 'E' key to end line
if (drawing) {
let newLines = lines.slice();
let lastLine = newLines[newLines.length - 1];
lastLine.points[2] = currentPos.x; // Corrected from 'last, lastLine.points[2]'
lastLine.points[3] = currentPos.y;
setLines(newLines);
setDrawing(false);
}
break;
case 'c': // 'C' key to cancel the current line
if (drawing) {
setLines(lines.slice(0, -1));
setDrawing(false);
}
break;
default:
break;
}
};
window.addEventListener('keydown', handleKeyDown);
return () => window.removeEventListener('keydown', handleKeyDown);
}, [currentPos, lines, drawing]);
return (
<Stage width={window.innerWidth} height={window.innerHeight}>
<Layer>
{lines.map((line, i) => (
<Line
key={i}
points={line.points}
stroke="#df4b26"
strokeWidth={5}
lineCap="round"
lineJoin="round"
/>
))}
{drawing && (
<Line
points={[lines[lines.length - 1].points[0], lines[lines.length - 1].points[1], currentPos.x, currentPos.y]}
stroke="#df4b26"
strokeWidth={5}
lineCap="round"
lineJoin="round"
dash={[10, 5]}
/>
)}
<Circle // This circle represents the cursor
x={currentPos.x}
y={currentPos.y}
radius={5}
fill="#df4b26"
/>
<Text // Display the coordinates of the cursor
text={`X: ${currentPos.x}, Y: ${currentPos.y}`}
x={currentPos.x + 10}
y={currentPos.y + 10}
fontSize={16}
fill="#000"
/>
</Layer>
</Stage>
);
};
export default DrawingRedStraightLineWithKeyboardApp;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment