Skip to content

Commit 05fe9d7

Browse files
committed
add emit and listen logic
1 parent 73f4e6c commit 05fe9d7

File tree

2 files changed

+18
-5
lines changed

2 files changed

+18
-5
lines changed

api/index.js

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,9 @@ app.get('/', (req, res)=>{
1919

2020
io.on('connection', (socket)=>{
2121
console.log('user connected socket')
22+
socket.on('draw', (data)=>{
23+
socket.broadcast.emit('draw', data);
24+
})
2225
})
2326

2427
server.listen(PORT, ()=>{

client/src/App.jsx

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ function App() {
1313
let color = '#000000'
1414
let ctx;
1515
let canvas;
16+
let lineWidth;
1617

1718
useEffect(() => {
1819
canvas = canvasRef.current;
@@ -24,22 +25,30 @@ function App() {
2425

2526
canvas.width = canvas.getBoundingClientRect().width;
2627
canvas.height = canvas.getBoundingClientRect().height;
27-
function drawLine(sx, sy, ex, ey) {
28+
29+
function drawLine(sx, sy, ex, ey, color, lineWidth) {
2830
ctx.moveTo(sx, sy);
2931
ctx.lineTo(ex, ey);
3032
ctx.lineCap = "round";
3133
ctx.stroke();
34+
ctx.lineWidth = lineWidth;
35+
ctx.strokeStyle = color;
3236
}
3337

34-
function handleMouseover(e) {
38+
function handleMousemove(e) {
3539
if (!isDrawing) return;
3640
const endX = e.clientX - canvas.getBoundingClientRect().left;
3741
const endY = e.clientY - canvas.getBoundingClientRect().top;
3842
drawLine(startX, startY, endX, endY);
43+
socket.emit('draw', {startX, startY, endX, endY, color, lineWidth})
3944
startX = endX;
4045
startY = endY;
4146
}
4247

48+
socket.on('draw', (data)=>{
49+
drawLine(data.startX, data.startY, data.endX, data.endY, data.color, data.lineWidth);
50+
})
51+
4352
function handleMousedown(e) {
4453
isDrawing = true;
4554
startX = e.clientX - canvas.getBoundingClientRect().left;
@@ -53,12 +62,12 @@ function App() {
5362
ctx.beginPath();
5463
}
5564

56-
canvas.addEventListener("mousemove", handleMouseover);
65+
canvas.addEventListener("mousemove", handleMousemove);
5766
canvas.addEventListener("mousedown", handleMousedown);
5867
canvas.addEventListener("mouseup", handleMouseup);
5968

6069
return () => {
61-
canvas.removeEventListener("mousemove", handleMouseover);
70+
canvas.removeEventListener("mousemove", handleMousemove);
6271
canvas.removeEventListener("mousedown", handleMousedown);
6372
canvas.removeEventListener("mouseup", handleMouseup);
6473
};
@@ -79,7 +88,8 @@ function App() {
7988

8089
function addLineWidth(e){
8190
if (e.target.id === "lineWidth") {
82-
ctx.lineWidth = e.target.value;
91+
lineWidth = e.target.value;
92+
ctx.lineWidth = lineWidth;
8393
}
8494
}
8595

0 commit comments

Comments
 (0)