Introduction to Canvas

From XPUB & Lens-Based wiki
Revision as of 11:07, 21 June 2012 by Timo (talk | contribs)

<source lang='javascript'>

window.requestAnimFrame = (function(callback){

   return window.requestAnimationFrame ||
   window.webkitRequestAnimationFrame ||
   window.mozRequestAnimationFrame ||
   window.oRequestAnimationFrame ||
   window.msRequestAnimationFrame ||
   function(callback){
       window.setTimeout(callback, 1000 / 60);
   };

})();


function drawRect(myRectangle){

   context.beginPath();
   context.rect(myRectangle.x, myRectangle.y, myRectangle.width, myRectangle.height);
   context.fillStyle = "#8ED6FF";
   context.fill();

}

function animate(lastTime, myRectangle, animProp){

   if (animProp.animate) {

       // update
       var date = new Date();
       var time = date.getTime();
       var timeDiff = time - lastTime;
       var linearSpeed = 100;
       // pixels / second
       var linearDistEachFrame = linearSpeed * timeDiff / 10000;
       
       var currentX = myRectangle.x;

       if (currentX < canvas.width - myRectangle.width ) {
           var newX = currentX + linearDistEachFrame;
           myRectangle.x = newX;
       }
       lastTime = time;

       // clear
       context.clearRect(0, 0, canvas.width, canvas.height);

       // draw
       drawRect(myRectangle);

       // request new frame
       requestAnimFrame(function(){
           animate(lastTime, myRectangle, animProp);
       });
   }

}

$(document).ready(function() {

   //real canvas element
   canvas = document.getElementById("myCanvas");
   context = canvas.getContext("2d");
   var myRectangle = {
       x: 0,
       y: 50,
       width: 100,
       height: 50    };

   /*
    * make the animation properties an object
    * so that it can be modified by reference
    * from an event
    */
   var animProp = {
       animate: false
   };

   // add click listener to canvas
   $("#myCanvas").click( function(){
       if (animProp.animate) {
           animProp.animate = false;
       }
       else {
           animProp.animate = true;
           var date = new Date();
           var time = date.getTime();
           animate(time, myRectangle, animProp);
       }
   });

   drawRect(myRectangle);

});