A brief introduction to Snap.svg, a relatively new JavaScript library for creating and animating Scalable Vector Graphics (SVG) within your browser. Snap.svg allows you to create interactive elements and manipulate them using the powerful API. So let’s get started with some basics of Snap.svg.

Why use Snap.svg?

  1. When raster images can’t provide the interactivity and animation.
  2. For resolution-independent graphics that look great on any screen size.
  3. Advanced SVG features such as clipping masks and gradients.

Getting started with Snap.svg

This tutorial will cover the basics of Snap, by no means an exhaustive tutorial feel free to be creative.

Creating a Snap surface

Let’s create a Snap surface <svg> element in the markup.

<svg id="snapSurface"></svg>

Add a basic circle to the Snap surface, add this code to your <script> block.

var s = Snap();
var circleElement = s.circle(100, 100, 50);

Apply some styles to the circle.

    fill: "#ebebeb",
    stroke: "#333333",
    strokeWidth: 2

Interacting with the circle element

Let’s set up simple hover in and out functions.

// Hover in circle animation
function animateIn(){
    opacity: '1',  
    r: 70
  }, 1000, mina.elastic);

// Hover out circle animation
function animateOut(){
    opacity: '1',  
    r: 30
  }, 1000, mina.elastic);

// Set up the hover
circleElement.hover(animateIn, animateOut);

You might be wondering what mina.elastic does? mina(a, A, b, B, get, set, [easing]) is an animation method that animates between a pair of numbers and you can apply an easing value.