From 884497eb2915afff6de4c13fc53a8ceb3323d0e4 Mon Sep 17 00:00:00 2001 From: Deveshi Dwivedi Date: Tue, 18 Jun 2024 20:13:43 +0530 Subject: [PATCH] implement drawing functionality in useDraw hook --- modules/canvas/hooks/Canvas.hooks.ts | 59 ++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 modules/canvas/hooks/Canvas.hooks.ts diff --git a/modules/canvas/hooks/Canvas.hooks.ts b/modules/canvas/hooks/Canvas.hooks.ts new file mode 100644 index 0000000..25385fa --- /dev/null +++ b/modules/canvas/hooks/Canvas.hooks.ts @@ -0,0 +1,59 @@ +import { useEffect, useState } from "react"; +import { socket } from "@/common/lib/socket"; +import { useOptions } from "@/common/recoil/options"; + +let moves: [number, number][]= []; + +export const useDraw = ( + ctx: CanvasRenderingContext2D | undefined, + blocked: boolean, + movedX: number, + movedY: number, + handleEnd: () => void +) => { + const options = useOptions(); + const [drawing, setDrawing] = useState(false); + +useEffect(()=>{ + if(ctx){ + ctx.lineJoin= "round"; + ctx.lineCap= "round"; + ctx.lineWidth= options.lineWidth; + ctx.strokeStyle= options.lineColor; + } +}); + +const handleStartDrawing = (x: number, y: number) =>{ +if(!ctx || blocked) return ; + +moves= [[x+movedX, y+movedY]]; +setDrawing(true); + +ctx.beginPath(); +ctx.lineTo(x+movedX,y+movedY); +ctx.stroke(); +}; +const handleEndDrawing = () =>{ +if(!ctx) return ; + socket.emit("draw", moves, options); + setDrawing(false); + ctx.closePath(); + handleEnd(); +}; +const handleDraw= (x:number, y:number) =>{ + if(ctx && drawing && !blocked){ + moves.push([x+movedX,y+movedY]); + ctx.lineTo(x,y); + ctx.stroke(); + } + +} + +return { + handleEndDrawing, + handleDraw, + handleStartDrawing, + drawing, +} + +}; \ No newline at end of file