From 233d23df16732f6c28e6cceef435ca550f4e6bee Mon Sep 17 00:00:00 2001 From: Deveshi Dwivedi Date: Tue, 18 Jun 2024 12:21:04 +0530 Subject: [PATCH] add hook for drawing --- common/hooks/drawing.ts | 53 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 common/hooks/drawing.ts diff --git a/common/hooks/drawing.ts b/common/hooks/drawing.ts new file mode 100644 index 0000000..4373b84 --- /dev/null +++ b/common/hooks/drawing.ts @@ -0,0 +1,53 @@ +import { useEffect, useState } from "react"; +import { socket } from "@/common/lib/socket"; + +let moves: [number, number][]= []; + +export const useDraw = ( + options: CtxOptions, + ctx?: CanvasRenderingContext2D +) => { + 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) return ; + +moves= [[x, y]]; +setDrawing(true); + +ctx.beginPath(); +ctx.lineTo(x,y); +ctx.stroke(); +}; +const handleEndDrawing = () =>{ +if(!ctx) return ; + socket.emit("draw", moves, options); + setDrawing(false); + ctx.closePath(); +}; +const handleDraw= (x:number, y:number) =>{ + if(ctx && drawing){ + moves.push([x,y]); + ctx.lineTo(x,y); + ctx.stroke(); + } + +} + +return { + handleEndDrawing, + handleDraw, + handleStartDrawing, + drawing, +} + +};