Project using node.js/Cloning Catch-Mind
Fill the canvas with socketIO
Cog Factory
2020. 12. 17. 07:40
Client 'A'가 canvas 전체를 칠하는 logic
// paint.js
const fill = (color = null) => {
let currentColor = ctx.fillStyle;
if (color !== null) currentColor = color;
ctx.fillStyle = currentColor;
ctx.fillRect(0, 0, CANVAS_SIZE, CANVAS_SIZE);
};
const handleClickFill = () => {
if (filling) {
fill();
getSocket().emit(window.events.fill, { color: ctx.strokeStyle });
}
};
canvas.addEventListener("click", handleClickFill);
// events.js
fill: "fill",
filled: "filled",
Fill mode로 해놓고 canvas를 클릭하면 fil() 함수로 Client 'A'의 canvas가 설정된 색깔로 채워진다. 그리고 서버에게 event를 보낸다.
server
// socketController.js
socket.on(events.fill, ({ color }) => {
broadcast(events.filled, { color });
});
Client 'A'로 부터 fill event를 수신하면 다른 Client들에게 color와 같이 filled event를 보낸다.
Other clients
// sockets.js
socket.on(events.filled, handleFilled);
// paint.js
export const handleFilled = ({ color }) => fill(color);
server로부터 filled event를 수신하면 canvas를 해당 color로 채운다.
소스 코드
github.com/zpskek/guessMind-v3/commit/ca51ece21a06aa4917d75b3637358d76d4ad74a0