Skip to content

Commit

Permalink
implement drawing functionality in useDraw hook
Browse files Browse the repository at this point in the history
  • Loading branch information
deveshidwivedi committed Jun 18, 2024
1 parent 4454a5d commit 884497e
Showing 1 changed file with 59 additions and 0 deletions.
59 changes: 59 additions & 0 deletions modules/canvas/hooks/Canvas.hooks.ts
Original file line number Diff line number Diff line change
@@ -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,
}

};

0 comments on commit 884497e

Please sign in to comment.