ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Drawing canvas with socketIO
    Project using node.js/Cloning Catch-Mind 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 화면에도 동시에 그림이 그려진다.

    'Project using node.js > Cloning Catch-Mind' 카테고리의 다른 글

    Erase canvas with socketIO  (0) 2020.12.17
    Fill the canvas with socketIO  (0) 2020.12.17
    Chat with socketIO  (0) 2020.12.15
    socket.io로 로그인 알리기  (0) 2020.12.14
    Client가 서버의 변수 공유하기  (0) 2020.12.14

    댓글

Designed by Tistory.