There are many ways to implement SVG animation, as well as a large SVG animation library. Now let’s introduce what are the methods of implementing SVG animation?

1. Animation of SVG

SVG Animation has five elements that control different types of animation. They are:

  • set
  • animate
  • animateColor
  • animateTransform
  • animateMotion

1.1, the set

Set sets the delay for the animation element, which is the simplest animation element in SVG, but it has no animation effects.

Use grammar:

<set attributeName="" attributeType="" to="" begin="" />
Copy the code
  • AttributeName: Is the name of the element attribute to be changed.
  • AttributeType: Indicates the value of attributeName, which supports three fixed parameters: CSS/XML/ AUTO. For example, x, Y, and Transform belong to XML, while opacity belongs to CSS. Auto is what the browser automatically checks, and it’s the default, so if you don’t know which one to choose, you just fill in auto, and the browser checks.
  • To: The value of the property when the animation ends.
  • Begin: animation delay time.

Eg: Draw a circle with a radius of 200. After 4 seconds, the radius becomes 50.

<svg width="320" height="320"> <circle cx="0" cy="0" r="200" style="stroke: none; fill: #0000ff;" > <set attributeName="r" attributeType="XML" to="50" begin="4s" /> </circle> </svg>Copy the code

1.2, the animate

Is the basic animation element to achieve a single attribute transition effect.

Use grammar:

<animate 
 attributeName="r" 
 from="200" to="50" 
 begin="4s" dur="2s" 
 repeatCount="2"
></animate>
Copy the code
  • From: The start value of the transition effect property.
  • To: The end value of the property for the transition effect.
  • Begin: Indicates the start time of the animation.
  • Dur: Animation transition time, controls animation speed.
  • RepeatCount: Number of times the animation is repeated.

Eg: Draw a circle with a radius of 200. After 4 seconds, the radius gradually changes from 200 to 50 in 2 seconds.

<circle cx="0" cy="0" r="200" style="stroke: none; fill: #0000ff;" > <animate attributeName="r" from="200" to="50" begin="4s" dur="2s" repeatCount="2"></animate> </circle>Copy the code

1.3, animateColor

Controlling the color animation, animate can also achieve this effect, so this property is currently deprecated.

1.4, animateTransform

Transform transform animation effect, similar to cSS3 transform. Achieve translation, rotation, scaling and other effects.

Use grammar:

<animateTransform attributeName="transform"  type="scale" 
 from="1.5" to="0" 
 begin="2s"  dur="3s" 
 repeatCount="indefinite"></animateTransform>
Copy the code
  • RepeatCount: Number of times to repeat. Set it to indefinite to indicate that the loop will be executed indefinitely.
  • Type: Adds the transform type.
  • Eg: Draw a circle with a radius of 200 and start scaling after 4 seconds. It will shrink from 1.5 to 0 times in 2 seconds.
<svg width="320" height="320"> <circle cx="0" cy="0" r="200" style="stroke: none; fill: #0000ff;" > <animateTransform attributeName="transform" begin="4s" dur="2s" type="scale" from="1.5" to="0" repeatCount="indefinite"></animateTransform> </circle> </svg>Copy the code

1.5, the animateMotion

You can define animation paths that allow SVG graphics to move along specified paths.

Use grammar:

<animateMotion 
 path="M 0 0 L 320 320" 
begin="4s" dur="2s"></animateMotion>
Copy the code
  • Path: Define the path, using the same syntax as the D attribute of PATH in HTML5(8) — SVG Path Details.
  • Begin: indicates the delay time.
  • Dur: Animation execution time.

Eg: Draw a circle with a radius of 10 and a delay of 4 seconds from the upper left corner to the lower right corner.

<svg width="320" height="320"> <circle cx="0" cy="0" r="10" style="stroke: none; fill: #0000ff;" > <animateMotion path="M 0 0 L 320 320" begin="4s" dur="2s" ></animateMotion> </circle> </svg>Copy the code

The actual production of animation, animation is too single not cool, need to change multiple attributes at the same time, the above four elements can be combined with each other, the same type of animation can also be combined. While these elements can be animated, events cannot be added dynamically, so let’s take a look at how JS animates.

Second, JavaScript control

In the previous article, we showed that JS can manipulate PATH, as well as SVG’s built-in shape elements, and can add events to any element.

Adding an event to an SVG element is the same as adding an event to a normal element. You can just add on+ event name or addEventListener.

Eg: Use SVG to draw a line, click the line to change the X1, to achieve the rotation effect.

<svg width="800" height="800" id="svg">
    <line id="line" x1="100" y1="100" 
    x2="400" y2="300" 
    stroke="black" stroke-width="5"></line>  
  </svg>
<script>
 window.onload = function(){
  var line = document.getElementById("line")
  line.onclick = function(){
   let start = parseInt(line.getAttribute("x1")),
       end=400,dis = start-end
   requestAnimationFrame(next)
   let count = 0;
   function next(){
    count++
    let a = count/200,cur = Math.abs(start+ dis*a)
    line.setAttribute('x1',cur)
    if(count<200)requestAnimationFrame(next)
   }
  }
 }
</script>
Copy the code

Js SVG animation, mainly using requestAnimationFrame to achieve a frame by frame change.

In order to be compatible with browsers of earlier versions, we can use VML. VML needs to add some extra things. For each element, we need to add v: element. You also need to add behavier to the style, which is often used for mapping. Because it’s too cumbersome to use, we use the raphael.js library.

3. Raphael. Js

Raphael.js implements cross-browser vector graphics through SVG/VML+ JS. VML is used in Internet Explorer, and SVG is used in non-Internet Explorer. It is similar to jquery, and it is a javascript library in essence, which is simple to use and easy to get started.

You need to import the raphael.js library before using it. CDN address is: cdn.bootcdn.net/ajax/libs/r…

3.1 create canvas

Rapheal has two ways to create a canvas:

First: Create a canvas on the browser window

Create syntax:

var paper = Raphael(x,y,width,height)

X and y are coordinates for the upper left corner of the canvas, where the canvas is absolutely positioned and may overlap with other HTML elements. Width and height are the width and height of canvas.

Second: Create a canvas in an element

Create syntax:

var paper = Raphael(element, width, height);

Element is the element node itself or ID width and height are the width and height of the canvas.

3.2. Drawing graphs

Once the canvas is created, the object comes with SVG built-in graphics with rectangles, circles, and ellipses. Their methods are:

paper.circle(cx, cy, r); Rect (x, y, width, height, r); rect(x, y, width, height, r); (optional) paper. Ellipse (cx, cy, rx, ry); // (cx, cy) rx horizontal radius ry vertical radius

Eg: Draw a circle, an ellipse and a rectangle in div.

<div id="box"></div>
<script>
 var paper = Raphael("box",300,300)
 paper.circle(150,150,150)
 paper.rect(0,0,300,300)
 paper.ellipse(150,150,100,150)
</script>
Copy the code

The running results are as follows:

In addition to simple shapes, you can draw complex shapes, such as triangles and hearts, using the PATH method.

Use syntax: paper.path(pathString)

PathString is composed of one or more commands, each starting with a letter, and multiple arguments separated by commas.

Eg: Draw a triangle.

Let sj = paper. Path ("M 0,0 L100,100 L100,0 'Z'")Copy the code

You can also draw text, using \n if you need a newline.

Paper. Text (x,y,text)

(x,y) is the text coordinate, and text is the text to be drawn.

3.3. Set properties

After the graph is drawn, we usually add stroke, fill, strope-width and so on to make the graph more beautiful. Raphael uses attr to set the attributes of the graph.

Use syntax: circle.attr({” attribute name “,” attribute value “,” attribute name “,” attribute value “,… })

If there is only a property name but no property value, it gets the property, and if there is a property value, it sets the property.

Note: You can omit ‘{}’ if you set only one property. Such as: the rect. Attr (‘ fill ‘, ‘pink’)

Eg: Add a border and background color to the top rectangle.

<div id="box">< div id="box">< script> var paper = Raphael("box",300,300) let rect = paper.rect(100,100,150,200) rect.attr({'fill':'red','stroke':'blue','stroke-width':'10'}) </script>Copy the code

3.4 Adding events

RaphaelJS generally has the following events: Click, dblclick, drag, hide, hover, mousedown, mouseout, mouseup, mouseover, etc., as long as the front of the “UN” can be (unclick, undblclick).

Use grammar:

Object.click (function(){// what to do})Copy the code

3.5. Add animation

Animate adds animation to the specified graph and executes it.

Use grammar:

Obj. Animate ({" attribute 1": attribute value 1, "attribute 2": attribute value 2,... },time,type)Copy the code

The property name and property value are added according to the type of animation you want.

Time: Time required for animation.

Type: indicates the type of animation easing. Common values are:

  • Linear – Linear gradient
  • Ease – in | easeIn | < – from slow to fast
  • Ease – out | easeOut | > – from fast to slow
  • Ease – in-out | easeInOut | < > – from slow to fast and slow
  • The back – in | backIn – at the beginning of the springback
  • At the end of the back – out | backOut – the springback
  • -Dan: That’s an elastic band
  • Bounce, bounce

Eg: Click on the rectangle and the rectangle will grow slowly.

<div id="box"></div>
<script>
 var paper = Raphael("box",800,500)
 let rect = paper.rect(100,100,150,100)
 rect.attr({'fill':'red','stroke':'blue','stroke-width':'10'})
 rect.attr('fill','pink')
 rect.click(function(){
  rect.animate({
   "width":300,
   "height":300
  },1000,"bounce")
 })
</script>
Copy the code

Copy the above code and run it on each browser and a lower version of IE. It works. There are many animation libraries for SVG, we introduced Raphael, interested partners can find other libraries.