Animated drawing with svg and jQuery

Animated drawing with svg and jQuery

Hi all,

I recently discovered the great possibilities of using svgs (scalable vector graphics) and came across this interesting example on Codepen :

http://codepen.io/ghepting/pen/xnezB

This page gives a clear explanation of the basic idea :

http://css-tricks.com/svg-line-animation-works/

Animated handwriting, quite awesome I thought. But then I realised how poorly CSS transitions and animations are supported (by IE mostly). But as I'm normally using jQuery all the time, I should have turned to it here from the start as well. With HTML5 alone, getting it to work is buggy and unreliable while on this platform it runs solid from IE9 on...



Here's the code - the #writing div simply is the one in which the svg and it's paths are :


  1. function textInit() {

        $('#writing').each(function() {

        var length, path, paths, iter;
        paths = $('path', this);

        for (iter = 0; iter < paths.length; iter++) {
        path = paths[iter];
        length = path.getTotalLength();
        $(path).attr('data-length', length)
  2.               .css({'stroke-dashoffset': length, 'stroke-dasharray': length});
        }
        });
    }

    var count = 0;

    function writeText() {

        $('#writing').each(function() {

        var length, path, paths;
        paths = $('path', this);
        path = paths[count];
        length = $(path).attr('data-length');

        $(path).animate({'stroke-dashoffset': 0}, {

            duration: 2*length,
            easing: 'linear',
            complete: function() {
            if (count == paths.length) count = 0;
            else {count++; writeText()}
            }
        });
        });
    }


Initiate the div with textInit(), giving the svg paths the appropriate attributes that are needed later and then animate the writing with the writeText() function. Svg paths can be created (free) with Inkscape.

Never will I underestimate jQuery again. Or doubt it at all! What an excellent lib.

And it offers a lot more control over the process too.

Not only text but any vector can be drawn of course (I'm just using it that way).



    • Topic Participants

    • edo