Bouncing Ball With HTML/CSS And Javascript

const width = window.innerWidth;
const height = window.innerHeight;

const numBalls = 100;

	function getRandomColor(){
		const letters = '0123456789abcdef';
		let color = '#';

		for(let i = 0; i < 6; i++){
			color += letters[Math.floor(Math.random() * 16)];
		}
		return color;
	}

	function createBall(){
		const ball = document.createElement('div');
		ball.classList.add('ball');
		ball.style.left = `${Math.random() * (width - 50)}px`;
		ball.style.top = `${Math.random() * (height - 50)}px`;
		ball.style.backgroundColor = getRandomColor();
		ball.isGrowing = true;
		ball.scale = 1;
		document.body.appendChild(ball);
		return ball;
	}

	function animateBall(ball){
		let dx = (Math.random() - 0.5) * 8;
		let dy = (Math.random() - 0.5) * 8;

			function moveBall(){
				let x = parseFloat(ball.style.left);
				let y = parseFloat(ball.style.top);

				if(x + dx > width - 50 || x + dx < 0){
					dx = -dx;
					ball.style.backgroundColor = getRandomColor();
				}
				if(y + dy > height - 50 || y + dy < 0){
					dy = -dy;
					ball.style.backgroundColor = getRandomColor();
				}

				ball.style.left = `${x + dx}px`;
				ball.style.top = `${y + dy}px`;

				if(ball.isGrowing){
					ball.scale += 0.02;
					if(ball.scale > 2.5){
						ball.isGrowing = false;
					}
				}else{
					ball.scale -= 0.02;
					if(ball.scale < 0.05){
						ball.isGrowing = true;
					}
				}

				ball.style.transform = `scale(${ball.scale})`;

				requestAnimationFrame(moveBall);
				
			}
			moveBall();
	}

	for(let i = 0; i < numBalls; i++){
		const ball = createBall();
		animateBall(ball);
	}	


Post Comment