Skip to content

Instantly share code, notes, and snippets.

@EteimZ
Created January 25, 2024 11:22
Show Gist options
  • Save EteimZ/852b488ea522b2078418422a8f6cc070 to your computer and use it in GitHub Desktop.
Save EteimZ/852b488ea522b2078418422a8f6cc070 to your computer and use it in GitHub Desktop.
Moving box in HTML5 canvas
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Moving Box</title>
</head>
<body>
<canvas id="draw"></canvas>
</body>
<script src="index.js"></script>
</html>
const canvas = document.getElementById("draw");
const ctx = canvas.getContext("2d");
// Define canvas properties
canvas.style.border = "1px solid black";
canvas.width = 800;
canvas.height = 600;
// Set initial position of rectangle
let x = 10;
let y = 10;
// Listen for keyboard events
document.addEventListener("keydown", function (event) {
switch (event.key) {
case "ArrowLeft":
console.log("Move box left");
x -= 5;
break;
case "ArrowDown":
console.log("Move box down");
y += 5;
break;
case "ArrowRight":
console.log("Move box right");
x += 5;
break;
case "ArrowUp":
console.log("Move box up");
y -= 5;
break;
case "Enter":
console.log("Return box to original position");
x = 10;
y = 10;
break;
default:
console.log("Unknown key");
break;
}
});
// Function to perform animation
function animate() {
// Clear the canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draw the box at the updated position
ctx.fillStyle = "green";
ctx.fillRect(x, y, 150, 100);
// Request the next animation frame
requestAnimationFrame(animate);
}
// Start the animation
requestAnimationFrame(animate);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment