In our latest project @ Webcake (webcake.ch), we wanted to have some icons with some lively and neat animations. To ensure that they’ll look great on any device, the idea of SVG animations came up. I’ve worked with SVG for a long time, but to animate them was a different task, so I had to make myself familiar with it first. This compass was the first approach to SVG animation design. I won’t use it in the actual project, but it’s a great point to start.
In the beginning it’s all about a great structure and hierarchy in your SVG image. I created the compass in Illustrator, strongly inspired by Anders Drage’s on Dribbble. Like I said before, make sure you keep your SVG’s structure clean! That means you have to group everything that belongs together and give a name to each layer and each group.
Fig. 1: Make sure you keep your structure clean and comprehensible
When you have finished creating your illustration, it’s time to save it as an SVG file and move on to the coding part!
This loads the code inside the SVG file into the HTML and not just the SVG itself, that allows us to access its layers and groups simply by their id’s.
My compass for example has the group “compass-whole-pointer” (I’ve chosen that name in Illustrator for the group which contains the paths of the pointer). In my CSS, I can now access this pointer with #compass-whole-pointer like this:
In my demo, I have positioned my compass in the center of the screen, you can do that as well if you want or you can leave it. But make sure you make your div (in my case with the id “workspace”) the exact dimensions of your SVG (mine is 350px * 350px)!
Afterwards I create the CSS3 @keyframes animation for later use. It’s very simple in this example because it uses only rotate transforms:
Now that we have all we need, let’s get it spinnin'! Just call the @keyframes animation when the class .svgLoaded is added to the SVG tag in your HTML.
Always remember to include your .js and .css file in the head of your HTML.
You’re good to go! It should now spin like a crazy compass. If you want to take a closer look of my code, dig into the source at svgcompass.herokuapp.com (it may take a while to load). If you don’t want to make your own compass, you can also catch the SVG file of this tutorial here.
Thank you for reading!