Search code examples
javascriptgsap

TweenMax / GSAP stagger raw array values


Let's say I have the following arrays with just numbers:

[0, 0, 0, 0]

and

[40, 50, 75, 80]

How do I interpolate from the first to the second, using staggering/cycling (with GSAP)? (And with staggering I mean, first do the first item, then after some delay, do the next).

Note: I have already converted the single number values to objects so that GSAP can work with them (so [{y: 0}, {y: 0}] and so forth


Solution

  • Answered by the following question on the GSAP forum:

    https://greensock.com/forums/topic/18692-interpolating-using-staggerto-from-one-array-w-values-to-the-next/

    To make it possible to interpolate between a single value in a array (in this case, a number), I had to create a new timeline-like object for every value

    var a = [0, 0, 0, 0];
    
    staggerArray(a, [10,20,30,40], {duration:1, stagger:0.5, round:true});
    
    //vars accepts: duration, stagger, round, as well as any typical vars for TimelineMax (like onComplete, onUpdate, repeat, yoyo, etc.)
    function staggerArray(start, end, vars) {
      var tl = new TimelineMax(vars),
          proxy = {},
          duration = vars.duration || 0,
          stagger = vars.stagger || 0,
          proxyUpdate = function(original, proxy, i) {
            return function() {
              original[i] = proxy[i];
            };
          },
          v, i;
      for (i = 0; i < start.length; i++) {
        proxy[i] = start[i];
        v = {};
        v[i] = end[i];
        v.onUpdate = proxyUpdate(start, proxy, i);
        if (vars.round) {
          v.roundProps = i + "";
        }
        tl.to(proxy, duration, v, stagger * i);
      }
      return tl;
    }