Skip to content

LayoutMorph

The LayoutMorph plugin makes it easy to smoothly animate elements when they suddenly change size or position because of DOM changes (like sorting a list, or toggling a CSS class).

It uses a technique called FLIP to calculate everything instantly and then animate it smoothly using hardware-accelerated transforms. This ensures high performance even with many elements.


1. Execution Pipeline

LayoutMorph works in three simple steps:

  1. Capture: Save the current position and size of the elements before you change anything.
  2. Change: Make your changes to the DOM or CSS.
  3. Animate: Call animateFrom() to smoothly move the elements from their old captured position to their new one.

In this demo, clicking the background toggles the flex direction. LayoutMorph handles the smooth transition between the two layouts.

60 FPS
js
// 1. Capture State
const state = AnimX.LayoutMorph.getState('.grid-item')

// 2. Change the DOM
document.querySelector('.grid').classList.toggle('is-column')

// 3. Animate the transition
AnimX.LayoutMorph.animateFrom(state, {
  duration: 0.6,
  ease: 'power3.inOut',
  stagger: 0.05
})

By default, LayoutMorph tracks x, y, scale, rotation, and opacity. If you want it to animate other CSS properties (like backgroundColor or borderRadius), you must explicitly tell it to in getState:

js
const state = AnimX.LayoutMorph.getState('.box', { 
  props: ['backgroundColor', 'borderRadius'] 
})

2. Fitting Elements

The fit method animates an element so that it perfectly matches the size and position of another target element. This is really useful for "shared-element" transitions where a small item expands into a larger view.

Click the background below to watch the small blue box stretch and move perfectly over the target box.

Target
60 FPS
js
AnimX.LayoutMorph.fit('.small-box', '.large-target', {
  duration: 0.8,
  ease: 'power2.out'
})

API Reference

Importing

js
import { LayoutMorph } from 'animx/layout-morph'

Static Methods

MethodDescription
getState(targets, config)Saves the current position, size, and CSS of the elements. Returns a state object.
animateFrom(state, config)Creates an animation moving the elements from their old saved state to their new current layout.
fit(element, target, config)Animates an element to perfectly cover another target element. Returns an animation.
isMorphing(element)Returns true if the element is currently animating. Useful for preventing spam-clicks.

getState Configuration

PropertyTypeDefaultDescription
propsArraynullAdditional CSS properties to track and animate (e.g., ['color', 'borderRadius']).

animateFrom Configuration

Accepts standard Tween configuration properties.

PropertyTypeDefaultDescription
durationnumber0.5Length of the transition in seconds.
easestring'power2.inOut'Easing curve.
staggernumber0Delay in seconds between animating each element.
onStartFunctionnullFired when the morph begins.
onCompleteFunctionnullFired when the morph finishes.