Web Development

GSAP MotionPath: Animating Elements Along an SVG Path

Team Nippysoft
• • 7 min read
GSAP MotionPath: Animating Elements Along an SVG Path

MotionPathPlugin is the GSAP plugin that moves an element along a path: an SVG <path>, a string of path data or a list of points. Without it, the code would have to work out the x, the y and the tangent angle on every frame; with it, a path and a tween are enough, and GSAP places and rotates the element.

The official demo shows it with an SVG group (<g>) traveling along a curve inside the same <svg> as the path. This post's demo is a paper plane on GSAP 3.15.0, with a slider that scrubs the flight, and it focuses on the tricky part: keeping the plane on the path when the screen width changes or a phone rotates.

This post is part of the GSAP series. Licensing and installation live in the series hub, and matchMedia and gsap.context in post 2, on the core. MotionPathPlugin has been free since 3.13, and two script tags are enough:

<script src="https://unpkg.com/gsap@3.15.0/dist/gsap.min.js"></script>
<script src="https://unpkg.com/gsap@3.15.0/dist/MotionPathPlugin.min.js"></script>
<script>
  gsap.registerPlugin(MotionPathPlugin);
</script>

The basics: motionPath in a tween

This one, based on the minimal example in the MotionPathPlugin docs, fits on one line:

// Assumes a #plane element and a <path id="route"> on the page.
gsap.to("#plane", { motionPath: { path: "#route" }, duration: 5 });

path takes an SVG <path> (selector or element), a string of path data, or an array of { x, y } points that GSAP draws a curve through. curviness tunes that curve (0 gives straight lines, 1 is the default), and type: "cubic" reads the points as a cubic Bézier:

// Assumes a #plane element; no SVG needed.
gsap.to("#plane", { motionPath: { path: "M9,100c0,0,18-41,49-65" }, duration: 5 });
gsap.to("#plane", {
  motionPath: { path: [{ x: 0, y: 0 }, { x: 120, y: -60 }, { x: 240, y: 0 }], curviness: 1.5 },
  duration: 5
});

A <circle> doesn't work as a path as it is: GSAP warns "Expecting a <path> element or an SVG path data string". MotionPathPlugin.convertToPath() turns a <circle>, <rect>, <ellipse> or <line> into a <path>.

align and alignOrigin: putting the element on the path

Without align, the path coordinates go straight into the element's x and y, so it traces the right shape but not necessarily on top of the path. With align: "#route", GSAP places it on the path even when the two live in different containers. It aligns the top left corner by default; alignOrigin: [0.5, 0.5] aligns the center and sets transformOrigin there too. align: "self" works the other way round: the path moves to the element so it doesn't jump at the start.

autoRotate, start and end

autoRotate: true turns the element to follow the path's direction. A number adds degrees to the turn: autoRotate: 90 for a drawing that faces up. The demo's plane faces right, so it uses true.

start and end mark the stretch, from 0 to 1. An end below start travels backwards, and one above 1 loops past the beginning.

Paths and responsive layouts

The docs warn that align isn't responsive: at the start, it works out once where the path sits relative to the element. If a resize then moves the path, the element keeps that stale math and drifts off. Their recipe is to listen for resize, store the tween's progress, kill it with progress(0).kill(), create a new one and jump back to the stored progress.

The demo takes a simpler route: the plane is a <g> inside the same <svg> as the path. Both are measured on the SVG's internal grid (its viewBox) and scale together, so the math the MotionPathPlugin 3.15.0 source does once still holds. At 900 and 390 px wide, before and after resizing, the plane's center stays within half a pixel of the path, without rebuilding the tween. The same plane as a <div> outside the SVG ends up 100 px or more off the path after going to 390 px, depending on how much the SVG shrinks.

// Assumes <svg viewBox="0 0 600 300"> holding <path id="route"> and <g class="plane">, plus a #progress slider.
const route = document.querySelector("#route");
const plane = document.querySelector(".plane");
const slider = document.querySelector("#progress");

const flight = gsap.to(plane, {
  motionPath: { path: route, align: route, alignOrigin: [0.5, 0.5], autoRotate: true },
  duration: 4,
  ease: "none",
  paused: true,
  onUpdate: () => { slider.value = Math.round(flight.progress() * 100); }
});
flight.progress(0); // places the plane at the start of the path

Scrubbing the flight with a slider

With ease: "none", 50% on the slider is half the route. Moving it pauses the tween and sets its progress(), as in post 2; when the plane flies on its own, onUpdate moves the slider:

// Continues the snippet above: uses flight and slider.
slider.addEventListener("input", () => {
  flight.pause();
  flight.progress(slider.value / 100);
  slider.setAttribute("aria-valuetext", slider.value + "%");
});

It works the same for a whole timeline, like the ones in post 3; with ScrollTrigger's scrub, from post 5, the scrollbar becomes the slider.

The slider is a native <input type="range"> with a <label>: arrow keys, Page Up, Page Down, Home and End already work, with no custom keys to program. Per ARIA in HTML, a range shouldn't carry aria-valuemin or aria-valuemax, since min and max cover them; aria-valuetext is fine, and WAI-ARIA 1.2 defines it as the human-readable text for the value, here "37%".

The demo: a paper plane

With full motion, the plane flies once when half of the demo comes into view; the flight lasts 4 s, under the 5 s after which criterion 2.2.2 of WCAG 2.2 asks for a way to pause, and it still has a Pause button. Under reduced motion nothing starts on its own: the slider moves the plane without animating, and it only flies when Play is pressed. gsap.matchMedia() handles that, as covered in post 2.

0%

MotionPathHelper: drawing the path in the browser

MotionPathHelper makes the path editable right on the page, with no back and forth between the browser and an SVG editor:

// Assumes MotionPathHelper.min.js is loaded, plus the flight tween from above.
gsap.registerPlugin(MotionPathPlugin, MotionPathHelper);
MotionPathHelper.create(flight);

Anchors and control points are dragged with the mouse; Alt+click adds a point, Delete removes the selected one and Ctrl+Z undoes. When the editing is done, the "COPY MOTION PATH" button copies the path data, ready to paste into the <path> or the tween. Taking it out of the final code is a call of this post, not of the docs: it weighs 44 KB minified and draws its own interface.

Common mistakes

  1. An HTML element aligned to an SVG path that scales. After a resize it drifts off the path.
  2. autoRotate: true with a drawing that faces up. It flies sideways; autoRotate: 90 fixes it.
  3. Any ease other than "none" behind a slider. The slider stops marking the share of the route: with the default ease, 50% puts the plane at 75% of the path. The eases from post 4 belong to the automatic flight.
  4. Leaving MotionPathHelper.create() in production. Readers would see the editing interface.
  5. A path selector that matches nothing. No warning names the path: the tween fails with "Cannot read properties of undefined (reading '0')".

FAQ

Is an SVG needed?

No. path takes a path data string or a list of points, with no <svg>.

Why does the element leave the path when the phone rotates?

Because align is computed once, at the start. There are two ways out: putting the element inside the same <svg> as the path, or rebuilding the tween on resize and keeping the progress.

Conclusion

The demo rests on four choices: path and element in the same <svg>, align with alignOrigin: [0.5, 0.5], autoRotate to match the drawing, and ease: "none" whenever a slider drives it.

The rest of the series lives in the hub and posts 2, 3, 4, 5, 6, 7, 8 and 9. Next up is post 11, on DrawSVG and MorphSVG.

References

Subscribe

Get the latest posts delivered right to your inbox.

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

Comments

No comments yet. Be the first to share your thoughts!

Subscribed!

Registered! A confirmation link has been sent to your email address. If you don't see it, please check your spam folder.

Error

An error occurred. Please try again.

Full code