// get the canvas element const canvas = document.getElementById("gameCanvas"); // set the canvas dimensions canvas.width = 512; canvas.height = 512; // get the canvas context const ctx = canvas.getContext("2d"); // set the background color ctx.fillStyle = "#e0f8cf"; ctx.fillRect(0, 0, canvas.width, canvas.height); // create a rectangle const rect = { x: 50, y: 50, width: 16, height: 16, step: 12, color: "#65ff00", colorAlt: "pink", }; // draw the rectangle ctx.fillStyle = rect.color; ctx.fillRect(rect.x, rect.y, rect.width, rect.height); // move the rectangle rect.x += 5; // clear the canvas ctx.clearRect(0, 0, canvas.width, canvas.height); // draw the rectangle ctx.fillStyle = rect.color; ctx.fillRect(rect.x, rect.y, rect.width, rect.height); // add keyboard input document.addEventListener("keydown", (event) => { switch (event.code) { case "ArrowLeft": case "KeyH": case "KeyA": rect.x -= rect.step; break; case "ArrowRight": case "KeyL": case "KeyD": rect.x += rect.step; break; case "ArrowUp": case "KeyK": case "KeyW": rect.y -= rect.step; break; case "ArrowDown": case "KeyJ": case "KeyS": rect.y += rect.step; break; case "KeyZ": case "KeyN": rect.color = "#65ff00"; break; case "KeyX": case "KeyM": rect.color = rect.colorAlt; break; } }); // game loop function gameLoop() { // clear the canvas ctx.clearRect(0, 0, canvas.width, canvas.height); // draw the rectangle ctx.fillStyle = rect.color; ctx.fillRect(rect.x, rect.y, rect.width, rect.height); // request the next frame requestAnimationFrame(gameLoop); } // start the game loop requestAnimationFrame(gameLoop);