Create bouncing ball object
<!doctype html> <html> <head> <title>Bouncing ball object example</title> </head>/*from w w w. jav a2s . com*/ <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 = "red"; let ball; window.onload = init; function init() { ball = new Ball(radius, color); ball.x = 50; ball.y = 50; ball.vx = 2; ball.vy = 0; ball.draw(context); setInterval(onEachStep, 1000 / 60); // 60 fps }; function onEachStep() { 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; } context.clearRect(0, 0, canvas.width, canvas.height); ball.draw(context); }; </script> </body> </html>