Introduction to Canvas

From XPUB & Lens-Based wiki
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.

How to move a square across a canvas element, by clicking your mouse...

<html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>



<script type='text/javascript'>
/// YOUR JACAVASCRIPT GOES HERE, SEE BELOW....
</script>
</head>
<body>
    
<canvas id='myCanvas' width='600' height='600'></canvas>


</body>
</html>


<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);

});