HTML5 - Super SVG animation

Posted by northernmonkey on Wed, 05 Jan 2022 15:05:28 +0100

There are many implementation methods of svg animation, and there is also a large svg animation library. Now let's introduce the implementation methods of svg animation?

1, SVG's animation

SVG animation has five elements that control different types of animation, namely:

  • set
  • animate
  • animateColor
  • animateTransform
  • animateMotion

1.1,set

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

Use syntax:

<set attributeName="" attributeType="" to="" begin="" />
  • attributeName: is the attribute name of the element to be changed.
  • attributeType: it is a list indicating the attributeName attribute value. It supports three fixed parameters CSS/XML/auto. For example, x,y and transform belong to XML and opacity belongs to CSS. Auto means that the browser automatically judges. It is also the default value. If you don't know which one to choose, fill in auto and the browser will judge by itself.
  • to: attribute value at the end of the animation.
  • 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>

1.2,animate

It is the basic animation element to realize the transition effect of single attribute.

Use syntax:

<animate 
 attributeName="r" 
 from="200" to="50" 
 begin="4s" dur="2s" 
 repeatCount="2"
></animate>
  • from: the attribute start value of the transition effect.
  • to: attribute end value of the transition effect.
  • begin: animation start time.
  • dur: animation transition time, controlling animation speed.
  • repeatCount: the number of animation repetitions.

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>

1.3,animateColor

Control color animation, animate can also achieve this effect, so this attribute has been abandoned.

1.4,animateTransform

Realize the transform animation effect, which is similar to the transform of css3. Achieve translation, rotation, scaling and other effects.

Use syntax:

<animateTransform attributeName="transform"  type="scale" 
 from="1.5" to="0" 
 begin="2s"  dur="3s" 
 repeatCount="indefinite"></animateTransform>
  • repeatCount: the number of repetitions. If it is set to infinite, it indicates an infinite loop, which is always executed.
  • Type: adds a transform type.
  • eg: draw a circle with a radius of 200, scale it after 4 seconds, and reduce it 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>

1.5,animateMotion

You can define an animation path to let each SVG figure move along the specified path.

Use syntax:

<animateMotion 
 path="M 0 0 L 320 320" 
begin="4s" dur="2s"></animateMotion>
  • Path: defines the path, using syntax and HTML5(8) - SVG path explanation The d attribute of path is consistent.
  • begin: delay time.
  • dur: animation execution time.

eg: draw a circle with a radius of 10 and delay 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>

When actually making animation, the animation is too single and not cool. When multiple attributes need to be changed at the same time, the four elements above can be combined with each other, and the same type of animation can also be combined. Although the above elements can realize animation, they cannot add events dynamically, so let's see how js makes animation.

2, JavaScript control

In the previous article, we introduced that js can operate path, also SVG's built-in shape elements, and add events to any element.

The method of adding events to SVG elements is the same as that of ordinary elements, which can be added only with on + event name or addEventListener.

eg: use SVG to draw a line. When clicking the line, change 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>

The SVG animation produced by js mainly uses requestAnimationFrame to change frame by frame.

The SVG graphics and animations we produced above run in low-level ie. it is found that SVG is only supported by IE9 and above, but not by low-level browsers. In order to be compatible with low-level browsers, VML can be used. Additional things need to be added to VML, v: elements need to be added to each element, and behavier needs to be added to the style, which is often used to draw maps. Because it is too troublesome to use, we use Raphael JS library.

3, Rapha ë l.js (Raphael)

Raphael.js realizes cross browser vector graphics through SVG/VML+js. VML is used in IE browser and SVG is used in non IE browser, which is similar to jquery. It is still a javascript Library in essence, which is simple to use and easy to use.

Raphael needs to be introduced before use JS library file. The address of cdn is:
https://cdn.bootcdn.net/ajax/libs/raphael/2.3.0/raphael.js

3.1. Create canvas

Rapheal has two ways to create canvases:

First: create canvas on browser window

Create syntax:

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

x. Y is the coordinate of the upper left corner of the canvas. At this time, the position of the canvas is absolutely positioned, which may overlap with other html elements. Width and height are the width and height of the canvas.

Second: create canvas in one 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 graphics

After the canvas is created, the object comes with SVG built-in graphics, including rectangle, circle and ellipse. Their methods are:

paper. circle(cx, cy, r); // (CX, CY) center coordinate R radius
paper.rect(x, y, width, height, r); // (x,y) upper left corner coordinate width height height r fillet radius (optional)
paper. ellipse(cx, cy, rx, ry); // (CX, CY) center coordinate 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>

The operation results are as follows:

In addition to simple graphics, you can also draw complex graphics, such as triangles and hearts. At this time, use the path method.

Usage syntax: paper path(pathString)

pathString is composed of one or more commands. Each command starts with a letter, and multiple parameters are separated by commas.

eg: draw a triangle.

let sj = paper.path("M 0,0 L100,100 L100,0 'Z'")

You can also draw text and use \ n if you need to wrap.

Text syntax: paper text(x,y,text)

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

3.3. Setting properties

After drawing graphics, we usually add stroke, fill, stroke width, etc. to make the graphics more beautiful. Raphael uses attr to set attributes for the graphics.

Usage syntax: circle Attr ({attribute name "," attribute value "," attribute name "," attribute value ",...})

If only the property name has no property value, the property is obtained. If there is a property value, the property is set.

Note: if only one attribute is set, '{}' can be omitted. For example: rect attr('fill','pink')

eg: add border and background color to the upper rectangle.

<div id="box"></div>
<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>

3.4. Add event

RaphaelJS generally has the following events:
click, dblclick, drag, hide, hover, mousedown, mouseout, mouseup, mouseover, and the corresponding cancellation events. Just add "un" in front of them (unclick, undblclick).

Use syntax:

obj.click(function(){
 //Contents to be operated
})

3.5. Add animation

animate adds animation to the specified shape and executes.

Use syntax:

obj.animate({
 "Property name 1":Attribute value 1,
 "Property name 2":Attribute value 2,
  ...
},time,type)

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

Time: the time required for the animation.

Type: refers to the type of animation jog. Common values are:

  • Linear - linear gradient
  • Ease in | ease in | < - from slow to fast
  • Ease out | ease out | > - from fast to slow
  • Ease in out | ease in out | < > - from slow to fast and then to slow
  • Back in | backin - rebound at the beginning
  • Back out | backout - rebound at the end
  • elastic - rubber band
  • bounce - bounce

eg: click the rectangle, and the rectangle slowly becomes larger.

<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 above code and run it in each browser and low version IE browser respectively. It is found that it can run normally. SVG has a lot of animation libraries. We introduced Raphael. Interested partners can find other libraries by themselves.

Topics: html5