Jump to content
Search Community

Best practice of using GSAP when scrolling

Hossein Rahimi test
Moderator Tag

Recommended Posts

Hello members.
In my recent project, I want to animate something when the user is scrolling.
What is the best practice of using GSAP here?
I'm using ReactJS for my project.

This is an example of my code and I think it can be much better. Cause I feel slow and delayed animations.

 

useEffect(() => {
    const gsap = require("gsap").gsap;
    var _reqID;

    function loop() {
        var doc = aboutParent;
        var fh = footer.scrollHeight;
        var percent = (doc.scrollTop / (doc.scrollHeight - doc.clientHeight - fh)) * 100;

        var update = (percent / 100) * differ + start;
        if (Math.round(update) <= end && Math.round(update) >= start) {
          gsap.to(scrollerSVG, {
            duration: 0.5,
            x: 445,
            y: update,
          });
        }

      // run the loop
      _reqID = requestAnimationFrame(loop);
    }

    _reqID = requestAnimationFrame(loop);

    return function cancel() {
      cancelAnimationFrame(_reqID);
    };
}, []);

 

It's not all of the code. But I think its enough for you to understand my opinion.
I would be thankful if you help me with this.

Link to comment
Share on other sites

Hi @Hossein Rahimi,

 

I'm not entirely sure what you have happening in your animation, but I believe the slow/delayed feel you're getting may be because of your tween's duration is causing the tweens to stack up (you're telling it to do a new 0.5s tween to a new value on every tick).

 

Instead of this, you may want to consider using gsap's quicksetter method for this: https://greensock.com/docs/v3/GSAP/gsap.quickSetter()

 

The other way would be to define your animation first, and use scroll position to update the tl.progress()

 

I also prefer to use gsap's ticker (https://greensock.com/docs/v3/GSAP/gsap.ticker) over requestAnimationFrame(), but that's a personal preference thing (performance will be very similar)

 

 

 

 

 

 

 

  • Like 3
Link to comment
Share on other sites

Hi, there are some concepts you should look into:

First one is repaint/reflow of the document. You are trying to read scrollHeight etc. like variables, but this is super slow - so only do this when needed (move logic like this into a resize function)

Second one is "gsap.set" vs "gsap.to" and overwriting tweens. There is a lot in the docs about that.

Good luck :-)

  • Like 2
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...