Master Snap.svg: From Basics to Advanced SVG Animations with Code Samples

This article provides a comprehensive guide to Snap.svg, explaining its purpose, API similarities with jQuery, core classes like Element and Paper, various animation techniques—including element and static animations, path and matrix transformations—along with compatibility tips, performance recommendations, and useful code examples.

Aotu Lab
Aotu Lab
Aotu Lab
Master Snap.svg: From Basics to Advanced SVG Animations with Code Samples

1. What is Snap.svg

Snap.svg.js is a JavaScript framework for manipulating SVG nodes and creating SVG animations, offering an API style similar to jQuery for DOM manipulation.

Snap.svg is a library that makes manipulating SVG resources as easy as using jQuery to manipulate the DOM.

The library’s design mirrors jQuery’s API, with comparable selectors, event binding, node operations, attribute handling, and chainable syntax.

2. Snap code structure

Element

The Element class provides the fundamental node‑manipulation methods.

// Select a node
var svg = Snap('#svg');
svg.select('circle'); // select
svg.select('.rect_01'); // select
// Bind an event
var svg = Snap('#svg');
svg.select('circle').click(function() {
    // do something
});

Paper

The Paper class offers drawing methods similar to createjs Graphics, allowing creation of basic shapes, text, images, gradients, etc.

// Draw a circle
var svg = Snap('#svg');
svg.paper.circle({
    cx: 100,
    cy: 100,
    r: 50,
    fill: '#f00'
});
// Create an image
svg.paper.image('url.jpg', 0, 400, 300, 300);

Snap utility methods

Snap also provides utilities such as Snap.ajax, Snap.format, color conversion, and a plugin system.

// Extend Snap with a plugin
Snap.plugin(function (Snap, Element, Paper, global, Fragment) {
    Snap.newmethod = function () {};
    Element.prototype.newmethod = function () {};
    Paper.prototype.newmethod = function () {};
});

3. Creating animations with Snap

Animation methods

Element.animate(attrs, duration, [easing], [callback])

Snap.animate(from, to, setter, duration, [easing], [callback]) – a more generic static method

Example of element animation:

// Animation example 1
var svg = Snap('#svg');
svg.select('circle').animate({r: 100}, 1000, mina.easeout(), function() {
    console.log('animation end');
});
// Animation example 2
var svg = Snap('#svg');
var circle = svg.select('circle');
var rect = svg.select('rect');
Snap.animate(0, 100, function (val) {
    circle.attr({r: val});
    rect.attr({x: val});
}, 1000, mina.easeout(), function () {
    console.log('animation end');
});

Animation property categories:

Simple numeric values (coordinates, width, height, opacity, etc.)

Path‑related animations (d attribute, stroke animation, path‑following)

Matrix transformations (translate, scale, rotate, skew)

Color changes (fill, stroke, etc.)

Color‑change example:

// Color animation example
var svg = Snap('#svg');
var circle = svg.paper.circle({cx: 100, cy: 100, r: 50, fill: '#f00'});
circle.animate({fill: '#00f'}, 1000, mina.easeout(), function () {
    console.log('animation end');
});

4. Path & matrix animation details

Path animation

Path deformation, stroke‑dash animation, and path‑following are supported. The d attribute can be interpolated automatically.

// Path deformation example
var path = svg.paper.path({
    d: 'M0.5,65.5 C18.68,33.758 ...',
    stroke: '#f00',
    fill: 'rgba(0,0,0,0)'
});
setTimeout(function () {
    // Transform to a heart shape
    path.animate({d: 'M114.5,58.5 C106.23,58.751 ... Z'}, 1000, mina.easeout(), function () {
        console.log('animation end');
    });
}, 1000);

Stroke‑dash (drawing) animation:

// Stroke‑dash animation
var path = svg.paper.path({
    d: 'M0.5,65.5 C18.68,33.758 ...',
    stroke: '#f00',
    fill: 'rgba(0,0,0,0)'
});
var length = Snap.path.getTotalLength(path);
path.attr({
    'stroke-dashoffset': length,
    'stroke-dasharray': length
});
Snap.animate(length, 0, function (val) {
    path.attr({'stroke-dashoffset': val});
}, 1000, mina.easeout(), function () {
    console.log('animation end');
});

Path‑following animation (e.g., a plane moving along a curve):

// Path‑following example
var length = Snap.path.getTotalLength(path);
Snap.animate(0, length, function (val) {
    var point = Snap.path.getPointAtLength(path, val);
    var m = new Snap.Matrix();
    m.translate(point.x, point.y);
    m.rotate(point.alpha - 90);
    plane.transform(m);
}, 30000, mina.easeout(), function () {
    console.log('animation end');
});

Matrix animation

Snap.Matrix provides translate, scale, rotate, and skew transformations, analogous to CSS transform.

// Simple translate animation
var rect = svg.paper.rect({x: 100, y: 100, width: 50, height: 30, fill: '#f00'});
var anim = function () {
    Snap.animate(0, 150, function (val) {
        var m = new Snap.Matrix();
        m.translate(val, 0);
        rect.transform(m);
    }, 1000, mina.easeout(), function () {
        console.log('animation end');
        setTimeout(anim, 300);
    });
};
anim();
// Combined translate & rotate animation
var rect = svg.paper.rect({x: 10, y: 100, width: 50, height: 30, fill: '#f00'});
var g = svg.paper.group(rect);
var anim_rotate = function () {
    Snap.animate(0, 250, function (val) {
        var m = new Snap.Matrix();
        m.rotate(val / 250 * 360, 10, 115);
        rect.transform(m);
    }, 500, mina.easeout(), function () {
        console.log('animation end');
        anim_rotate();
    });
};
anim_rotate();
var anim_move = function () {
    Snap.animate(0, 250, function (val) {
        var m = new Snap.Matrix();
        m.translate(val, 0);
        g.transform(m);
    }, 2000, mina.easeout(), function () {
        console.log('animation end');
        anim_move();
    });
};
anim_move();

Equivalent CSS keyframes are also shown for simple translate and combined animations.

@keyframes demo6 {100% {transform: translate3d(250px,0,0);}}
.demo6 {animation: demo6 2s linear infinite both;}
@keyframes demo7_rotate {100% {transform: rotate(360deg);}}
@keyframes demo7_move {100% {transform: translate3d(250px,0,0);}}
.demo7 {animation: demo7_move 2s linear infinite both;}
.demo7 rect {transform-origin: 35px 115px; animation: demo7_rotate .5s linear infinite both;}

5. Compatibility notes and recommendations

Snap API is compatible with IE9+, Safari, Chrome, Firefox, Opera, and mobile browsers on iOS, Android X5, and Android native browsers.

CSS transform on SVG nodes performs poorly on Android native browsers.

In iOS 7/8, innerHTML cannot be used inside SVG.

Android native browsers may render blurry SVG; inserting a <text>a</text> node fixes the issue (cannot be hidden with display:none).

Recommendations:

Prefer CSS transforms for simple animations; use Snap’s transform & matrix for complex, segmented control or better compatibility.

Avoid animating many nodes on mobile—around ten 150×150 images work well on most devices.

Avoid animating filter properties on mobile devices.

6. References

Snap.svg official website

Web Animation API tutorial on motion paths

Zhang Xinxu: Snap.svg API Chinese documentation with demo pages

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

frontendJavaScriptSVG animationWeb animationMatrix transformSnap.svg
Aotu Lab
Written by

Aotu Lab

Aotu Lab, founded in October 2015, is a front-end engineering team serving multi-platform products. The articles in this public account are intended to share and discuss technology, reflecting only the personal views of Aotu Lab members and not the official stance of JD.com Technology.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.