Step 1 - Draw Circle
Step 2 - Draw multiple circles
Step 3 - Animate one circle
Step 4 - Animate multiple circles
Step 5 - Add colors to Animated Circles
detail post hereYou can draw animated circles in an HTML5 canvas using JavaScript by leveraging the requestAnimationFrame
function. Below is a step-by-step guide to animating circles using the Canvas API.
Step 1: Create an HTML5 Canvas
First, create an HTML file with a <canvas>
element:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Animated Circles</title>
<style>
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
background-color: black;
}
canvas {
border: 1px solid white;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script src="script.js"></script>
</body>
</html>
Step 2: JavaScript Code to Animate Circles
Create a script.js
file with the following logic:
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
// Set canvas size to full window
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
// Circle properties
const circles = [];
const numCircles = 10;
// Function to generate random values
function random(min, max) {
return Math.random() * (max - min) + min;
}
// Circle class
class Circle {
constructor(x, y, radius, dx, dy, color) {
this.x = x;
this.y = y;
this.radius = radius;
this.dx = dx; // X velocity
this.dy = dy; // Y velocity
this.color = color;
}
draw() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false);
ctx.fillStyle = this.color;
ctx.fill();
ctx.closePath();
}
update() {
// Bounce off walls
if (this.x + this.radius > canvas.width || this.x - this.radius < 0) {
this.dx = -this.dx;
}
if (this.y + this.radius > canvas.height || this.y - this.radius < 0) {
this.dy = -this.dy;
}
// Move circle
this.x += this.dx;
this.y += this.dy;
this.draw();
}
}
// Create multiple circles
for (let i = 0; i < numCircles; i++) {
let radius = random(10, 40);
let x = random(radius, canvas.width - radius);
let y = random(radius, canvas.height - radius);
let dx = random(-2, 2);
let dy = random(-2, 2);
let color = `hsl(${random(0, 360)}, 100%, 50%)`;
circles.push(new Circle(x, y, radius, dx, dy, color));
}
// Animation loop
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height); // Clear canvas
circles.forEach(circle => circle.update()); // Update circles
requestAnimationFrame(animate);
}
// Start animation
animate();
How It Works
- Canvas Setup: The canvas fills the entire window.
- Circle Class:
- Each circle has a random position, size, speed, and color.
- The
draw()
method renders the circle. - The
update()
method updates its position and bounces it off walls.
- Animation Loop:
- Clears the canvas.
- Moves each circle.
- Calls
requestAnimationFrame(animate)
for smooth animation.
- Get link
- X
- Other Apps
- Get link
- X
- Other Apps
Comments
Post a Comment