Blueprint by Tiny
Return to Tiny.cloud
Return to Tiny.cloudTry TinyMCE for Free
Search by

A how-to guide to SVG animation

Juan Calou

August 29th, 2022

Written by

Juan Calou

Category

Developer Insights

We live in a technology ecosystem brimming with diverse devices. Front-end engineers are aware of the challenges this brings. When you have different and diverse screen sizes and aspect ratios, or resolutions and color settings, the hardest thing to achieve can be getting a consistent, content experience across.

One solution for consistency is making use of images called Scalable Vector Graphics (SVGs). Images with the .svg file format bring with them advantages despite their limitations such as creating a visually interesting look for websites while not adding to the load time burden.

This article explores SVG images, and how they work well for animation solutions that work consistently across different browsers and devices.

What is an SVG?

It’s a format for images. It’s based on XML, which works a lot like HTML. The SVG format defines diverse elements that essentially add up to familiar geometric shapes. These shapes can be combined into two-dimensional graphics that tend to work well in web applications.

The SVG specification is an open standard developed by the World Wide Web Consortium (W3C) in 1999. As a result of this standard being developed in 1999, SVG rendering support has been available consistently across browsers for a while now. The format is a common part of web development. All the more reason to understand how they work.

What are SVG animations?

Since SVG images are XML documents under the hood, web browser’s DOM node-based APIs can interact with the images. Through the node-based APIs, a web browser can change the position of the SVG content on the page. When you line up a series of SVGs showing the same object in different positions, bingo… you have the basis of animation with SVGs. Talk about bringing pictures to life!

With the right APIs and configuration, you can even turn SVGs into a small but significant animated production.

SVG path animation

The key to creating animated elements with an SVG is the overpowered <path> element. Path elements can have different attributes. One of these is a stroke, which plays a role in SVG path animation.

The path elements represent basic shapes. Using the path, it’s possible to create almost any advanced 2D shape you can imagine. You can learn a lot more through tutorials about the path element.

How the path element works

The path element works a lot like the Logo programming language only modernized (Logo was around in 1967 after all). The element takes a sequence of drawing commands through the “d” attribute in the following example:

 <!-- A right-angled triangle -->
<path d="M10 10 L75 10 L75 75 Z" />

The path element works almost like a connect-the-dots drawing. Each command tells you where to send your pen next to complete the shape:

  1. The pen is being instructed to move to position M10 10)
  2. Draw a line to (75, 10) (L75 10)
  3. Draw a line to (75, 75) (L75 75)
  4. Close the path by returning to the starting point (Z).

Using other drawing commands, you can create complex shapes:

  1. Arcs (A)
  2. Quadratic bezier curves (Q)
  3. Cubic bezier curves (C)

SVG animation techniques

1. Stroke dasharray animation css

The stroke-dasharray attribute controls the pattern of dashes and gaps used to stroke the path. If you wanted to draw your lines as a group of dashes and gaps instead of one continuous stroke of ink, this is the attribute you would use.

With SVG images being a part of the web browser’s DOM and stroke-dasharray being a presentation element, the attribute can also be set using CSS.

2. Stroke dashoffset animation css

The dashoffset property specifies how far into the dash pattern to start the dash. Similar to the dasharray CSS property, the stroke-dashoffset attribute can also be controlled using CSS.

SVG animation with css

For our first technique, you’re going to take advantage of the dasharray and dashoffset CSS properties together to animate SVG paths. They give the viewer the illusion that the paths are being drawn gradually.

Take this quadratic bezier curve, for example: 

<path fill="transparent" stroke="#000000" stroke-width="5" d="M10 80 Q 77.5 10, 145 80 T 280 80" class="path"></path>

To animate this path as if it’s being drawn gradually and smoothly on the screen, you have to set the dash (and gap) lengths, using the stroke-dasharray attribute, equal to the path length. This is so that the length of each dash and gap in the dashed curve is equal to the length of the entire path.

Next, set the dash offset, using the stroke-dashoffset attribute, to 0. This makes the path appear on screen as a solid curve (you’re essentially looking at the first dash, and you already made each dash span the entire length of the curve). By setting the dash offset equal to the length of the curve, you end up with an invisible curve (you’re now looking at the curve being rendered as an entire gap – the part that immediately follows a dash).

Now by animating the stroke-dashoffset property, you can make the curve appear on screen gradually.

As you can see, the curve is always there. You’re only changing the dash offset to make the dashed part appear bit by bit.

You can take this a step further by using the same principle but with more paths:

Here you have one black curve that is fixed, a red one that is moving along the path, and another black one following the red one but 40px behind.

Stroke-dasharray and stroke-dashoffset are two very powerful attributes that can be used to apply a plethora of animations and effects to your SVG paths. You can try this handy tool that you can use to experiment with the two attributes.

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.
  • offset-distance: The offset-distance CSS property specifies a position along an offset-path.

This element can be anything, a div, an image, text, whatever. The idea is that with the use of offset-path and offset-distance you can give the element a path to follow and animate the distance and the element will move through the path.

SVG animations using JavaScript

If all of these are not fancy enough already, you can always resort to JavaScript.

Animating SVG elements with JavaScript can be much like animating DOM elements. However, with JavaScript, you can achieve the animation techniques above, but more easily.

Previously, you had to hardcode the path lengths in your CSS. With the help of the JavaScript function path.getTotalLength() it’s possible to calculate the length of the path on-the-fly and use it as needed. You can learn more about it here.

Besides, a number of libraries are already at your disposal that can make SVG animations a lot easier than it already is.

Snap.svg not only makes it easy to draw SVG images using JavaScript, it makes animating them as simple as calling .animate({}).

Another library, anime.js, lets you make a div element follow an SVG path with just a few lines of code.

If you’re looking for a library that does more on its own but makes the results still look stunning, then Vivus is what you’re looking for. It takes a different, more configuration-driven approach to SVG path animation. With this library, you just have to add an ID to the SVG element you want to draw and define a Vivus object with that ID. Vivus takes care of the rest.

How to use svg animation with HTML

If you need to complete svg animation without css or JavaScript, you can use a set of HTML elements to get some animation going.

The following HTML tags are fundamental for SVG animation: 

  • <svg> – a container element. This tag marks the beginning of a scalable vector graphic
  • <rect> – draws a rectangle element, defining positing, length, and height
  • <animate> – the tag provides a way to change an element into animation
  • <ellipse> – draws an ellipse element based on a center coordinate
  • <line> – draw a line connecting two points
  • <circle> – draw a circle based on a center coordinate and radius

And there are several other HTML tags for SVG animation. In particular, the <g> element can group SVG related elements together. A small but useful tag.

As an example, if you wanted to animate a basic shape with HTML, you could run the following example adapted from the MDN documentation

<svg viewBox="0 0 10 10" xmlns="http://www.w3.org/2000/svg">
    <ellipse width="10" height="10">
      <animate attributeName="rx" values="0;5;0" dur="2s"
repeatCount="indefinite" />
    </ellipse>
  </svg>

This steadily animates the given space with just the HTML tags and attributes.

SVG animation on hover

When it comes to animation for hovering over a shape, which is an element of responsive design, it’s easier to introduce the :hover: pseudo-class. You can set up SVG animations to have this hover effect on the page:

  <svg id="ex1" version="1.1" xmlns="http://www.w3.org/2000/svg">
    <style>
      #ex1 circle {
        fill: blue;
      }
      #ex1 circle:hover {
        fill: white;
      }
    </style>
    <circle cx="75" cy="75" r="75" />
  </svg>

  .yourCSSClass:hover {
  animation-play-state: running;
}

This CSS style changes the color of the circle when the mouse hovers over it, shifting it from blue to white.

Beginning and pausing SVG animations on hover

You can control whether animations begin or pause using a CSS property known as animation-play-state. The property has ‘paused’ and ‘running’ states that you can configure in the animation CSS.

When configuring your CSS, you can set up a class for an element, and then add the hover pseudo-class to it. Next, configure the animation play state:

.yourCSSClass:hover {
  animation-play-state: running;
}

This changes the animation to begin running when hovering over the element. When you wish to change the element behavior, where the animation pauses when hovering over it, change the animation-play-state to “paused”.

SVG animation on scroll

Using JavaScript, you can configure animation events to change and SVG with an event listener when the scroll event fires. Include the onscroll event, and also include the requestAnimationFrame() function. Scroll events can fire very fast, so to keep the load on the browser low, use the function to control how often the animation changes, moderated by the current time passing.

You could combine an event listener with the scroll event, and the SVGAnimationElements ‘beginEvent’ and ‘endEvent’ as needed.

Further reading

Below are a list of resources that you may find useful when dealing with SVG images and animating them:

  • To go more in depth with SVG animation, you can read this short article on the three ways to animate SVG images and watch the video screencast by CSS Tricks.
  • One thing this article didn’t cover is animating SVG images with Synchronized Multimedia Integration Language (SMIL). While using CSV for SVG gives you the advantage of working with something you are already familiar with, SMIL takes things to the next level.
  • With SMIL, you can implement advanced animation effects such as shape morphing using SVG alone. A short, yet effective guide to using SMIL for such effects is available here. Although, support for SMIL is a bit edgy at this moment (no pun intended).

This post would not be possible without the work of Juan Calou on the Toptal Engineering Blog.

GuestCSSJavascriptImages
byJuan Calou

Juan is a systems engineer who graduated from college in 2005. He's spent his whole career working in the computing world after first entering the web industry in 2006. He is always learning new stuff and working on different kinds of projects. He is an eager learner with great attention to detail.

Related Articles

  • Developer Insights

    HTML editor with preview: single screen or side-by-side editing?

    by Joe Robinson in Developer Insights
Subscribe for the latest insights served straight to your inbox every month.

Deploy TinyMCE in just 6 lines of code

Built to scale. Developed in open source. Designed to innovate.

Begin with your FREE API Key
Tiny Editor
Tiny logo
Privacy Policy - Terms of Use© 2022 Tiny Technologies Inc.TinyMCE® and Tiny® are registered trademarks of Tiny Technologies, Inc.

Products

  • TinyMCE
  • Tiny Drive
  • Customer Stories
  • Pricing