94 lines
2.1 KiB
HTML
94 lines
2.1 KiB
HTML
{{block "draw" .}}
|
|
<canvas
|
|
id="drawCanvas"
|
|
width="500"
|
|
height="500"
|
|
style="border: 1px solid black"
|
|
></canvas>
|
|
<canvas
|
|
id="receiveCanvas"
|
|
width="500"
|
|
height="500"
|
|
style="border: 1px solid black"
|
|
></canvas>
|
|
|
|
<script>
|
|
const canvas = document.getElementById("drawCanvas");
|
|
const ctx = canvas.getContext("2d");
|
|
ctx.lineWidth = 2;
|
|
ctx.lineCap = "round";
|
|
|
|
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);
|
|
};
|
|
|
|
canvas.addEventListener("mousedown", () => {
|
|
ctx.beginPath();
|
|
lineId++;
|
|
drawing = true;
|
|
});
|
|
canvas.addEventListener("mouseup", () => {
|
|
drawing = false;
|
|
ctx.closePath();
|
|
});
|
|
canvas.addEventListener("mousemove", (e) => {
|
|
if (!drawing) return;
|
|
ctx.lineTo(e.offsetX, e.offsetY);
|
|
sendMessage(lineId, e.offsetX, e.offsetY);
|
|
ctx.stroke();
|
|
});
|
|
|
|
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);
|
|
</script>
|
|
{{end}}
|