Animating Graphics on Canvas
We can also create animations on the canvas using JavaScript and the HTML <canvas>
tag. Let's create a moving rectangle animation on our canvas.
<!doctype html>
<html>
<head>
<title>Animated Canvas</title>
</head>
<body>
<canvas id="myCanvas" style="border: 1px solid black;"></canvas>
<script>
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
let x = 20;
let y = 20;
const dx = 5;
function animate() {
requestAnimationFrame(animate);
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "red";
ctx.fillRect(x, y, 50, 50);
if (x + 50 > canvas.width || x < 0) {
dx = -dx;
}
x += dx;
}
animate();
</script>
</body>
</html>
In the above code, we first get the canvas element by its ID myCanvas
, and then we get a 2D drawing context by using getContext()
. We then declare some variables x
and y
to hold the position of our rectangle. We also declare dx
variable to move the rectangle along the x
axis.
We then create a function animate()
to draw the rectangle on the screen. We use the clearRect()
method to clear the previous drawings on the canvas on each frame. We then fill the rectangle with a red color using the fillRect()
method.
We then check if the rectangle has reached the boundaries of the canvas, and if so, we change the direction of the movement by changing the value of dx
.
Finally, we call the requestAnimationFrame()
method to create a loop for animation.
Save the file and refresh your browser to see the animated rectangle.