Bouncing animation - Javascript Canvas

Javascript examples for Canvas:Animation

Description

Bouncing animation

Demo Code

ResultView the demo in separate window

<html>
   <head> 
      <title>Canvas example for jack</title> 
      <meta name="viewport" content="width=device-width, initial-scale=1"> 
      <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> 
      <style id="compiled-css" type="text/css">

body {/*from   w  w  w  .  j  a v a2  s .c  o  m*/
   padding: 20px;
}
canvas {
   border: 1px solid #000
}


      </style> 
      <script type="text/javascript">
    $(window).load(function(){
var context = document.getElementById('stage').getContext('2d');
var FPS = 50;
var width = 450;
var height = 450;
function collision(c1, c2) {
  var dx = c1.x - c2.x;
  var dy = c1.y - c2.y;
  var dist = c1.radius + c2.radius;
  return (dx * dx + dy * dy <= dist * dist)
}
function Ball(x, y, speedX, speedY, color) {
  this.x = x;
  this.y = y;
  this.radius = 10;
  this.speedX = speedX;
  this.speedY = speedY;
  this.color = color;
  this.draw = function(){
    context.beginPath();
    context.arc(this.x, this.y, this.radius, 0, Math.PI*2, true);
    context.closePath();
    context.fillStyle = this.color;
    context.fill();
  };
  this.move = function(balls){
    if(this.x + this.radius >= width || this.x - this.radius <= 0) {
      this.speedX *= -1
    }
    if(this.y + this.radius >= height || this.y - this.radius <= 0 ) {
      this.speedY *= -1
    }
    this.x = this.x + this.speedX;
    this.y = this.y + this.speedY;
    for(var i = 0; i < balls.length; i++) {
        if(this != balls[i] && collision(this,balls[i])) {
            this.color = '#E0E01B';
        }
    }
    this.draw();
  }
  return true;
}
var balls = [];
balls.push(new Ball(20, 20, -5, -2, '#00ff00'));
balls.push(new Ball(100, 200, -7, -2, '#ff0000'));
balls.push(new Ball(70, 150, 3, 1, '#0000ff'));
balls.push(new Ball(350, 350, 4, 2, '#000000'));
setInterval(function(){
  // clear stage
  context.clearRect(0, 0, width, height);
  for(var i = 0; i < balls.length; i++) {
    //var otherBalls = balls;
    balls[i].move(balls);
  }
}, 1000/FPS)
    });

      </script> 
   </head> 
   <body> 
      <canvas id="stage" width="450" height="450"></canvas>  
   </body>
</html>

Related Tutorials