place/web/place.js

77 lines
1.6 KiB
JavaScript

const apiBase = "http://localhost:8080";
var tiles = [];
var color = {
r: 0,
g: 0,
b: 0
};
async function getInfo() {
let response = await fetch(`${apiBase}/info`);
return await response.json();
}
async function setPixel(canvas, ctx, x, y, c) {
let bounds = canvas.getBoundingClientRect();
x = x - bounds.left;
y = y - bounds.top;
let response = await fetch(`${apiBase}/set`, {
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
})
});
console.log(response);
switch (response.status) {
case 200:
ctx.fillStyle = `rgb(${c.r}, ${c.g}, ${c.b})`;
ctx.fillRect(x, y, 1, 1);
break;
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;
}
}
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);
tile.src = `${apiBase}/tile?x=${x}&y=${y}`;
tiles[y].push(tile);
}
}
}
async function main() {
let info = await getInfo();
console.log(info);
let canvas = document.getElementById("place");
let ctx = canvas.getContext("2d");
init(info, ctx);
canvas.onclick = e => setPixel(canvas, ctx, e.clientX, e.clientY, color);
}
main();