Source Code:
(back to article)
Submit
Result:
Report an issue
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Game Control Example</title> <style> #gameArea { width: 300px; height: 300px; border: 1px solid black; position: relative; } #player { width: 50px; height: 50px; background-color: red; position: absolute; top: 125px; left: 125px; } </style> <script> document.addEventListener('DOMContentLoaded', function () { const player = document.getElementById('player'); let posX = player.offsetLeft; let posY = player.offsetTop; document.addEventListener('keydown', function(event) { switch (event.key) { case "ArrowUp": posY -= 10; break; case "ArrowDown": posY += 10; break; case "ArrowLeft": posX -= 10; break; case "ArrowRight": posX += 10; break; } player.style.left = posX + 'px'; player.style.top = posY + 'px'; }); }); </script> </head> <body> <div id="gameArea"> <div id="player"></div> </div> <p>Use arrow keys to move the red square within the game area.</p> </body> </html>