place/web/place.js

65 lines
1.3 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;
try {
await fetch(`${apiBase}/set`, {
method: "POST",
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
x: x,
y: y,
r: c.r,
g: c.g,
b: c.b
})
});
ctx.fillStyle = `rgb(${c.r}, ${c.g}, ${c.b})`;
ctx.fillRect(x, y, 1, 1);
} catch {
alert(`failed to set pixel at ${x}-${y} to ${c}`);
}
}
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();