Chanc.ee

24 Apr 2020

Animating SVGs: Strokes

This post will document a method to produce a self contained animated SVG. An illustration should be robust, like a JPEG or a PNG - and in this instance if we imagine an SVG that illustrates a mechanical process - we want that illustration to stand alone and not be dependent on any external files. Animated icons or illustrations in a RSS feed. Sign me up fam 🔥

An animated Bohr model of Helium An animation detailing a Bohr model of Helium with a pink proton and blue electrons.

Our SVG symbol

I'm digging svg symbols at the minute, so let's use one of those. Here we have a symbol called hydrogen which contains a three circles: one for our proton, another to represent the electrons orbit and one to represent the electron. At this point we can inject this SVG into some html and the electron will orbit the proton.

<svg xmlns="http://www.w3.org/2000/svg" style="display: none;" xml:space="preserve">
    <symbol id="hydrogen" viewBox="0 0 200 200">
    <circle id="proton" stroke="none" fill="rgb(252, 75, 133)" cx="100" cy="100" r="29" />
    <circle id="orbit" stroke="rgb(0, 183, 255)" stroke-width="1" stroke-miterlimit="10" fill="none" cx="100" cy="100" r="65" />
    <circle id="electron" stroke="rgb(0, 183, 255)" stroke-width="20" stroke-linecap="round" stroke-miterlimit="10" stroke-dasharray="0,401" stroke-dashoffset="0" fill="none" cx="100" cy="100" r="65">
	<animate attributeName="stroke-dashoffset" from="0" to="401" dur="4s" repeatCount="indefinite" />
   </circle>
</symbol>
</svg>

How

You can attach an animate tag to any element in an svg. Here, we've targeted the dash-offset and used it to push a single dash around a circle to render our animation. Note the circle element with the animate tag has a closing </circle> rather than closing inline like: .../>.

<animate attributeName="stroke-dashoffset" from="0" to="401" dur="4s" repeatCount="indefinite" />

Viewboxes

Make sure you declare a viewbox - this will define the aspect ratio your illustration will render at. This could be important in the case of a mechanical diagram or less so if you are depicting something like a line chart. There's further reading on the specification for outlying scenarios like making an svg only scale in the x-axis.

This post has not been webmention'd yet.

Chancee is a designer who codes from London Town.

They have worked for the likes of Nike, Vodafone, Sky, Disney and Pearsons. Won awards from Promax, BAFTAs, the Appys and The Drum. Spoken at The Waldorf and Southampton University - despite swearing like a sailor. Available for hire to draw pretty curves and code clever things.