canvas accleration

To create a quadratic motion animation with HTML5 Canvas, we can increment the vx (horizontal velocity), the vy (vertical velocity), or both the vx and the vy of an object for each frame, and then update the position of the object, according to the equation of acceleration: distance = velocity * time + 1/2 * acceleration * time ^2

by bhupendra negi

HTML

<canvas width = "400" height = "200" id = "myCanvas">
    NO browser suppport for canvas
</canvas>
<input type = "button" value = "GO !" id = "start"/>

CSS

canvas {
    
   border: 1px solid blue;
}

JavaScript

var strbtn = document.getElementById("start");
strbtn.addEventListener("click",ongo,false);



function drawRectangle(myRect,context)
{
 context.beginPath();
 context.fillStyle = "yellow";
 context.rect(myRect.x,myRect.y,myRect.width,myRect.height);
 context.lineWidth = 5;
 context.fill();
 context.strokeStyle = "black";
 context.stroke();
    
}


 function animate(myRectangle, canvas, context, startTime)
{
    var time = (new Date()).getTime() - startTime;
    console.log("time elapsed :" + time);
    
    var gravity = 10;
    // distance = velocity*time + .5 * accleration * t^2
    newY= .5*gravity * Math.pow(time/1000,2)
    
    //changing x position of rectangle;
     if(newY < canvas.height - myRectangle.height) {
          myRectangle.y = newY;
   
    //clear canvas for new frame 

    context.clearRect(0, 0, canvas.width, canvas.height);
    // drawing new rectangle frame
    drawRectangle(myRectangle,context);
   
     requestAnimationFrame(function() {
          animate(myRectangle, canvas, context, startTime);
        });
     }
    
    
}

var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');

     
//intial configuration of rectangle 
var myRectangle = {
        x: 150,
        y: 0,
        width: 100,
        height: 50,
        borderWidth: 5
      };

      drawRectangle(myRectangle, context);

 // on GO click animation starts 
function ongo()
{
var startTime = (new Date()).getTime();
console.log(startTime);
animate(myRectangle, canvas, context, startTime);
}