Smooth SVG Path Morphing with flubber

The goal of this library is to provide a best-guess interpolation for any two arbitrary shapes (or collections of shapes) that results in a reasonably smooth animation, without overthinking it.

Installation per npm:

npm install flubber

Note that flubber only calculates the interpolated data:

import { interpolate } from "flubber";

const triangle = "M1,1 L2,1 L1.5,2 Z";
const pentagon = [[0, 0], [1, 1], [3, 1], [2, 0.5], [0, 1]];

const interpolator = interpolate(triangle, pentagon);
interpolator(0); // returns the SVG triangle path string
interpolator(0.5); // returns something halfway between the triangle and the pentagon
interpolator(1); // returns the SVG pentagon path string

To actually animate the SVG path you’ll need to call interpolator yourself on a timed interval, and set the path data to the returned result.

// Animate with a duration of 1250ms
animateOverTime(1250, (progress) => {
    myPathElement.setAttribute("d", interpolator(t));
});

This looks like a great thing to combine with some easing functions 😉

flubber (GitHub) →

☝️ animateOverTime above is a custom function I quickly throw together. It allows one to perform a callback during a given period of time. Underneath the hood it’s powered by requestAnimationFrame.

See the Pen Timed requestAnimationFrame by Bramus (@bramus) on CodePen.

Published by Bramus!

Bramus is a frontend web developer from Belgium, working as a Chrome Developer Relations Engineer at Google. From the moment he discovered view-source at the age of 14 (way back in 1997), he fell in love with the web and has been tinkering with it ever since (more …)

Join the Conversation

1 Comment

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.