Description

Use timer to create animation

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  a 2  s  . c o  m
  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;
 
window.onload = init; 
 
function init() {
  ball = new Ball(20,"#0000ff");
  ball.x = 50; ball.y = 250;
  ball.vx = 2;
  ball.draw(context);
  setInterval(onEachStep, 1000/60); // 60 fps
};
 
function onEachStep() {
  ball.x += ball.vx; 
  context.clearRect(0, 0, canvas.width, canvas.height);  
  ball.draw(context); 
};
   
  </script>
</body>
</html>

Related Topic