const canvas = document.getElementById("drawCanvas"); const ctx = canvas.getContext("2d"); ctx.lineWidth = 2; ctx.lineCap = "round"; ctx.strokeStyle = "white"; let drawing = false; let lineId = 0; const drawSocketUrl = (window.location.protocol.startsWith("https") ? "wss://" : "ws://") + window.location.host + "/draw/ws"; let drawSocket = new WebSocket(drawSocketUrl); drawSocket.onerror = (e) => { console.log("error", e); }; drawSocket.onclose = (e) => { console.log("closed", e); }; setTimeout(() => { drawSocket.send("ping"); }, 200); const sendMessage = (id, x, y) => { if (drawSocket.readyState !== drawSocket.OPEN) { drawSocket = new WebSocket(drawSocketUrl); } drawSocket.send(id + "," + x + "," + y); }; const drawStart = () => { ctx.beginPath(); lineId++; drawing = true; }; const drawStop = () => { drawing = false; ctx.closePath(); }; const drawMove = (e) => { if (!drawing) return; ctx.lineTo(e.offsetX, e.offsetY); sendMessage(lineId, e.offsetX, e.offsetY); ctx.stroke(); }; function touchStart(event) { console.log("start"); drawStart(event.touches[0]); } function touchMove(event) { console.log("move", event.touches[0]); const e = { offsetX: event.touches[0].clientX - canvas.offsetLeft, offsetY: event.touches[0].clientY - canvas.offsetTop, }; drawMove(e); event.preventDefault(); } function touchEnd(event) { console.log("end"); drawStop(event.changedTouches[0]); } canvas.addEventListener("mousedown", drawStart); canvas.addEventListener("mouseup", drawStop); canvas.addEventListener("mousemove", drawMove); canvas.addEventListener("touchstart", touchStart, false); canvas.addEventListener("touchend", touchEnd, false); canvas.addEventListener("touchmove", touchMove, false); const receiveCanvas = document.getElementById("receiveCanvas"); const recCtx = receiveCanvas.getContext("2d"); recCtx.lineWidth = 2; recCtx.lineCap = "round"; let receiveLineId = 0; drawSocket.addEventListener("message", function (event) { const parts = event.data.split(","); if (parts[0] != receiveLineId) { recCtx.closePath(); recCtx.beginPath(); receiveLineId = parts[0]; recCtx.moveTo(parts[1], parts[2]); } else { recCtx.lineTo(parts[1], parts[2]); recCtx.stroke(); } }); setInterval(() => { if (drawSocket.readyState !== drawSocket.OPEN) { drawSocket = new WebSocket(drawSocketUrl); } drawSocket.send("ping"); }, 10000);