How to use requestAnimationFrame to animate multiple squares in a loop

前端 未结 2 1370
自闭症患者
自闭症患者 2021-01-24 01:32

I am using HTML canvas to draw multiple squares. I have 2 functions: 1) draw a square and 2) draw multiple squares inside a loop.

Now I want to animate these squares us

2条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-24 02:16

    You can do something like

    var numRects = 10;
    var size = 5;
    var i = 1;                          // which rectangle we're drawing
    var delay = 1000/60;                // num miliseconds between frames
    var before = new Date().getTime(),  // last draw time in ms
        now;                            // current time in ms
    
    function animateRect() {
      // get the current time to find if we should draw
      now = new Date().getTime();
    
      // if sufficient time passed since last draw, draw a rect
      if ( now - before > delay && i <= numRects) {
        rect(i * size, i * size, (i * size) * 2, (i * size) * 2);
        i++;
        before = now;
      }
    
      requestAnimFrame(animateRect);
    }
    

    Edit:

    As Blindman67 pointed out below, requestAnimFrame passes the current timestamp since the beginning of the animation to the callback. Here's how to take advantage of it:

    var numRects = 10;
    var size = 5;
    var i = 1;                          // which rectangle we're drawing
    var delay = 1000/60;                // num miliseconds between frames
    var before;                         // last draw time in ms
    
    function animateRect(now) {
        if ( !before ) before = now;
        // if sufficient time passed since last draw, draw a rect   
        if ( now - before > delay && i <= numRects) {
            rect(i * size, i * size, (i * size) * 2, (i * size) * 2);
            i++;
            before = now;
        }
    
        requestAnimFrame(animateRect);
    }
    

    However, this would necessitate modifying the shim the OP is using, in order to pass the current timestamp to the callback in setTimeout:

    window.requestAnimFrame = (function() {
        return window.requestAnimationFrame ||
            window.webkitRequestAnimationFrame ||
            window.mozRequestAnimationFrame ||
            window.oRequestAnimationFrame ||
            window.msRequestAnimationFrame ||
            function( /* function */ callback, /* DOMElement */ element) {
                window.setTimeout(callback, 1000 / 60, new Date.now());
            };
        })();
    

提交回复
热议问题