Capítulo 160 de 411

Chapter 160: Align transformOrigin of Two Elements (Helper)

Core Idea

A helper that instantly changes one element's transformOrigin to match another element's, without the visual jump that normally happens when transformOrigin changes (requires MotionPathPlugin for coordinate conversion).

Key Concepts

  • Reads the target element's computed transformOrigin, converts those coordinates into the source element's space via MotionPathPlugin.convertCoordinates().
  • After setting the new origin, it measures the resulting bounding-box shift and offsets x/y by the same amount to cancel out the jump.
  • Requires gsap.registerPlugin(MotionPathPlugin).

Code Examples

function alignOrigins(fromElement, toElement) {
  let [fromEl, toEl] = gsap.utils.toArray([fromElement, toElement]),
    a = window.getComputedStyle(toEl).transformOrigin.split(" "),
    newOrigin = MotionPathPlugin.convertCoordinates(toEl, fromEl, {
      x: parseFloat(a[0]), y: parseFloat(a[1]),
    }),
    bounds1 = fromEl.getBoundingClientRect(), bounds2;
  gsap.set(fromEl, { transformOrigin: newOrigin.x + "px " + newOrigin.y + "px" });
  bounds2 = fromEl.getBoundingClientRect();
  gsap.set(fromEl, {
    x: "+=" + (bounds1.left - bounds2.left),
    y: "+=" + (bounds1.top - bounds2.top),
  });
}
  • What it demonstrates: converting an origin between two elements' coordinate spaces, then compensating position so nothing visibly moves.

Key Takeaways

  1. Changing transformOrigin mid-animation normally causes a jump unless the position is compensated like this.
  2. Depends on MotionPathPlugin.convertCoordinates() for the coordinate-space math.

Connects To

  • MotionPathPlugin: provides the coordinate conversion this helper relies on.