place/web/place.js

83 lines
1.8 KiB
JavaScript
Raw Permalink Normal View History

2024-06-13 17:25:45 +00:00
const apiBase = "localhost:8080";
const ssl = false;
2024-06-13 11:25:18 +00:00
var tiles = [];
var color = {
r: 0,
g: 0,
b: 0
};
async function getInfo() {
2024-06-13 17:25:45 +00:00
let response = await fetch(`${ssl ? "https" : "http"}://${apiBase}/info`);
2024-06-13 11:25:18 +00:00
return await response.json();
}
2024-06-13 17:25:45 +00:00
async function sendPixel(canvas, x, y, c) {
2024-06-13 11:25:18 +00:00
let bounds = canvas.getBoundingClientRect();
x = x - bounds.left;
y = y - bounds.top;
2024-06-13 17:25:45 +00:00
let response = await fetch(`${ssl ? "https" : "http"}://${apiBase}/set`, {
2024-06-13 12:43:09 +00:00
method: "POST",
credentials: 'include',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
x: x,
y: y,
r: c.r,
g: c.g,
b: c.b
})
});
2024-06-13 11:25:18 +00:00
2024-06-13 12:43:09 +00:00
switch (response.status) {
case 400:
alert("missing parameters in request");
break;
case 403:
alert("not allowed to set another pixel yet");
break;
case 500:
alert(`failed to set pixel at ${x}-${y} to ${c}`);
break;
2024-06-13 11:25:18 +00:00
}
}
function init(info, ctx) {
for (let y = 0; y < info.canvasSize; y++) {
tiles.push([]);
for (let x = 0; x < info.canvasSize; x++) {
let tile = new Image();
tile.onload = () => ctx.drawImage(tile, x * info.tileSize, y * info.tileSize);
2024-06-13 17:25:45 +00:00
tile.src = `${ssl ? "https" : "http"}://${apiBase}/tile?x=${x}&y=${y}`;
2024-06-13 11:25:18 +00:00
tiles[y].push(tile);
}
}
}
2024-06-13 17:25:45 +00:00
async function updates(ctx) {
let socket = new WebSocket(`ws://${apiBase}/updates`);
socket.onmessage = async e => {
let pixel = await JSON.parse(e.data);
ctx.fillStyle = `rgb(${pixel.r}, ${pixel.g}, ${pixel.b})`;
ctx.fillRect(pixel.x, pixel.y, 1, 1);
}
}
2024-06-13 11:25:18 +00:00
async function main() {
let info = await getInfo();
console.log(info);
let canvas = document.getElementById("place");
let ctx = canvas.getContext("2d");
init(info, ctx);
2024-06-13 17:25:45 +00:00
updates(ctx);
canvas.onclick = e => sendPixel(canvas, ctx, e.clientX, e.clientY, color);
2024-06-13 11:25:18 +00:00
}
main();