jay-svg

How to do SVG path animations

Introduction:

Scalable Vector Graphics (SVG) is an XML-based vector image format for two-dimensional graphics that has support for interactivity and animation.

With the imminent dominance of html5 , svg poses a unique advantage for creating unique interactive experiences.Unlike images , svg are responsive in themselves , can be animated , given classes and ids , can be dynamically created and edited.

A primer in SVG is explained at Blog post with the demo at SVG demo

Heres a demo of what we have made

Step 1 : Download Inkscape

Inkscape is an open-source vector graphics editor similar to Adobe Illustrator, Corel Draw, Freehand, or Xara X. What sets Inkscape apart is its use of Scalable Vector Graphics (SVG), an open XML-based W3C standard, as the native format.

Download

You will need Inkscape to create complex paths which will be used for the svg path animations.

screenshot of inkscape
inkscape

Step 2 : Draw the SVG

Draw the SVG drawing using tools of Inkscape Draw Lines and Bezier Curves.You can edit the curves to suit your needs.This might take some time to make the curves perfect.
Its important to make sure that there is only 1 path throughout the drawing with only one beginning and one end.

Step 3 : Javascript Code for animation


The code works this way , first we give the strokeDasharray property the maximum length of the the path .We also give this length to property strokeDashOffset
Also the path is given a transition of 3s with easing ease-in-out.
Then the property strokeDashOffset is set to 0 which triggers the easing animation.

function  docready () {
	var path = document.querySelector('svg path');
	var length = path.getTotalLength();

	path.style.transition = path.style.WebkitTransition = 'none';

	path.style.strokeDasharray = length + ' ' + length;
	path.style.strokeDashoffset = length ;

        path.getBoundingClientRect();

	path.style.transition = path.style.WebkitTransition = 'stroke-dashoffset 3s ease-in-out';

	// Below line triggers the Animation

	path.style.strokeDashoffset = '0';
}
window.onload = docready;

Source

Step 4 : html file

Copy the svg code generated to any .html file.
To the bottom before the ending body tag , add the above javascript code.
Save it and open the file in your favourite browser.
You can change the stroke-width:4px; to make the line thicker.

There is also a jQuery plugin for it called Lazy Line Painter for making this svg path animations simpler.

DEMO

The main inspiration for this article : http://jakearchibald.com/2013/animated-line-drawing-svg/

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>