Animating properties of injected SVG elements with TweenMax

Hello all, this post was somewhat inspired by the work of PJ.Onori and his blog post about SVG injecting and manipulation through javascript and css.

You can read more about his findings here: svg-css-injection

So after injecting the SVG inside the DOM I thought of why shouldn’t we try and animate it (no one likes static images right?), some simple things like change color gracefully, scale it or even programmatically create a simple animation of it.

I will show here how we can use simple tools like JQuery and TweenMax from Greensock and animate a simple SVG graphic.

View a DEMO here: AnimateSVG DEMO

Note: The SVG graphic I used is from PJ Onori and his Iconic font icon set (which is open source!).

Creating the DOM

So let’s begin by creating some nice placeholders for our SVG graphic.

<div id="mainBox">
    <div id="canvasBox">

    </div>

    <div id="toolbox">
        <div class="colorBtn">
            Animate Color
        </div>

        <div class="animateSignal" id="lowSignal">
            Low Signal
        </div>

        <div class="animateSignal" id="strongSignal">
            Strong Signal
        </div>
    </div>
</div>

Now we have a placeholder for our graphic “canvasBox” and some DIV elements that will host some buttons.

Injecting the SVG

As you may already know we can downright write code for SVG graphics that gets rendered right on the HTML, however its quite common that for simple graphics we use code that was either exported from some illustration program like Adobe Illustrator, its much easier that way especially if we are not designers or we have limited time to find scalable vector graphics for our projects.
An SVG graphic code can look like the following:

<svg xmlns="http://www.w3.org/2000/svg" version="1.1">
  <circle cx="100" cy="50" r="40" stroke="black"
  stroke-width="2" fill="red" />
</svg>

which is a red circle with a black outline.

We are goind to use something more elaborate, like signal showing bars (like mobile phones have to indicate signal strength).

<svg id="barsSVG" style="enable-background:new 0 0 28 32" xmlns="http://www.w3.org/2000/svg" xml:space="preserve" height="32px" width="28px" version="1.1" y="0px" x="0px" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 28 32">
 <g fill="#010101">
    <rect x="24" height="32" width="4"/>
    <rect height="24" width="4" y="8" x="16"/>
    <rect height="16" width="4" y="16" x="8"/>
    <rect y="24" width="4" height="8"/>
 </g>
</svg>

For ease of use we assign this as a string in a variable:

var baseSVG = '<svg id="barsSVG" style="enable-background:new 0 0 28 32" xmlns="http://www.w3.org/2000/svg" xml:space="preserve" height="32px" width="28px" version="1.1" y="0px" x="0px" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 28 32"><g fill="#010101"><rect x="24" height="32" width="4"/><rect height="24" width="4" y="8" x="16"/><rect height="16" width="4" y="16" x="8"/><rect y="24" width="4" height="8"/></g></svg>';

Note: It is preferable and advisable to minify the text (remove tabs and spaces) before you assign it to a variable.

Now we can inject it to our placeholder as soon as the DOM has finished initialization.

$(document).ready(function($){
 $("#canvasBox").append(baseSVG);
});

Next we will enhance the ready function.

Manipulating SVG Properties

Now that we have our static SVG its time to spice it up with some animations. Let’s see how, first of all let us change its color with a smooth way:

We assign a click event listener to one of the buttons:

 $(".colorBtn").live('click',function(){
        var randomColor = get_random_color();
        var svgElement = $("#barsSVG");
        TweenMax.to(svgElement.children(),0.5,{css:{'fill':randomColor}});
    });

// we also add a function to help us create some random color each time

function get_random_color() {
    var letters = '0123456789ABCDEF'.split('');
    var color = '#';
    for (var i = 0; i < 6; i++ ) {
        color += letters[Math.round(Math.random() * 15)];
    }
    return color;
}

Now when we click the button the color of each of the SVG’s children elements will change color (fill for SVG graphics) during 0.5 seconds.

Moving on to something more complex we are going to create a simple animation from our static SVG to indicate that the signal is dropping or raising.

$("#lowSignal").live("click",function(){
        var numChildren = $("#barsSVG").children('g').children().length;
        var svgElements = $("#barsSVG").children('g').children();
        var delay = 0.5;
        for(var i=0;i<numChildren-1;i++){
            TweenMax.to(svgElements[i],0.5,{css:{'opacity':0},delay:delay});
            delay += 0.3;
        }
    });

What we do here is to create a table of each of the SVG chilren elements and animate their opacity with a steady pace but leaving one bar to indicate low signal.

And following the reverse procedure, we show the stregthening of the signal

$("#strongSignal").live('click',function(){
        var numChildren = $("#barsSVG").children('g').children().length;
        var svgElements = $("#barsSVG").children('g').children();
        var delay = 0.5;
        for(var i=numChildren;i>0;i--){
            TweenMax.to(svgElements[i-1],0.5,{css:{'opacity':1},delay:delay});
            delay += 0.3;
        }
    });

Note: These event listeners are part of the document ready function that we declared above.

As you see then its is fairly easy to create simple animations and give those high quality graphics a bit more power.

View a DEMO here: AnimateSVG DEMO

Enjoy!

facebooktwittergoogle_pluspinterestlinkedin
linkedin
Tagged , , , , . Bookmark the permalink.

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>