Gravity Balls
Home
Snippets
Gravity Balls
HTML
CSS
JS
<canvas id="canvas"></canvas>
body { margin: 0; overflow: hidden; background: #0f172a; } canvas { display: block; }
const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); canvas.width = window.innerWidth; canvas.height = window.innerHeight; let balls = []; class Ball { constructor(x, y) { this.x = x; this.y = y; this.radius = 15 + Math.random() * 10; this.color = `hsl(${Math.random() * 360}, 70%, 60%)`; this.dy = 0; this.gravity = 0.5; this.bounce = 0.7; } update() { this.dy += this.gravity; this.y += this.dy; if (this.y + this.radius > canvas.height) { this.y = canvas.height - this.radius; this.dy *= -this.bounce; } this.draw(); } draw() { ctx.beginPath(); ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2); ctx.fillStyle = this.color; ctx.fill(); } } canvas.addEventListener("click", (e) => { balls.push(new Ball(e.clientX, e.clientY)); }); function animate() { ctx.clearRect(0, 0, canvas.width, canvas.height); balls.forEach(ball => ball.update()); requestAnimationFrame(animate); } animate();
Ad #1
Ad #2
Scroll to Top