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