Skip to content Skip to sidebar Skip to footer

Drawing A Shape In Canvas On Repeat

I'm new here and trying to get canvas to work for me. I wanted to make a canvasanimation where a circle was redrawn every 2 seconds with a canvas reset in between. The circle shoul

Solution 1:

You can use the timestamp that requestAnimationFrame feeds to its animation function to throttle the drawing to 1 frame-per-second.

Given the timestamp fed into your animation loop, calculate the milliseconds that have elapsed since the last draw. If 1000ms haven't elapsed, do nothing. If 1000ms have elapsed, do the draw() and reset the startTime to wait for another 1000ms to elapse.

Example code and a Demo: http://jsfiddle.net/m1erickson/mwuc0tby/

var startTime;
var interval=1000;

requestAnimationFrame(animate);

functionanimate(t){
    requestAnimationFrame(animate);
    if(!startTime){startTime=t;}
    if(t-startTime<interval){return;}
    startTime=t;
    draw();
}

I suggest using requestAnimationFrame because it comes with some nice built-in efficiencies in terms of resources and performance.

Solution 2:

You can use setInterval instead:

setInterval(function() {
  // draw the circle// reset
}, 2000);

Post a Comment for "Drawing A Shape In Canvas On Repeat"