// configure the canvas -- our playspace...magic circle and what not const canvas = document.getElementById("gameCanvas"); canvas.width = 512; canvas.height = 512; const ctx = canvas.getContext("2d"); ctx.fillStyle = "#E0F8CF"; ctx.fillRect(0, 0, canvas.width, canvas.height); // our noble avatar into playspace const player = { x: 50, y: 50, width: 16, height: 16, step: 10, color: "#65ff00", colorAlt: "pink", spriteUrl: "chickadee.svg" }; const playerSprite = new Image(); playerSprite.src = player.spriteUrl; // add keyboard input // FIXME: this input is blocking, allowing for only 1 key to be read at a time // this means that if you wanna do 2 things at 1 time you cannot. // For more info, document.addEventListener("keydown", (event) => { switch (event.code) { case "ArrowLeft": case "KeyH": case "KeyA": player.x -= player.step; break; case "ArrowRight": case "KeyL": case "KeyD": player.x += player.step; break; case "ArrowUp": case "KeyK": case "KeyW": player.y -= player.step; break; case "ArrowDown": case "KeyJ": case "KeyS": player.y += player.step; break; case "KeyZ": case "KeyN": console.log('Action A'); break; case "KeyX": case "KeyM": console.log('Action B'); break; } }); // game loop function gameLoop() { // clear the canvas every tick ctx.clearRect(0, 0, canvas.width, canvas.height); // looping canvas space so you can't wander out of view // this feels like a hack... if (player.x < 0) { player.x = canvas.width - 1 } if (player.x > canvas.width) { player.x = 1 } if (player.y < 0) { player.y = canvas.height - 1 } if (player.y > canvas.height) { player.y = 1 } // draw // ctx.fillStyle = player.color; ctx.fillRect(player.x, player.y, player.width, player.height); ctx.drawImage(playerSprite, player.x, player.y, player.width, player.height); // next frame requestAnimationFrame(gameLoop); } // start the game loop requestAnimationFrame(gameLoop);