Animate Anything Along an SVG Path | Codrops (2023)

Animate Anything Along an SVG Path | Codrops (1)

From our sponsor: Animate Anything Along an SVG Path | Codrops (2)Animate Anything Along an SVG Path | Codrops (3)Animate Anything Along an SVG Path | Codrops (4)Get personalized content recommendations to make your emails more engaging. Sign up for Mailchimp today.

SVG is a very neat format to display any illustration, icon or logo on a website. Furthermore, they can be animated in CSS or JavaScript to make them more attractive. But SVG can also be used for their data only, without the visual! Let me explain…

An SVG is a vector image format, which means it is not made of coloured pixels, but math functions that, once interpreted, can be rendered on screen. Since the browser must convert the file from functions to actual pixels, it also let us access a wide variety of methods to either manipulate, or retrieve data from the math.

In today’s article, we will explore the functiongetPointAtLength()and see how we can use the data of anSVG pathfor creative use cases such as the demo below.

See the Pen Random dots along path – CodePen Challenge by Louis Hoebregts (@Mamboleoo) on CodePen.

⚠️ If you are not familiar with SVG,this CSS-Tricks articleis a good start!

The method getPointAtLength()

If we take a look at the MDN documentation page about the method it says:
The SVGGeometryElement.getPointAtLength() method returns the point at a given distance along the path.

(Video) SVG Tutorial - Draw Any Path Animation

The method will give us the coordinates of a point that is precisely along the path at a specific distance that we send as a parameter.

For examplepath.getPointAtLength(10)will return an SVGPoint (an object) with x & y coordinates.

Animate Anything Along an SVG Path | Codrops (5)

Since we need to give the distance of our point, it means we will most likely need to know how long is our path. Luckily, the SVG API has a methodgetTotalLength()available to anySVGGeometryElementthat returns the total length of our element!

⚠️ TheSVGGeometryElementvariable refers to all SVG tags that are created from a geometry (path, rect, circle,…) so this does not include image, filter, clip-path,… tags.

Let’s see how we can then use this function to animate a circle along a given path using the GreenSock library.

To do so, we need a JavaScript object that will contain the animated values(as gsap cannot animate number variables directly)and set a propertydistanceto zero.
We then create a tween that will update thedistancevalue from 0 to the total length of our path.
Finally on each frame, we retrieve a point along the path based on the animated distance value, and we update thecxandcyattributes of our circle to make it move ✨

// Create an object that gsap can animateconst val = { distance: 0 };// Create a, { // Animate from distance 0 to the total distance distance: path.getTotalLength(), // Function call on each frame of the animation onUpdate: () => { // Query a point at the new distance value const point = path.getPointAtLength(val.distance); // Update the circle coordinates circle.setAttribute('cx', point.x); circle.setAttribute('cy', point.y); }});

See the Pen Animate single element along path by Louis Hoebregts (@Mamboleoo) on CodePen.

⚠️ If the effect you want to achieve is just animating one element along an SVG path such as in the demo above, you could check theMotionPathPlugin by GreenSock. It will let you animate easily any DOM element from a path you provide. (plus it’s free!)

(Video) Animate Along SVG Path using GSAP MotionPathPlugin

Using the points coordinates for particles

I love particles, it’s no breaking news. Which is why, when I learn a new technique I always try to implement something with them!
Let’s see how instead of a single circle moving along a path, we could make many more circles exploding like a bomb fuse 💣

The overall logic of this animation is exactly the same as before, except that on each frame we will create a new circle element and animate it. As you can see, the setup is very similar.

const svg = document.querySelector('svg');const fuse = svg.querySelector('.fuse');const val = { distance: 0 };, { distance: fuse.getTotalLength(), repeat: -1, duration: 5, onUpdate: () => { // Query a point at the new distance value const point = fuse.getPointAtLength(val.distance); // Create a new particle createParticle(point); }});

ThecreateParticlefunction will be called on each frame to make a new particle pop and fade out. Here are the steps of the animation:

  1. Create a new circle element and append it to the SVG
  2. Set the coordinates from the point we calculated withgetPointAtLength
  3. Define a random radius and color for each
  4. Animate that particlecx&cyattributes to a random position
  5. Once the animation is complete, remove the particle from the DOM
function createParticle (point) { // Create a new circle element const circle = document.createElementNS('', 'circle'); // Prepend the element to the SVG svg.prepend(circle); // Set the coordinates of that circle circle.setAttribute('cx', point.x); circle.setAttribute('cy', point.y); // Define a random radius for each circle circle.setAttribute('r', (Math.random() * 2) + 0.2); // Define a random color circle.setAttribute('fill', gsap.utils.random(['#ff0000', '#ff5a00', '#ff9a00', '#ffce00', '#ffe808'])); // Animate the circle, { // Random cx based on its current position cx: '+=random(-20,20)', // Random cy based on its current position cy: '+=random(-20,20)', // Fade out opacity: 0, // Random duration for each circle duration: 'random(1, 2)', // Prevent gsap from rounding the cx & cy values autoRound: false, // Once the animation is complete onComplete: () => { // Remove the SVG element from its parent svg.removeChild(circle); } });}

See the Pen Bomb fuse particles by Louis Hoebregts (@Mamboleoo) on CodePen.

⚠️ To make the animation prettier I’m also animating thestroke-dashoffsetof the fuse to make it more realistic. You can checkthis articlefor more details on such animation.

Using the coordinates in WebGL

So far we have only animated SVG elements next to the path. But sometimes all we need are the raw coordinates from the path, but not the path itself. For example, if we want to animate particles in a 2D Canvas or in WebGL like in the animation below.

See the Pen Make it POP! by Louis Hoebregts (@Mamboleoo) on CodePen.

⚠️ The following chapter expects you to know how to setup and run athree.jsscene.

(Video) Awesome Scrolling SVG Line Drawing - How they did it!

Here are the key concepts of this animation:

  1. Get the path and its total length
  2. Loop along the path until you reach its length
  3. Get the point that exists on the index distance
  4. On each iteration, create a Vector3 at the point’s coordinates
  5. Push the vector into an array of vertices
  6. Create a geometry from the vertices
  7. Create a Points mesh and add it into your scene
// Get the Path in the DOMconst path = document.querySelector("path");// Store the total length of the pathconst length = path.getTotalLength();// Empty array to store all verticesconst vertices = [];// Loop along the pathfor (let i = 0; i < length; i += 0.2) { // Get the coordinates of a point based on the index value const point = path.getPointAtLength(i); // Create a new vector at the coordinates const vector = new THREE.Vector3(point.x, -point.y, 0); // Randomize a little bit the point to make the heart fluffier vector.x += (Math.random() - 0.5) * 30; vector.y += (Math.random() - 0.5) * 30; vector.z += (Math.random() - 0.5) * 70; // Push the vector into the array vertices.push(vector);}// Create a new geometry from the verticesconst geometry = new THREE.BufferGeometry().setFromPoints(vertices);// Define a pink materialconst material = new THREE.PointsMaterial( { color: 0xee5282, blending: THREE.AdditiveBlending, size: 3 } );// Create a Points mesh based on the geometry and materialconst particles = new THREE.Points(geometry, material);// Offset the particles in the scene based on the viewbox valuesparticles.position.x -= 600 / 2;particles.position.y += 552 / 2;// Add the particles in to the scenescene.add(particles);

See the Pen Untitled by Louis Hoebregts (@Mamboleoo) on CodePen.

Creating a heart of particles is fun, but animating those particles is even FUNNIER 🥳

First we setup a global timeline so that all tweens will be grouped together and we’ll be able to repeat all of them once the last animation is complete.

// Create a global gsap timeline that contains all tweensconst tl = gsap.timeline({ repeat: -1, yoyo: true});

While creating the vector, we attach a gsap tween on it so that it animates from the center of the heart. We can calculate the x & y coordinates for the start based on the SVG viewBox attributesviewBox="0 0 600 552".
Sinceyaxis are in the other direction in SVG, we apply a negative value. (yis going up in WebGL, while in CSS & SVG it’s going down).

Each vector’s animation will have a delay that is calculated from its own distance along the path so that will create a nice flow of particles going round.

for (let i = 0; i < length; i += 0.1) { [...] // Create a tween for that vector tl.from(vector, { x: 600 / 2, // Center X of the heart y: -552 / 2, // Center Y of the heart z: 0, // Center of the scene ease: "power2.inOut", duration: "random(2, 5)" // Random duration }, i * 0.002 // Delay calculated from the distance along the path );}

Finally, we need to update the geometry of the Points mesh on each frame as the Vector3 objects are being animated but the geometry is not aware of that.

function render() { requestAnimationFrame(render); // Update the geometry from the animated vertices geometry.setFromPoints(vertices);}

And voilà 💖

(Video) Make Awesome SVG Animations with CSS // 7 Useful Techniques

See the Pen Create word from SVG Path – WebGL by Louis Hoebregts (@Mamboleoo) on CodePen.

What’s next?

You tell me! Now that you can extract the coordinates of points along an SVG path, try to apply those data anywhere else 🚀
What about animating lines instead of particles? Or create a new path based on random points that you pick along another one?

Explore this technique and share your results with me on Twitter, I can’t wait to see what you’ll come up with 💙

See you another time,

9 Awesome WordPress Plugins to Use in 2022

Inspirational Websites Roundup #33

(Video) GreenSock Scroll-Driven SVG Path Follower


Can you animate a path in SVG? ›

Animating objects along SVG paths

With SVG and CSS, another cool thing you can do is animate objects or elements following a path. There are 2 SVG attributes you're going to use for the animation: offset-path: The offset-path CSS property specifies the offset path where the element gets positioned.

How to add animation to SVG path? ›

Animating an SVG path with CSS
  1. The first part was to create an SVG line, and I used sketch to draw a triangle-looking element. ...
  2. Now we can move to animate it, and since I'm only using one SVG, I added the code to the main SVG element. ...
  3. The dash array refers to the width of the dash and the offset to the starting point.
Dec 9, 2022

Why doesn t my SVG animation work? ›

One of the most common reasons why the SVG animation doesn't work is the use of <img> tags to add the SVG. The SVG might be visible on the website, but the animation will not start. You can easily fix this by replacing all <img> tags with an <object> tag.

Is SVG good for Animation? ›

SVG (Scalable Vector Graphics) is a vector image format based on XML. It is infinitely scalable and it has support for interactivity and animation. SVG is ideal for logos, icons, diagrams, animations, and other web illustrations, because it tends to have smaller file sizes than other formats.

How do I make SVG path clickable? ›

The simplest way to make a portion of an SVG clickable is to add an SVG hyperlink element to the markup. This is as easy as wrapping the target with an <a> tag, just as you would a nested html element. Your <a> tag can surround a simple shape or more complex paths. It can surround a group of SVG elements or just one.

How to add animation in SVG image? ›

Add animated SVG to your website
  1. a) Using an <img> tag. For example <img src="sample. svg" /> . ...
  2. b) Using an <object> tag. If you've made an interactive SVG, you should use the <object> tag instead of <img> ...
  3. c) Using inline SVG in HTML5. This means that you will simply place the SVG code inside HTML:
Jan 27, 2020

Is it possible to draw any path in SVG? ›

YES!!!! Because of the complexity involved in drawing paths it is highly recommended to use an SVG editor to create complex graphics.

How to make SVG images responsive? ›

  1. Set up your tools correctly. ...
  2. Remove height and width attributes. ...
  3. Optimise and minify SVG output. ...
  4. Modify code for IE. ...
  5. Consider SVG for hero text. ...
  6. Leave width and height in place for progressive icons. ...
  7. Use vector-effects to keep hairlines thin. ...
  8. Remember bitmaps.
Mar 22, 2021

What is the difference between animated GIF and animated SVG? ›

GIF images are generally bigger in size than SVG images are with animations added to them. This negatively affects the overall page size, load times and performance.

How do I make an editable SVG? ›

How to make SVG files
  1. Launch Canva. Open Canva on your chosen web browser or the app. ...
  2. Upload your image. Upload your desired image from your device and drag and drop it onto the layout. ...
  3. Edit your SVG image. Select your image to make simple adjustments. ...
  4. Add final touches. ...
  5. Download in SVG format.

How do I animate my SVG logo? ›

How to animate a logo with SVGator
  1. Create. Start a new project by importing your static logo or creating it from scratch in the SVG editor.
  2. Animate. Choose the desired animator and set up keyframes on your timeline, then set easing and speed. ...
  3. Export.

How do you manipulate SVG? ›

To edit an SVG image in Office for Android, tap to select the SVG you want to edit and the Graphics tab should appear on the ribbon. Styles - These are a set of predefined styles you can add to quickly change the look of your SVG file.

What is the downside to SVG? ›

Disadvantages of Using SVG Images

Because SVG is vector-based, it does not work well for images with lots of fine details and textures like photographs. SVG is best suited for logos, icons, and other “flat” graphics that use simpler colors and shapes.

What are the risks of SVG? ›

For instance, imagine a user uploads an SVG file with a script embedded in it that steals their session cookie when viewed by other users on the same site. If the web application fails to sanitize the uploaded SVG and renders it as-is, the script will execute and the attacker can access the victim's session.

What is meant by path animation? ›

Motion paths let you animate objects moving along curves and complex shapes. Similarly to lines drawn with the pen tool, you define motion paths by setting anchor points which are then connected by straight or curved lines.

What is path animation with example? ›

Path Animation Types
Property typeCorresponding path animation classExample
DoubleDoubleAnimationUsingPathAnimate an Object Along a Path (Double Animation)
MatrixMatrixAnimationUsingPathAnimate an Object Along a Path (Matrix Animation)
PointPointAnimationUsingPathAnimate an Object Along a Path (Point Animation)
Feb 6, 2023

How do you make an object follow a path in animate? ›

Select the object you want to animate on the path, and then Shift-select the curve. Note: You can Shift-select multiple objects and attach them to the same path curve. Remember to select the path curve last. In the Animation menu set, select Constrain > Motion Paths > Attach to Motion Path > .

How do I embed SVG elements directly? ›

3. How to use inline SVG images. SVG images can be written directly into the HTML document using the <svg> </svg> tag. To do this, open the SVG image in VS code or your preferred IDE, copy the code, and paste it inside the <body> element in your HTML document.

How do I write text in SVG path? ›

To create SVG text that follows a path you use a <textPath> element in combination with a path you define inside <defs> tags. To refer to the path you'll use an xlink:href attribute on the <textPath> . Note: SVG 2.0 is dropping the xlink: and will simply use href to refer to the path.

What is SVG animation? ›

Animation of Scalable Vector Graphics, an open XML-based standard vector graphics format is possible through various means: Scripting: ECMAScript is a primary means of creating animations and interactive user interfaces within SVG.

How do you add animations to design? ›

Place the object you want to animate in your document. In the Animation panel (Window > Interactive > Animation), choose a motion preset from the Preset menu. Specify motion preset options. To edit the motion path, use the Pen tool and Direct Selection tool.

How do I make an animated SVG from a GIF? ›

How to convert GIF to SVG
  1. Upload gif-file(s) Select files from Computer, Google Drive, Dropbox, URL or by dragging it on the page.
  2. Choose "to svg" Choose svg or any other format you need as a result (more than 200 formats supported)
  3. Download your svg.

What is the difference between path and polygon in SVG? ›

Polygon will automatically close the shape for you (by returning to the first point) after drawing at least three sides, and is composed of a series of connected straight lines, which means it does not scale well. Paths can use straight OR curved lines, and do not auto-close the shape for you.

How do paths work in SVG? ›

The <path> element is the most powerful element in the SVG library of basic shapes. It can be used to create lines, curves, arcs, and more. Paths create complex shapes by combining multiple straight lines or curved lines. Complex shapes composed only of straight lines can be created as <polyline> s.

Can you put an image inside an SVG? ›

The <image> SVG element includes images inside SVG documents. It can display raster image files or other SVG files. The only image formats SVG software must support are JPEG, PNG, and other SVG files.

What program do professionals use to animate? ›

Some of the best animation software in the market are Visme, Adobe Animate, Adobe Character Animator, Pencil2D, Biteable and Animaker.

What do designers use to animate? ›

Animation designers primarily rely on digital software to create their animations. While 2D designers may draft some designs on paper and then scan them in to be digitally manipulated, they'll execute the animation process exclusively on a computer.

What programming language is used for SVG? ›

SVG is an XML language, which means it has a very strict and somewhat verbose syntax. This can make it a little annoying to write, but on the other hand, it makes it possible to read and understand SVG documents even if you are not familiar with the syntax.

Is SVG sharper than PNG? ›

If you have detailed images, definitely stick with PNG. However, SVGs are better for responsive and retina-ready web design due to their scalability and lack of quality degradation. In addition, they support animation while PNG doesn't, and raster file types that support animation like GIF and APNG.

Do SVG files get blurry? ›

Generally, SVG files are not supposed to appear blurry as they are a vector file. Vector files essentially have unlimited resolution and scale to look good on a computer at any size.

What are the advantages of SVG over JPEG or GIF? ›

Unlike raster formats seen in JPG, GIF, and PNG, an SVG image remains crisp and clear at any resolution or size. That's because an SVG is drawn from mathematically declared shapes and curves, not pixels. SVG's can be animated, support transparency, and any combinations of colors or gradients.

Is Lottie better than SVG? ›

All the advantages of SVG are increased when working with Lottie files. The format is smaller and offers scalability. In addition, Lottie is much easier incorporate in web design and offers more customization options. Below are why Lottie animated icons are a much better option than SVG.

What are the 3 types of GIF? ›

For simplicity, we classify the different types of GIFs into 3 major categories: video-based, animation-based, and stickers. Video-based GIFs are the most traditional GIF that you're probably familiar with. They feature short clips of video content.

Are all SVG files editable? ›

Because SVG files are produced in a text-based markup language similar to HTML, they an be edited using a text editor. Note: If you don't know what you're doing, you could damage the file. It's best to use a vector editing program like Adobe Illustrator to edit SVG files.

Can SVG images be edited with any text editor? ›

SVG images can be created with any text editor, but it is often more convenient to create SVG images with a drawing program, like Inkscape.

How to edit SVG animation? ›

To edit SVG files within Adobe Illustrator and use the edited content within Animate, do the following:
  1. In Animate, export to SVG.
  2. Edit your artwork by opening the SVG file using Adobe Illustrator.
  3. Save the SVG file as an . ai file, and import within Animate.
Feb 15, 2022

Where can I animate my logo for free? ›

First, open Canva and go to “Animated Logos” for a library of professionally designed templates to draw inspiration from and customize. Second, choose from any professionally designed animated logo templates that are closest to the look and feel you're going for. All of these templates are fully customizable.

Can I edit an SVG file in Cricut? ›

It's really easy to Edit SVG Files for Printables in Cricut Design Space. You can do this with SVG Files in Cricut Access, or files that you upload to your design space dashboard. My favorite feature of the Cricut Machine is the ability to print and cut.

How to make SVG path responsive? ›

  1. Set up your tools correctly. ...
  2. Remove height and width attributes. ...
  3. Optimise and minify SVG output. ...
  4. Modify code for IE. ...
  5. Consider SVG for hero text. ...
  6. Leave width and height in place for progressive icons. ...
  7. Use vector-effects to keep hairlines thin. ...
  8. Remember bitmaps.
Mar 22, 2021

How to make a path in SVG? ›

Getting SVG path data for SVG Icon extension
  1. Open or create your shape in Adobe Illustrator.
  2. Make sure it is a compound path. When you select the shape Illustrator will tell you if it is a compound path. ...
  3. Object > Compound Path > Make. ...
  4. Copy to clipboard. ...
  5. Get the d="..." data. ...
  6. Paste into iconPath field. ...
  7. Flip it.
Mar 20, 2015

Can you animate SVG in Adobe? ›

Interchanging SVG files with Adobe Illustrator

Animate enables interchanging of content with Adobe Illustrator. This workflow is a replacement for the FXG Export feature that was dropped with Animate (13.0). You can export SVG files from within Animate, and import them within Adobe Illustrator.

What is SVG not suitable for? ›

Because SVG is vector-based, it does not work well for images with lots of fine details and textures like photographs. SVG is best suited for logos, icons, and other “flat” graphics that use simpler colors and shapes.

How do I make an entire SVG clickable? ›

The simplest way to make a portion of an SVG clickable is to add an SVG hyperlink element to the markup. This is as easy as wrapping the target with an <a> tag, just as you would a nested html element. Your <a> tag can surround a simple shape or more complex paths. It can surround a group of SVG elements or just one.

How to make SVG file interactive? ›

Interactivity: SVG maps can be made interactive through the use of JavaScript and CSS, allowing viewers to hover over or click on specific elements to see more detailed information.

How do you simplify SVG paths? ›

Method 1: Simplifying Object's Path
  1. Go to Object > Path > Simplify. Use the “Curve Precision” slider in order to manipulate the object and delete extra points.
  2. You can view how this has changed the object in Outline mode, by going to View > Outline.

What is clipping path in SVG? ›

SVGClipping MaskCSSHTML. Clipping and masking is a feature of SVG that has the ability to fully or partially hide portions of an object through the use of simple or complex shapes. Over the years many developers have taken these abilities and pushed them in various directions.

Which Adobe tool is best for SVG? ›

A helpful note: since Photoshop is a raster graphics editor, many people prefer to create and edit SVG files in Adobe Illustrator, a vector graphics editor.


1. CSS movement path. Pure CSS animation along svg path with offset-path / motion-path and keyframe.
(Dev Negant)
2. Motion Path Animation - Animate Any Object Along a Custom Path | SVGator
3. Try this Multi-Path SVG Scroll Animation Technique
4. Animate Any SVG icons with CSS Only | SVG Stroke Animation With Html CSS
(Online Tutorials)
5. SVG Explained in 100 Seconds
6. How to animate SVG, drawing, along path, masks. Animate websites like never before. Part 2
(WP Soul)


Top Articles
Latest Posts
Article information

Author: Melvina Ondricka

Last Updated: 26/07/2023

Views: 6082

Rating: 4.8 / 5 (68 voted)

Reviews: 83% of readers found this page helpful

Author information

Name: Melvina Ondricka

Birthday: 2000-12-23

Address: Suite 382 139 Shaniqua Locks, Paulaborough, UT 90498

Phone: +636383657021

Job: Dynamic Government Specialist

Hobby: Kite flying, Watching movies, Knitting, Model building, Reading, Wood carving, Paintball

Introduction: My name is Melvina Ondricka, I am a helpful, fancy, friendly, innocent, outstanding, courageous, thoughtful person who loves writing and wants to share my knowledge and understanding with you.