Canvas How to - Stop a moving ball with Ease








Question

We would like to know how to stop a moving ball with Ease.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>//<![CDATA[ 
window.onload=function(){<!-- w  w w.j a v a2  s.  c om-->
function Ball(radius, color){
  this.radius = radius || 25;
  this.color = 'red';
  this.x = 0;
  this.y = 0;
  this.rotation = 0;
}
Ball.prototype.draw = function(context){
  context.save();
  context.fillStyle = this.color;
  context.translate(this.x, this.y);
  context.beginPath();
  context.arc(0, 0, this.radius, 0, Math.PI*2)
  context.fill();
  context.restore();
};
  var canvas = document.getElementById('canvas'),
        log = document.getElementById('log'),
    context = canvas.getContext('2d'),
    w = canvas.width,
    h = canvas.height,
        ball = new Ball(),
        angle = 3*Math.PI/180,
        cx = w/2,
        cy = h/2;
    (function keepDrawing(){
    context.clearRect(0, 0, w, h);
    var x1 = ball.x - cx,
      y1 = ball.x - cy,
      x2 = x1*Math.cos(angle) - y1*Math.sin(angle),
      y2 = y1*Math.cos(angle) + x1*Math.sin(angle);
    ball.x = cx + x2;
    ball.y = cy + y2;
    ball.draw(context);
        setTimeout(keepDrawing, 40)
  }());
}//]]>  
</script>
</head>
<body>
  <canvas id="canvas" width="500" height="300"></canvas>
</body>
</html>

The code above is rendered as follows: