HTML5 Game - Balling moving at constant speed

Description

Balling moving at constant speed

Demo

ResultView the demo in separate window

<!doctype html>
<html>
<body>
<canvas id="canvas" width="700" height="500"></canvas>
<script>
class Ball {/*from   ww w.j a  v a2  s .com*/
  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 ball;
let t0; // time at last call
let dt; // elapsed time between calls
 
window.onload = init; 
 
function init() {
  ball = new Ball(20,"#0000ff");
  ball.x = 50; ball.y = 250;
  ball.vx = 200;
  ball.draw(context);
  t0 = new Date().getTime(); // initialize value of t0  
  animFrame();
};

function animFrame(){
  requestAnimationFrame(animFrame,canvas);
  onEachStep();
}
 
function onEachStep() {
  let t1 = new Date().getTime();
  dt = 0.001*(t1-t0); // time elapsed in seconds since last call
  t0 = t1; // reset t0
  ball.x += ball.vx * dt; 
  context.clearRect(0, 0, canvas.width, canvas.height);  
  ball.draw(context); 
}
   
  </script>
</body>
</html>

Related Topic