Work with Existing SVG or Create New Ones
The first line in our little example here cares for the SVG element with the ID
graphic. Using the variable
graphic1 we have access to all elements inside the SVG element. The second line creates a new SVG graphic with a width of 300 px and a height of 400 px.
Now we have the possibility to manipulate existing shapes inside the element or add new shapes. To achieve this, the library offers various functions, with which we can draw circles, squares and other shapes.
circle() we draw a – now what? – circle… The first two values define the x and y coordinates of the circle’s center, the third value describes the radius.
attr() allows you to control fill and frame colors as well as frame border size. You are allowed to work with all the attributes the original form element supports.
Existing SVG files can be loaded and processed, too. That’s what the method
Snap.load() is for. It loads an external SVG, which then gets attached to a function.
In this example we load the file
triangle.svg and hand it over to a function, with the variable
file as a helper. The method
select() now lets you access all the elements of the SVG.
select() in itself always selects the first element, whereas
selectAll() selects all available elements of the same type and writes them to an array.
append() binds the shapes selection to the graphic. External graphics can be accessed and manipulated in the same way and extent, internal graphics, those created directly with
Snap.svg can. Thus,
attr() allows you to alter the shape of the triangle.
Animate the SVG
Besides statically manipulating shapes of your SVG, Snap.svg is even capable of animating your graphics.
animate() allows you to alter the properties of an SVG shape along a motion path. The method expects at least two parameters. The first parameter defines the property to be altered, while the second defines the time of the animation in milliseconds.
If you want more, you could add an easing method or a function to be executed once the animation has ended.
In our example we alter the radius and change the x coordinate of the circle center. Our animation will run one second. Using
mina.easein ensures, that the animation will slow down before it stops. Easing features resemble those you already know from CSS3.
Interactions like Drag and Mouseover
Snap.svg offers several possibilities to add interaction to your SVG. Making a shape draggable per mouse is totally simple like that:
In this little example, our circle is made draggable inside the SVG space. Mouseover effects are simple to attach, too. Let’s say, we want our animation to start on mouseover:
The following video gives you a quick overview of what more you can do and helps you getting to speed quickly: