From 6f5fdfb799267e45baab207d0145c2b6efa6ec11 Mon Sep 17 00:00:00 2001 From: trafficlunar Date: Thu, 5 Dec 2024 22:02:15 +0000 Subject: [PATCH] feat: add pencil tool --- src/App.tsx | 64 +++++++++++++++++++++++++++++++++++++++++++------- src/types.d.ts | 2 +- 2 files changed, 57 insertions(+), 9 deletions(-) diff --git a/src/App.tsx b/src/App.tsx index e7b5346..11d6e30 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -1,6 +1,6 @@ import { useEffect, useRef, useState } from "react"; import { Layer, Stage } from "react-konva"; -import { Hand } from "lucide-react"; +import { Hand, Pencil } from "lucide-react"; import { Menubar, @@ -34,9 +34,25 @@ function App() { const [mousePosition, setMousePosition] = useState({ x: 0, y: 0 }); const [tool, setTool] = useState("hand"); + const [selectedBlock, setSelectedBlock] = useState("stone"); const [blocks, setBlocks] = useState([]); const [cssCursor, setCssCursor] = useState("grab"); + const [mouseDown, setMouseDown] = useState(false); + + const onToolChange = (value) => { + setTool(value); + + switch (value) { + case "hand": + setCssCursor("grab"); + break; + + default: + setCssCursor("auto"); + break; + } + }; const onMouseMove = (e) => { const stage = e.target.getStage(); @@ -47,15 +63,15 @@ function App() { x: (pointer.x - stage.x()) / oldScale, y: (pointer.y - stage.y()) / oldScale, }); - }; - const onMouseDown = (e) => { - if (tool == "hand") { - setCssCursor("grabbing"); + if (mouseDown) { + onClick(e); } }; const onMouseUp = (e) => { + setMouseDown(false); + if (tool == "hand") { setCssCursor("grab"); } @@ -75,6 +91,28 @@ function App() { }); }; + const onClick = (e) => { + switch (tool) { + case "hand": + setCssCursor("grabbing"); + break; + case "pencil": { + const blockX = Math.floor(mousePosition.x / 16); + const blockY = Math.floor(mousePosition.y / 16); + const updatedBlocks = blocks.filter((b) => !(b.x === blockX && b.y === blockY)); + + setBlocks([ + ...updatedBlocks, + { + name: selectedBlock, + x: blockX, + y: blockY, + }, + ]); + } + } + }; + useEffect(() => { if (stageContainerRef.current && stageRef.current) { setStageSize({ @@ -118,26 +156,36 @@ function App() { - + + + +
setMouseDown(true)} onMouseUp={onMouseUp} onWheel={onWheel} + onClick={onClick} style={{ cursor: cssCursor }} > diff --git a/src/types.d.ts b/src/types.d.ts index a451695..c013d71 100644 --- a/src/types.d.ts +++ b/src/types.d.ts @@ -7,4 +7,4 @@ interface Block extends Position { name: string; } -type Tool = "hand"; \ No newline at end of file +type Tool = "hand" | "pencil"; \ No newline at end of file