Created
April 16, 2021 23:10
-
-
Save bbachi/da1393f8618deadc992b660e1a75ba22 to your computer and use it in GitHub Desktop.
React
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Stage, Layer, Line } from 'react-konva'; | |
import { useState, useRef } from 'react'; | |
const DrawingArea = () => { | |
const [lines, setLines] = useState<any>([]); | |
const isDrawing = useRef(false); | |
const handleMouseDown = (e:any) => { | |
isDrawing.current = true; | |
const pos = e.target.getStage().getPointerPosition(); | |
setLines([...lines, { points: [pos.x, pos.y] }]); | |
}; | |
const handleMouseMove = (e:any) => { | |
// no drawing - skipping | |
if (!isDrawing.current) { | |
return; | |
} | |
const stage = e.target.getStage(); | |
const point = stage.getPointerPosition(); | |
// To draw line | |
let lastLine: any = lines[lines.length - 1]; | |
if(lastLine) { | |
// add point | |
lastLine.points = lastLine.points.concat([point.x, point.y]); | |
// replace last | |
lines.splice(lines.length - 1, 1, lastLine); | |
setLines(lines.concat()); | |
} | |
}; | |
const handleMouseUp = () => { | |
isDrawing.current = false; | |
}; | |
return ( | |
<div className=" text-center text-dark"> | |
<Stage | |
width={600} | |
height={600} | |
onMouseDown={handleMouseDown} | |
onMousemove={handleMouseMove} | |
onMouseup={handleMouseUp} | |
className="canvas-stage" | |
> | |
<Layer> | |
{lines.map((line:any, i:number) => ( | |
<Line | |
key={i} | |
points={line.points} | |
stroke="#df4b26" | |
strokeWidth={2} | |
tension={0.5} | |
lineCap="round" | |
globalCompositeOperation={ | |
line.tool === 'eraser' ? 'destination-out' : 'source-over' | |
} | |
/> | |
))} | |
</Layer> | |
</Stage> | |
</div> | |
) | |
} | |
export default DrawingArea |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment