animejs svg tutorial
Javascript Web Development

Create SVG Morphing Animation with Anime.js

In this tutorial we will show you how to create an SVG morphing effect with anime.js, a lightweight JavaScript animation engine that getting popular these days. (source code at the end of this post) You might want to watch the basic tutorial video first if you are not familiar with anime.js.

Creating SVG Polygon

First we’ll need to create our SVG polygon. You can use Photoshop, Illustrator or any SVG drawing tools that you like. For me, I’m going to use an SVG Path Builder by Anthony Dugois.

anime.js path builder

Then create a new shape and copy the path code at the bottom.

anime.js svg morph tutorial 1

The current code is in path format so we need to convert it to points. Delete M at the start and Z at the end. Then replace L with comma.

M 87 472 L 87 91 L 267 80 L 501 78 L 489 304 L 500 450 L 293 457 Z //path

87 472,87 91,267 80,501 78,489 304,500 450,293 457 //points

Then on our HTML, create SVG and polygon tags. I’ll set to stroke/fill colors and paste the points code.

<svg id="demo-svg" width="600" height="600">
  <polygon stroke="none" fill="red" points="87 472,87 91,267 80,501 78,489 304,500 450,293 457"></polygon>
</svg>

And here is our shape

Now we’re going to create a second shape to morph to. The only requirement is all shapes in the animation need to have the same number of points so you can’t add a new one.

anime.js svg morphing tutorial 2

SVG Morph Effect

Let’s work on the animation. First create anime object and target the polygon element. We’ll use points property to morph the shape. We’ll use the points from both shapes as value objects. Then add the rest of the animation properties.

anime({
  targets: '#demo-svg polygon',
  points: [
    {value: '87 472,87 91,267 80,501 78,489 304,500 450,293 457'},
    {value: '126 263,281 317,475 132,405 417,530 535,29 490,202 365'}
  ],
  easing:'easeOutQuad',
  duration: 2500,
  loop:true,
  direction:'alternate'
});

You can watch the live demo in the video (I also covered about SVG line drawing and motion path) Or you can download and try the source code below.

Source Code (Motion Path/ Morphing/ Line Drawing) – Download

Written By

Leave a Reply

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

error: