add delays in animations in canvas? - Javascript Canvas

Javascript examples for Canvas:Animation

Description

add delays in animations in canvas?

Demo Code

ResultView the demo in separate window

<!doctype html>
<html>
   <head> 
      <script src="https://code.jquery.com/jquery.min.js"></script> 
      <style>

body{ background-color: ivory; }
canvas{border:1px solid red;}

      </style> 
      <script>
    $(function(){/*from  w w  w. j  a  v  a 2s .co m*/
        var canvas=document.getElementById("canvas");
        var ctx=canvas.getContext("2d");
        ctx.fillStyle="skyblue";
        ctx.strokeStyle="lightgray";
        ctx.lineWidth=4;

        var r=0;
        var interval=100;
        $("#interval").text("Call randomFill to rotate every "+interval+"ms");
        var lastTime;
        requestAnimationFrame(animate);
        function animate(timestamp) {

            if(!lastTime){lastTime=timestamp;}
            // calculate the elapsed time
            var elapsed=timestamp-lastTime;
            if(elapsed>interval){

                r+=Math.PI/120;
                randomFill(r);
                lastTime=performance.now();
            }
            requestAnimationFrame(animate);
        }
        function randomFill(r){
            ctx.clearRect(0,0,ctx.canvas.width,ctx.canvas.height)
            ctx.save();
            ctx.translate(100,100);
            ctx.rotate(r);
            ctx.fillRect(-25,-25,50,50);
            ctx.strokeRect(-25,-25,50,50);
            ctx.restore();
        }
    }); // end $(function(){});

      </script> 
   </head> 
   <body> 
      <p id="interval">Call randomFill</p> 
      <canvas id="canvas" width="350" height="350"></canvas>  
   </body>
</html>

Related Tutorials