Files
knet/js/draw.js
2025-02-26 13:38:55 +01:00

102 lines
2.4 KiB
JavaScript

(() => {
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 socketUrl =
(window.location.protocol.startsWith("https") ? "wss://" : "ws://") +
window.location.host +
"/draw/ws";
let socket = new WebSocket(socketUrl);
socket.onerror = console.error;
socket.onclose = console.warn;
setTimeout(() => socket.send("ping"), 200);
// const queue = []
const sendMessage = (id, x, y) => {
// queue.push(`${id},${x},${y}`)
// console.log(queue)
if (socket.readyState !== socket.OPEN) {
socket = new WebSocket(socketUrl);
}
socket.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();
};
const touchStart = (e) => drawStart(e.touches[0]);
const touchMove = (e) => {
drawMove({
offsetX: e.touches[0].clientX - canvas.offsetLeft,
offsetY: e.touches[0].clientY - canvas.offsetTop,
});
e.preventDefault();
};
const touchEnd = (e) => drawStop(e.changedTouches[0]);
canvas.addEventListener("mousedown", drawStart);
canvas.addEventListener("mouseup", drawStop);
canvas.addEventListener("mousemove", drawMove);
canvas.addEventListener("touchstart", touchStart);
canvas.addEventListener("touchend", touchEnd);
canvas.addEventListener("touchmove", touchMove);
const receiveCanvas = document.getElementById("receiveCanvas");
const recCtx = receiveCanvas.getContext("2d");
recCtx.lineWidth = 2;
recCtx.lineCap = "round";
recCtx.strokeStyle = "white";
let receiveLineId = 0;
socket.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 (socket.readyState !== socket.OPEN) {
socket = new WebSocket(socketUrl);
}
socket.send("ping");
}, 10000);
})();