object drop animation - Javascript Canvas

Javascript examples for Canvas:Animation

Description

object drop animation

Demo Code

ResultView the demo in separate window

<html>
   <head> 
      <meta name="viewport" content="width=device-width, initial-scale=1"> 
      <script type="text/javascript" src="https://code.jquery.com/jquery-3.0.0.js"></script> 
      <script type="text/javascript">
    window.onload=function(){/* w  w  w. j  a  v a 2s .  c  o m*/
var canvas, context;
var canvasDisplayed = false;
var intervalAnimation = null;
var posX, posY, vx, vy, gravity;
$('.two').click(function() {
  if (!canvasDisplayed) {
    showCanvas()
  }
  animation()
});
function showCanvas () {
   canvasDisplayed = true;
   canvas = document.getElementById('canvas2');
  context = canvas.getContext('2d');
  context.fillStyle = "black";
  context.fillRect(0,0,canvas.width,canvas.height);
}
function resetSquare () {
   posX = 20;
  posY = canvas.height / 2;
  vx = 8,
  vy = -10;
  gravity = 1;
}
function animation () {
   resetSquare()
   animationEnd()
  intervalAnimation = setInterval(function(){
        context.fillStyle = "black";
      context.fillRect(0, 0, canvas.width, canvas.height)
    posX += vx;
    posY += vy;
    if (posY > 120){
      vy *= -0.5;
      vx *= 0.5;
      posY = 120;
    }
    vy += gravity;
    context.fillStyle = "red";
    context.fillRect(posX, posY, 10, 10);
  }, 30);
}
function animationEnd () {
   context.fillStyle = "black";
   context.fillRect(0, 0, canvas.width, canvas.height);
   clearInterval(intervalAnimation);
}
    }

      </script> 
   </head> 
   <body> 
      <canvas class="canvas2" id="canvas2"></canvas> 
      <script src="canvas.js"></script> 
      <div class="buttons"> 
         <button class="two">Canvas 2</button> 
      </div>  
   </body>
</html>

Related Tutorials