Search code examples
javascriptjqueryanimationsvggsap

JS/GSAP solution for infinite animation


I am trying to create a infinite star rain animation, all stars are SVG's. I tried this to create the animation:

(function($) {
TweenMax.set(".astar", {
  x:function(i) {
    return i * 50;
  }
});


TweenMax.to(".astar", 5, {
  ease: Linear.easeNone,
  x: "+=500", //move each box 500px to right
  modifiers: {
    x: function(x) {
      return x % 500; //force x value to be between 0 and 500 using modulus
    }
  },
  repeat: -1
});
})(jQuery);

The repeat process is not smooth as you can see on this Codepen: https://codepen.io/daniellwdb/pen/NXogoB Is there any JS or GSAP solution to make the animation smooth so that it will look like stars keep spawning from the left and move to the right?


Solution

  • With your current setup, I think the easiest way to pull this off would be to duplicate your starfield so that the beginning of your next loop is identical to the end of your first one. Let's say this is your starfield SVG:

    |...o.|
    |o....|
    |..o..|
    

    Your new "duplicated" starfield would essentially be:

    |...o.|...o.|
    |o....|o....|
    |..o..|..o..|
    

    So when you move that duplicated image from left to right 100%, what you see in the last "frame" is identical to what it will return to when it loops.

    Here's a fiddle that shows this concept in action: https://jsfiddle.net/yarp4oLs/5/

    I have two identical starfield images that are 200x200 (so 400x200 when side-by-side) and they are displayed in a "viewport" container that is 200x200. Then I just slide them to the left 200px and repeat. Instant stars!