What is Snap.svg

Snap.svg. Js is a framework for manipulating SVG nodes/creating SVG animations.

Snap. SVG is a library that makes manipulating SVG resources as easy as jQuery manipulating DOM

— Translated from the official website

Snap.svg (Snap) and jQuery (JQ) are best compared, but it is likely that the author also referred to JQ’s API design. How similar are they? Take a look at the comparison chart below:

/ Context The selector event Node operation Attribute operation The chain of writing
Snap svg The Snap. The select () ‘circle’ El. Click (…). / el. Touchend (…). after()/remove()/append() attr() SVG. Paper. Circle (50,50,40). Attr (# f00 “} {the fill: “);
JQ document JQuery (‘ div ‘) El. Click (…). after()/remove()/append() attr() Elem. AddClass (” hide “). The remove ();

In JQ, the outermost DOM boundary you can manipulate is document. In the concept of Snap, the outermost operable node is SVG, and the selection of SVG nodes and event binding need to be done in this context.

As can be seen from the above comparison figure, many JQ shadows are very similar to JQ in terms of selectors, event binding, node operations and so on. Students with JQ foundation can basically master all THE API of Snap in half a day.

Second, Snap code structure

The author made the chart above according to THE Snap API, and annotated it to make it easier for you to understand. You can focus on the two classes Element and Paper.

1. Element

This section is the set of methods related to node operations and is the most basic part of the class library.

Var SVG = Snap('# SVG '); svg.select('circle'); / / select SVG. Select (' rect_01 '); / / selectCopy the code
Var SVG = Snap('# SVG '); svg.select('circle').click(function() { // do something });Copy the code

For more information, see the API documentation below.

2. Paper

This section is the set of methods related to drawing, which is part of almost every animation framework, similar to the Graphics of CreateJS.

SVG has six basic shapes: rectangles, circles, ellipses, lines, folds, and polygons. There is another way: Path. Path is the most complex drawing method, and it can draw complex shapes — not to mention the six basic shapes. For basic image to path conversion, please refer to another article on this site: basic SVG shape conversion.

The Paper method set can draw six basic graphs (nodes), text (nodes), pictures (nodes), and gradients.

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);Copy the code

3. Snap tool method

There are a number of utilities under Snap, such as snap.ajax, snap.format templates, color format conversions, and plug-in methods.

Plugin (function (Snap, Element, Paper, global, Fragment) {snap.newmethod = function () {}; Element.prototype.newmethod = function () {}; Paper.prototype.newmethod = function () {}; });Copy the code

Animation with Snap

1. The method of animation

Snap does animation in two main ways:

  • Use the animate method in Element, element.animate (attrs, duration, [easing], [callback])
  • Using Snap’s static method, snap.animate (from, to, setter, duration, [easing], [callback]), which is more generic and powerful, specifies a start and end value. Setters can place animations of multiple nodes.

Example: Demonstrates the use of the Element. Animate method. Click here to preview the address

Var SVG = Snap('# SVG '); svg.select('circle').animate({r: 100}, 1000, mina.easeout(), function() { console.log('animation end'); }); 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'); });Copy the code

2. Animation properties

What are the properties that can be animated in Snap? The author can be roughly divided into several categories:

  • Simple numeric classes, such as coordinates, width and height, opacity, most Paper API configurable property values, and even filter-related properties. {x:100} -> {x:200}, {width:0} -> {width:100}
  • Path-related animation, such as d property (morphing animation), stroke animation, path-following animation
  • Matrix class, zoom out, shift, rotate, and so on, similar to CSS transform
  • {fill: ‘#f00’} -> {fill: ‘#f0f’}

Example: color change animation, preview address click here

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'); });Copy the code

Detailed explanation of path & Matrix animation

This section will focus on the path and matrix related animation methods mentioned in section 2 above, as well as the differences and similarities with CSS transform animation.

1. The path animation

1). Path deformation animation

This type of animation is very powerful. As mentioned above, basic graphics and path can be converted to each other, so the deformation animation between basic graphics is also valid. Not only that, but more complex path shapes such as waves, houses, cars, white clouds, small ICONS, etc., can all morph into each other.

The D attribute of path can reach the d value of the final state through a series of mathematical operations in Snap’s parsing rules and interpolation in animation, but we cannot interfere with the interpolation calculation in the middle.

Var path = svg.paper.path({d: 'M0.500, 65.500c18.680,33.758 45.141,-6.797 72.500,2.500 C99.859,11.797 72.148,59.027 79.500,98.500 C86.852,137.973 117.668,128.914 138.500,59.500 C159.332,-9.914 246.500,59.500 246.500,59.500 C273.181,117.750 137.350,184.417 225.500,173.500 C351.137,157.940 155.369,160.617 162.500,86.500 C165.180,58.645 237.169,-2.418 283.500,2.500 C357.654, 10.371, 363.758, 80.355, 364.500, 109.500 ', stroke: '# f00', the fill: 'rgba (0,0,0,0)'}); SetTimeout (function() {path.animate({d: 'M1,100 L350,100'}, 1000, mina.easeout(), function() {// console.log('animation end'); / /}); // Animate: heart path.animate({d: 'M114.500, 58.500c106.230,58.751 23.907,-37.262 5.500,21.500 c-26.759,124.483 111.761,221.360 119.500,219.500 C154.464,211.096 201.234,149.580 220.500,104.500 C250.260,34.864 220.892,7.159 194.500,1.500 C160.455,-5.800 Easeout (), function() {console.log('animation end'); function() {console.log('animation end'); }); }, 1000);Copy the code

Example: Curve to straight line, preview address here

Example: Curve changes to heart, preview the address here

2). Path Stroke animation

This animation mainly uses SVG’s stroke-Dasharray and stroke-Dashoffset properties, which are described in detail in another article on this site and will not be described here

Example: Simple curve stroke animation

var path = svg.paper.path({d: 'M0.500, 65.500c18.680,33.758 45.141,-6.797 72.500,2.500 C99.859,11.797 72.148,59.027 79.500,98.500 C86.852,137.973 117.668,128.914 138.500,59.500 C159.332,-9.914 246.500,59.500 246.500,59.500 C273.181,117.750 137.350,184.417 225.500,173.500 C351.137,157.940 155.369,160.617 162.500,86.500 C165.180,58.645 237.169,-2.418 283.500,2.500 C357.654, 10.371, 363.758, 80.355, 364.500, 109.500 ', stroke: '# f00', the fill: 'rgba (0,0,0,0)'}); var length = Snap.path.getTotalLength(path); Path.attr ({'stroke-dashoffset': length, 'stroke-dasharray': length // Compute complex path length with Snap API}); Snap.animate(length, 0, function(val) { path.attr({ 'stroke-dashoffset': val }); }, 1000, mina.easeout(), function() { console.log('animation end'); });Copy the code

Or use CSS:

@keyframes demo4 { 
    100% {
        stroke-dashoffset: 0
    }
}
.demo4 {
    animation: demo4 1s ease-out infinite both;
}Copy the code

Example: pattern stroke. Here is a complex example from Codepen — a stroke animation of a complex pattern.

3).path path follows animation

This kind of animation refers to the animation of an SVG node (basic graphics, text, pictures, etc.) moving along the track, which is mainly suitable for simulating the navigation track of vehicles and particle scattering track, etc.

The key to this kind of animation is knowing how the length of a path corresponds to coordinates. Snap provides an API to get the length of a path and to get position coordinates based on the length. With the snap.animate method above, creating a path-following animation becomes very simple.

Example: Follow the curve movement of the small plane, preview the address here:

var length = Snap.path.getTotalLength(path); / / get the length of the path the Snap. The animate (0, length, the 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); // Keep the plane always in the curve direction. Point-alpha: The Angle formed by the tangent of a point and the horizontal line plane.transform(m); }, 30000, mina.easeout(), function() { console.log('animation end'); });Copy the code

Example: Double 12 opening animation, this is the author last year double 12 do a path following animation effect, preview address here:

A new CSS property, Motion-Path, can be used to achieve similar results, but the support is limited to Chrome on the PC, Opera, and the latest X5 core mobile browsers.

@keyframes demo5 { 0% { motion-offset: 0; } 100% { motion-offset: 100%; } } .demo5 { motion-path: C237.176 path (" M221.712, 180.442, 177.728, 279.348, 178.094, 261152-18.742 - c - 26.654-48.543-28.207-63-22-14.981, 6.431-34.763, 6. 357-34, 40 s66.09, 74.162, 88,68,60.358-23.742, 67-49,14.211 s163-59.957-27-81. 688,88.664, 153 16/32-bit c - 7.828, 6.838-32.045, 22.952-32 , 64,0.039, 35.491, 7.878, 62.872, 14,78 s52.737, 39.557, 73,41,58.638, 16.552, 105-7 c44. 249-22.478, 75.073-94.409, 55-164 c349. 768, 4 6.792, 217.142, 54.519, 200 zhongguo kuangye daxue S104.613, 66.128, 16.922, 78111 c, 28.532 to 16.5, 96.616, 1134,14.482, 30.932, 51.88, 58.52, 68,64,39.98 8,13.593, 100.081, 21.615, 129, "); motion-rotation: auto 90deg; Animation: demo5 10s linear infinite both; }Copy the code

Click here for a preview (check out the latest version of Chrome, Opera, or the latest X5 core mobile browser)

2. The matrix of animation

The Snap matrix animation contains you familiar translate/scale/rotate/skew animation, principle, and the transform of CSS also almost unanimously.

1) Matrix simple displacement animation, preview address here:

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); // Translate transform API rect.transform(m); // Apply matrix} to the rect node, 1000, mina.easeout(), function() {console.log('animation end'); setTimeout(anim, 300); }); } anim();Copy the code

2) Matrix displacement and rotation composite animation, preview addressClick here to:

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, 150, animate); function(val) { var m = new Snap.Matrix(); m.rotate((val/250)*360, 10+25, 100+15); Rect.transform (m); rect.transform(m); 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();Copy the code

The above two animations are implemented using CSS as follows:

@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; rect { transform-origin: 35px 115px; animation: demo7_rotate .5s linear infinite both; }}Copy the code

Simple displacement animation CSS version preview click here; Rotation and displacement conform to animated CSS version preview click here.

Five, several compatibility instructions and suggestions

This section describes some of the compatibility issues I encountered during the development process and provides some suggestions for use. Of course, there will be more problems I have not encountered, welcome to see more comments and exchanges, generous comments.

  • Overall, Snap’s API compatibility is good, with the website claiming it is compatible with IE9 and above, Safari, Chrome, Firefox, Opera; In terms of mobile devices, the author has tested the compatibility of iOS, Android X5 kernel and Android native browser. The examples in this paper can be executed except for special instructions
  • CSS Transform animations applied to SVG nodes are not compatible with Native Android browsers, X5 is fine
  • The innerHTML method cannot be used in SVG in iOS7 and 8
  • Drawing SVG graphics in android native browsers is likely to cause rendering blur (as shown below), which can be magically fixed by adding a text node to SVG

Such a< text>a</text> node fixes the ambiguity, but cannot be hidden by display: None

In terms of usage suggestions:

  • In general, transform animations can be implemented using CSS in preference, but if you need sophisticated segmentation control or better compatibility, try Snap’s Transform&Matrix
  • Some Snap animations are computation-intensive, and while nodes in SVG are “absolutely positioned” and generally do not cause rearrangements when animated (see figure below), it is important not to have too many animation elements on mobile devices. Taking image animation as an example, according to the author’s test, the image animation nodes of about 150×150 can basically meet the performance requirements of most models when controlled at about 10
  • Filter class properties are not suitable for animation on mobile devices

Small plane animation in Chrome render layer boundary image:

The orange edge is the SVG boundary (i.e., the render layer, which is transformed :rotateY(30deg) for easy viewing of SVG nodes; Green redraw. As you can see, animation elements in SVG will only cause redrawing, and nodes in it will not open a new render layer with translateZ.

Vi. Reference materials

The Snap. SVG’s official website

Web Animation API Tutorial 5: Motion Path

Zhang Xinxu: Snap. SVG API Chinese document and demo example page

Snap.svg
animation
SVG framework
Web development
Convex laboratory
Aotu. IO/notes / 2017 /…