Skip to main content

How to draw animated circles in HTML5 canvas

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 here

You 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

  1. Canvas Setup: The canvas fills the entire window.
  2. 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.
  3. Animation Loop:
    • Clears the canvas.
    • Moves each circle.
    • Calls requestAnimationFrame(animate) for smooth animation.

Comments

Popular posts from this blog

8 Mistakes Every Beginner Programmer Makes (and How to Avoid Them)

  Starting with programming can be exciting but also challenging. Every beginner makes mistakes—it's part of the learning process! However, knowing common pitfalls can help you improve faster. Here are eight mistakes every beginner programmer makes and how to avoid them. 1. Not Understanding the Problem Before Coding ❌ Mistake: Jumping straight into coding without fully understanding the problem can lead to messy, inefficient, or incorrect solutions. ✅ Solution: Take a step back and analyze the problem . Break it into smaller parts and think about the logic before writing any code. Use flowcharts, pseudocode, or even pen and paper to sketch out your solution. 📌 Example: Instead of diving into loops, first clarify what needs to be repeated and under what conditions. 2. Ignoring Error Messages ❌ Mistake: Many beginners panic when they see an error message and either ignore it or randomly change things to make the error disappear. ✅ Solution: Read the error message carefully —it of...

Understanding SQL Query Execution Order

When writing SQL queries, understanding the execution order is crucial for writing efficient and optimized code. Many beginners assume that queries execute in the order they are written, but in reality, SQL follows a specific sequence of execution. SQL Execution Order SQL queries run in the following order: 1️⃣ FROM + JOIN 2️⃣ WHERE 3️⃣ GROUP BY 4️⃣ HAVING 5️⃣ SELECT (including window functions) 6️⃣ ORDER BY 7️⃣ LIMIT Let’s break down each step with examples. 1. FROM + JOIN (Data Retrieval) The SQL engine first retrieves data from the specified table(s) and applies any JOIN operations. 🔹 Example: SELECT employees.name, departments.department_name FROM employees JOIN departments ON employees.department_id = departments.id; Here, the JOIN happens before any filtering ( WHERE ) or grouping ( GROUP BY ). 2. WHERE (Filtering Data) Once data is retrieved, the WHERE clause filters rows before aggregation occurs. 🔹 Example: SELECT * FROM employees WHERE salary > 50000 ; Thi...

Exploring the Latest AI Tools: Revolutionizing Productivity and Creativity

Artificial Intelligence (AI) continues to revolutionize various industries by providing powerful tools that enhance creativity, productivity, and efficiency. Here’s a curated list of the latest AI tools across different domains in 2024: Design Tools AI-powered design tools help streamline the creative process, making it easier to create stunning visuals, graphics, and branding materials. Autodraw – AI-assisted sketching tool. Flair AI – Generates high-quality product mockups. Booth AI – AI-driven photoshoot generator. Content Creation These tools assist in generating and enhancing content, from text to multimedia, making content production more efficient. Writesonic – AI-powered writing assistant for blogs and ads. Beautiful AI – Smart presentation design tool. Stocking AI – Generates realistic stock images. Clipdrop – Enhances and removes background from images. Steve AI – Converts text into animated videos. Tome – AI storytelling and presentation software. Murf AI – AI voic...