How to get started with Snap.svg

Animating and transversing SVG files with Javascript is actually not such an easy task and plugins like Snap.svg make our lives much easier when it comes to animating our SVG files.

This library is one that aims to help Web Developers easily bring advanced SVG features to the Web, with it we can load, animate and even create SVG graphics right in the browser.

The creator of this plugin is also the creator or Raphael, also an SVG plugin. The main difference between these two resources is that Snap aims only at top level browsers not worrying much about backwards compatibility and that allows it to have much more advanced characteristics.

Getting started

In order to get started with Snap.svg we need to head over to their website and download the latest version. After we’ve downloaded the zip file we need to insert the Snap Javascript file into our HTML:

<script src=“js/snap.svg-min.js”></script>

After this is done we can start playing around with the plugin and we are going to start by creating our drawing surface , and this surface is where our SVG file will be placed:

var s = Snap(800,800);

In my case I created a new surface but we can also call the snap function to an already existing element like so:

var s = Snap(“#element”);

Both these ways are great, it all depends on your project and what you trying to accomplish with the plugin. Now that we have initialized the plugin it’s time to get our file in the HTML.

Inserting the SVG and animating it

To insert an external SVG file we need to call the load function and this function takes two parameters, the first one is the file we want to insert and the second is the callback function, this is the function that will run when the file is placed on the page. This means that this is the function where all our animation code will be placed.

Snap.load(“img/wdd.svg”, onSVGLoaded ) ;

The load function is this simple, it loads the file and then calls the function and in this function we need to append the file to our page :

function onSVGLoaded( svg ){
s.append( svg );
}

This is all we need to properly show the SVG on our page and have it ready for snap to mess around with.

Now, let’s move on to animate and transform this SVG file with Javascript. It’s worth mentioning that all this transforming and animating code will go before the append function but inside the onSVGLoaded function. First of all let’s try to change the color of the rectangle we have:

svg.select(“rect[fill=‘#AD6F6F’]").attr({fill: "#5D9170"});

As you can see from the line I got the svg and selected a rectangle that had that background and then changed the atribute of it to another color. You can do this with any attribute in the SVG file and the syntax it’s pretty self explanatory but this doesn’t animate the rectangle , it just changes its color.

Let’s try to animate the circle’s radius, first we need to get the circle and assign it to a variable:

var circle = svg.select(‘circle’);

After this is done we can call the animate function to that same variable and pass in the radius as a parameter:

circle.animate({r: 20}, 1000);

As you can see this function takes two parameters , the first one is the attributes ( key and value, in this case the key is radius and value one is 20 ) and then we have the duration which is how long the animation will last.

If you been following this long you can see that when you load up the page the circle does animate and shrinks down. From this you can see what you can do with this and we can even change the line when we change the color of the fill in the rectangle to have it animate like so:

svg.select(“rect[fill=‘#AD6F6F']").animate({fill: "#5D9170"},1000);

As you can see I changed attr to animate and also added the duration of the animation and it’s already working.

The last thing I want to do with this is to make this rectangle wider and place the text there and this means I have to animate the rectangle’s width and the text position. Firstly I want to make the rectangle bigger:

var rect = svg.select(‘rect’);

rect.animate( { width: 500 }, 1000 );

As you can see all I really did was animate the width to 500. The last thing we need is to move the text and for that we need to change the text’s x and y values:

var text = svg.select(‘text’);

text.animate({y: -200,x: 150}, 1000);

In this case I wanted to call two atributes so I separated them with commas and moved the text 200px up and 150px to the right.

Final Thoughts

SVG is a powerful format for the Web, it’s the only format that was designed specifically for the Web and it gives us abilities we don’t have with other image formats, just the fact that it can be copied in code and pasted to our HTML file gives us freedom we really never had with bitmap image files.

Hopefully you got into SVG and really understood the reason so many people are adopting it and are behind it.

Sara Vieira is a freelance Web Designer and Developer with a passion for HTML5/CSS3 and jQuery. You can follow her on twitter or check out her website.
More articles by Sara Vieira

robrogan

I’m always eager to use SVG image assets for web projects, but the common hesitation from developers is load time. For circles or other simple shapes it might be fine, but if you wanted to create some graphics in Illustrator, supposedly it’s still more efficient to export that as a PNG than an SVG. I’m curious about your thoughts on using complex graphics (objects with many vector points) – worth it?

Digital Workshop

IMO probably not worth it just for images but if you want to do any of the cleverness above you’ll need it.

We’ve gone very SVG heavy because of the flash-style effects we can do. There’s a slight overhead as you can see here http://goo.gl/KF3XEB but it’s worth it IMO.

When you originally set out to create a web design portfolio site for your business, it was most likely with the intent to use those work samples to impress prospective clients and generate more revenue. But a WordPress website is a powerful, revenue-generating tool in and of itself. You’ve invested a lot of time in creating it, so don’t let it go to waste. Your main source of revenue right now likely comes from the development projects you work on. As a web design professional, that may present some...

Evan Campbell recently wrote an informative article for employers at WebdesignerDepot titled "How to Find the Perfect Web Developer". In this article, we will share a few tips with you to help you ensure that you’re the kind of developer that Evan and his readers would want to hire. 1) Avoid becoming a “specialist” ... Trends on the Web move quickly. If you spend five years exclusively fine-tuning your knowledge of Drupal only to find that suddenly overnight everyone wants a Wordpress site (or...

In this tutorial we’re going to show you how to use the JavaScript Battery API to improve the user experience for people in desperate need of a charger. We’ll look at the Battery API itself, as well as some techniques for getting the most out of every drop of the most precious of resources! Some browsers lack support for the Battery API (you guessed it; Safari and IE), so a quick support check can go a long way in terms of debugging: if(navigator.getBattery){ // Battery API available. // Rest of code goes...

The web development industry is one that is always growing because of how we use the web. No longer do we expect the Internet to simply host a digital pamphlet for a business. The expectations nowadays are for a site to be rich with content, provide the means for visitors to interact and be dynamic in every interaction. With the demand at an all time high, freelance web developers may think that there is little they could do to harm their career. Unfortunately, there are many ways that people in this industry...

Usability testing is sometimes one of those things that developers conveniently ‘forget’ about. Why? Well do a search for it. Usability testing, as it is generally practiced, costs money. There are interviews to perform, a variety of tests to create for each and every project, services to pay for… and what if your client’s in another country? Or what if they’re a small business with a small budget, or a brand-new startup? What if the only reason you learned web development in the first...

Social media is an effective way of driving more traffic to a website and reaching a new audience for published content. If you or your clients use WordPress, you probably know there is a myriad of plugins that allow anyone to quickly share every published article across a variety of social media networks. But, sharing is not the only way to integrate social media into WordPress. In fact, there are a few other ways of making a website more social and helping your clients get more eyes on their content. 1....

What you see may be what you get, but it's not necessarily what everyone else gets. I was reminded of this when I bought a gaming monitor. I'd originally intended to get a 4K monitor of some kind, but I decided to go for speed over size. The one I did get can render my games at a brisk 144hz, and my games have never looked better. Well, they looked good after I finally got my color calibration worked out. It took a while, as I was out of practice, but after finding my monitor's ICC profile and eyeballing the calibration...

Since 2010, mobile searches have seen a 400% increase and it is estimated that by 2013, there will be more mobile Internet users than desktop users. A mobile-friendly site can thus help you connect with your customers and drive conversions. Just because your website can be seen on your mobile phone does not however mean that its mobile ready. Mobile sites are designed with mobile users in mind and fit well on small screens. They are supposed to offer simple navigation capabilities and take advantage...

About

DeveloperDrive.com is a blog about web development from the makers of the popular web design blog WebdesignerDepot.com
Founded in 2011, we focus on the latest trends, tutorials, opinion articles as well as tips and tricks to empower our readers to become better web developers.