Falling ball with gravity, and bouncing
<!doctype html> <html> <body> <canvas id="canvas" width="700" height="500" style='border:1px solid black;'></canvas> <script> class MyObject{//from w ww . j a v a 2s . c om constructor(){ this.radius = 20; this.color = "#0000ff"; this.g = 0.1; // acceleration due to gravity this.positionX = 50; // initial horizontal position this.positionY = 50; // initial vertical position this.horizontalSpeed = 2; // initial speed this.verticalSpeed = 0; // initial speed } paint(){ } } class AnimationController{ } let canvas = document.getElementById('canvas'); let context = canvas.getContext('2d'); let radius = 20; let color = "#0000ff"; let g = 0.1; // acceleration due to gravity let positionX = 50; // initial horizontal position let positionY = 50; // initial vertical position let horizontalSpeed = 2; // initial speed let verticalSpeed = 0; // initial speed setInterval(refresh, 1000/60); // 60 fps function refresh() { verticalSpeed += g; // gravity increases the vertical speed positionX += horizontalSpeed; // horizontal speed increases horizontal position positionY += verticalSpeed; // vertical speed increases vertical position if (positionY > canvas.height - radius){ // if ball hits the ground positionY = canvas.height - radius; // reposition it at the ground verticalSpeed *= -0.8; // reverse and reduce its vertical speed } if (positionX > canvas.width + radius){ // if ball goes beyond canvas positionX = -radius; // wrap it around } context.clearRect(0, 0, canvas.width, canvas.height); context.fillStyle = color; context.beginPath(); context.arc(positionX, positionY, radius, 0, 2*Math.PI, true); context.closePath(); context.fill(); }; </script> </body> </html>