Start simple with SnapSVG

Part 1

Deepika Chhabra
3 min readDec 7, 2017

Overview

We use SVG to create interactive, resolution-independent vector graphics that will look great on any size screen. And the Snap.svg JavaScript library makes working with your SVG assets as easy as jQuery makes working with the DOM. A unique feature of Snap is its ability to work with existing SVG. That means your SVG content does not have to be generated with Snap for you to be able to use Snap to work with it. That means you create SVG content in tools like Illustrator, Inkscape, or Sketch then animate or otherwise manipulate it using Snap.

SnapSVG, as they say -

  1. Injects life into your SVG.
  2. Source agnostic.
  3. Open source and Free.

Let’s Build It

Let us now begin with creating like literally the simplest svg using SnapSVG ✌️ Create an svg using snap or use an already created svg like:

var s = Snap(“#svg”);

Now lets create a circle using snap function circle(x,y,r) as it would look something like that in the picture shown above.

var bigCircle = s.circle(150, 150, 100);

Now we’ll create two more circles that are smaller in size as

var smallCircle1 = s.circle(110,120,10);
var smallCircle2 = s.circle(190,120,10);

The above two statements would create two black circles that have radius of 10. Now we’ll try changing their attributes like fill and stroke for these circles by using attr() function provided by snap so the final svg looks something like below.

smallCircle1.attr({
fill: “#fff”,
stroke: “#333”,
strokeWidth: 3
});
smallCircle2.attr({
fill: “#fff”,
stroke: “#333”,
strokeWidth: 3
});

Snap provides path() function to create lines and curves of your choice and we’ll use path() to create a simple quadratic curve.

var path = s.path(“M100,180,Q150,220,200,180”).attr({
fill: “none”,
stroke: “#fff”,
strokeWidth: 3
});

Now we’ll try to add a simple animation to this svg using animate() function.

function onHover(){
smallCircle1.animate({fill: “#333”,},800,mina.easeout);
smallCircle2.animate({fill: “#333”,},800,mina.easeout);
path.animate({stroke: “#333”,},800,mina.easeout);
}
s.hover(onHover);

For animation, I have created a simple function that contains code as to what all I need to animate. Full Code for the above example can be found out on my github repo.

To have more in-depth knowledge of the possible functions, I would highly recommend to read their official documentation and start creating your own svg.

— Do spread the words and clap if you ❤️‍ it. Feel free to suggest anything by commenting down below ⤵️

--

--