Bouncing ball
<!doctype html> <html> <head> <meta charset="utf-8"> <title>Bouncing balls</title> </head>/*from www . j a va 2 s. c o m*/ <body> <canvas id="canvas" width="700" height="500"></canvas> <script> class Ball { constructor(radius, color) { this.radius = radius; this.color = color; this.x = 0; this.y = 0; this.vx = 0; this.vy = 0; } draw(context) { context.fillStyle = this.color; context.beginPath(); context.arc(this.x, this.y, this.radius, 0, 2 * Math.PI, true); context.closePath(); context.fill(); } } let canvas = document.getElementById('canvas'); let context = canvas.getContext('2d'); let g = 0.1; let radius = 20; let color = "#0000ff"; let balls; let numBalls = 5; window.onload = init; function init() { balls = new Array(); for (let i = 0; i < numBalls; i++) { let ball = new Ball(radius, color); ball.x = 50; ball.y = 75; ball.vx = Math.random() * 5; ball.vy = (Math.random() - 0.5) * 4; ball.draw(context); balls.push(ball); } setInterval(onEachStep, 1000 / 60); // 60 fps }; function onEachStep() { context.clearRect(0, 0, canvas.width, canvas.height); for (let i = 0; i < numBalls; i++) { let ball = balls[i]; ball.vy += g; ball.x += ball.vx; ball.y += ball.vy; if (ball.y > canvas.height - radius) { ball.y = canvas.height - radius; ball.vy *= -0.8; } if (ball.x > canvas.width + radius) { ball.x = -radius; } ball.draw(context); } }; </script> </body> </html>