Project using node.js/Cloning Catch-Mind

Drawing canvas with socketIO

Cog Factory 2020. 12. 15. 13:58

paint.js

// paint.js

import { getSocket } from "./sockets";

const beginPath = (x, y, size) => {
  ctx.beginPath();
  ctx.moveTo(x, y);
  ctx.lineWidth = size;
};

const strokePath = (x, y, color) => {
  let currentColor = ctx.strokeStyle;
  if (color !== null) currentColor = color;
  ctx.strokeStyle = currentColor;

  ctx.lineTo(x, y);
  ctx.stroke();
};

const handleMousemove = (e) => {
  const x = e.offsetX;
  const y = e.offsetY;

  if (!painting) {
    beginPath(x, y);
    getSocket().emit(window.events.beginPath, { x, y, size: ctx.lineWidth });
  } else {
    strokePath(x, y);
    getSocket().emit(window.events.strokePath, {
      x,
      y,
      color: ctx.strokeStyle,
    });
  }
};

export const handleBeganPth = ({ x, y, size }) => beginPath(x, y, size);
export const handleStrokenPath = ({ x, y, color }) => strokePath(x, y, color);
// events.js

beginPath: "beginPath",
beganPth: "beganPth",
strokePath: "strokePath",
strokenPath: "strokenPath",
// socketController.js

socket.on(events.beginPath, ({ x, y, size }) => {
	broadcast(events.beganPth, { x, y, size });
  });
socket.on(events.strokePath, ({ x, y, color }) => {
	broadcast(events.strokenPath, { x, y, color });
  });
// socekts.js

import { handleBeganPth, handleStrokenPath } from "./paint";

socket.on(events.beganPth, handleBeganPth);
socket.on(events.strokenPath, handleStrokenPath);

  그림을 canvas 위에 그리는 순간 beginPath와 strokePath가 실행이 된다. 그리고 다른 clients 화면에도 동시에 그림이 그려진다.