Jump to content
Search Community

DynamicProps

aokorodu test
Moderator Tag

Recommended Posts

Ah, DynamicProps was way back from the ActionScript days :) Typically you could just recreate the tween each time the "target" object moves to a new position (and don't forget to set overwrite: true or overwrite: "auto" so that the previous one is killed). But if you need a single tween instance so that it definitely ends after a certain amount of time and the ease gets adjusted on-the-fly, I whipped together a helper function that you can feed into a modifier, as demonstrated here: 

See the Pen 1ed6118d993bac95e12d3236cc836f9e?editors=0010 by GreenSock (@GreenSock) on CodePen

 

Notice when you drag the red dot, the blue will start animating there no matter where you move it, and it'll always end up exactly on top of it after 5 seconds (the duration of the tween). Of course when the tween ends, it doesn't keep following it. 

 

Helper function:

// the "getter" can be a function with your own logic OR you can pass in another target whose property should be copied.
function getDynamicProp(prop, getter) {
  let ratio = 0,
      result, initted, copy, unit;
  if (typeof(getter) !== "function") {
    copy = (typeof(getter) === "string") ? document.querySelector(getter) : getter;
    getter = () => gsap.getProperty(copy, prop);
  }
  return function(value, target) {
    if (this.ratio !== ratio || !initted) {
      let end = parseFloat(getter()),
          factor = (this.ratio == 1 || ratio == 1) ? 0 : 1 - ((this.ratio - ratio) / (1 - ratio));
      if (!initted) {
        unit = typeof(value) === "string" ? gsap.utils.getUnit(value) : 0;
        initted = true;
      }
      result = (end - ((end - gsap.getProperty(target, prop)) * factor)) + unit;
      ratio = this.ratio;
    }
    return result;
  };
}

Usage example: 

gsap.to("#box", {
  x: "+=1", // these values don't matter - we'll override them with modifiers. These are placeholders.
  y: "+=1",
  duration: 5, 
  modifiers: {
    x: getDynamicProp("x", this.target),
    y: getDynamicProp("y", this.target)
  }
});

You can define your own getter functions if you want. 

 

This isn't an "official" plugin or solution or anything, but hopefully it gets you what you need. Thanks for being a Club GreenSock member! 🙌

 

Does that help? 

  • Like 4
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...