Book Review
Project Overview
The "Bouncing Balls" project is a fun and interactive example that showcases how to create moving elements within a defined container using JavaScript. The project dynamically generates balls that bounce within the boundaries of a container, with velocity and direction changing upon collision with the walls. This project is a great way to understand concepts like object-oriented programming, DOM manipulation, and basic animation.
Full Working Example
Bouncing Balls
Explanation
The "Bouncing Balls" project consists of a container element with a button to add balls dynamically. Each ball is represented by a div
element with a class of "ball" and a random color. The ball's position and velocity are controlled by the Ball
class, which defines the ball's radius, position, and velocity in the x and y directions. The moveWithin
method of the Ball
class updates the ball's position based on its velocity and reverses the velocity when the ball collides with the container's boundaries. The rand
function generates random values within a specified range. The DOMContentLoaded
event listener initializes the project by adding event listeners to the "Add Ball" button and creating new balls with random initial positions and velocities. The setInterval
function updates the ball's position every 25 milliseconds, creating the bouncing effect.
HTML Structure bouncing-balls
The HTML structure defines the container for the bouncing balls and a button to add new balls dynamically.
<div class="balls">
: Acts as the wrapper for the project layout.<div id="box">
: The container where the balls will bounce.<button id="addBall">
: A button to add new balls to the container.
JavaScript Code Explanation bouncing-balls
The JavaScript code is responsible for creating, styling, and animating the balls within the container. Here's a breakdown:
- Define the size of the balls and container dimensions.
- Constructor: Initializes ball properties like radius, position, and velocity.
moveWithin
Method: Handles collision detection and updates the ball's position based on its velocity.- A button click creates a new
Ball
object, assigns it random velocity, and appends it to the container. - The ball's position is updated at regular intervals using
setInterval
. - Generates a random value for the ball's velocity within a specified range.