Source Code: (back to article)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Animation Example</title>
<style>
canvas {
border: 1px solid black;
}
</style>
</head>
<body>
<canvas id="animationCanvas" width="200" height="200"></canvas>
<script>
const canvas = document.getElementById('animationCanvas');
const ctx = canvas.getContext('2d');
let x = 0; // Starting position
function drawFrame() {
ctx.clearRect(0, 0, canvas.width, canvas.height); // Clear the canvas for the new frame
ctx.fillStyle = 'green'; // Set the fill color to green
ctx.fillRect(x, 20, 50, 50); // Draw a moving rectangle
x++; // Increment the horizontal position
if (x < canvas.width) {
requestAnimationFrame(drawFrame); // Continue the animation
}
}
drawFrame();
</script>
</body>
</html>