Skip to content

Commit

Permalink
add hook for drawing
Browse files Browse the repository at this point in the history
  • Loading branch information
deveshidwivedi committed Jun 18, 2024
1 parent 59ce3db commit 233d23d
Showing 1 changed file with 53 additions and 0 deletions.
53 changes: 53 additions & 0 deletions common/hooks/drawing.ts
Original file line number Diff line number Diff line change
@@ -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,
}

};

0 comments on commit 233d23d

Please sign in to comment.