diff options
-rw-r--r-- | js/canvas/game.js | 91 | ||||
-rw-r--r-- | js/canvas/index.html | 23 |
2 files changed, 114 insertions, 0 deletions
diff --git a/js/canvas/game.js b/js/canvas/game.js new file mode 100644 index 0000000..569cc4c --- /dev/null +++ b/js/canvas/game.js @@ -0,0 +1,91 @@ +// 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); \ No newline at end of file diff --git a/js/canvas/index.html b/js/canvas/index.html new file mode 100644 index 0000000..641eb20 --- /dev/null +++ b/js/canvas/index.html @@ -0,0 +1,23 @@ +<!DOCTYPE html> +<html> +<head> + <meta charset="utf-8"> + <meta name="viewport" content="width=device-width, initial-scale=1"> + <title>game</title> + <style type="text/css"> + body { + padding: 1em 0; + } + #gameCanvas { + border: 1px solid black; + margin: 0 auto; + display: block; + background-color: #f0f0f0; + } + </style> +</head> +<body> + <canvas id="gameCanvas" width="800" height="600"></canvas> + <script type="text/javascript" src="game.js"></script> +</body> +</html> \ No newline at end of file |