svg wave

SVG

用SVG实现一个波浪动画

几个svg相关标签:

  • path:定义形状的基础元素,其中d属性就是图形的路径

  • animateTransform:定义目标元素的变形属性,波浪的循环移动就是使用这个属性来实现

  • g:组合对象的容器

绘制单个静态波浪

1
2
3
4
5
6
7
8
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="600" height="200">
<path d="
M 0 164
Q 129 118, 274 164
T 548 164
V 0
H 0" fill="#ccc"></path>
</svg>

上面是写好的单个波浪,其中d属性绘制了形状,fill属性表示填充的颜色

d属性中使用了以下几个命令:

  • M:M x y表示移动到(x, y)点( svg中左上角是(0,0)点 )

  • Q:Q x1 y1, x2 y2表示绘制二次贝塞尔曲线,x1 y1为二次贝塞尔的控制点,x2 y2为终点

  • T:T x y表示生成上一个二次贝塞尔曲线的镜像,其终点坐标为(x,y)

  • V:V y表示从当前点(x0,y0)垂直移动到(x0, y)

  • H:H x表示从当前点(x0, y0)水平移动到(x, y0)

上面的代码解释为:首先从(0, 0)移动到(0, 164)处,再绘制起点为(0, 164),终点为(274, 164),控制点为(129 ,118)的二次贝塞尔曲线,接着绘制以(548, 164)为终点的镜像二次贝塞尔曲线,最后依次移动到(548, 0),(0,0),从而形成闭合曲线

绘制运动效果

1
2
3
4
5
6
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="600" height="200">
<g fill="rgba(93, 147, 252, 0.7)">
<path d="M 0 164 Q 129 118, 274 164 T 548 164 T 822 164 T 1096 164 T 1370 164 V 0 H 0"></path>
<animateTransform attributeName="transform" attributeType="XML" type="translate" from="0" to="-548" dur="2s" repeatCount="indefinite"></animateTransform>
</g>
</svg>

增加了animateTransform后就动起来了,该标签的几个属性含义为:

  • attributeName:需要运动的属性
  • type:具体运动的类型
  • from:运动初始值
  • to:运动终点值
  • dur:运动时间
  • repeatCount:重复次数,indefinite为无限循环

多个组合

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="300" height="200">
<g fill="rgba(93, 147, 252, 0.7)">
<path d="M 0 164 Q 129 118, 274 164 T 548 164 T 822 164 T 1096 164 T 1370 164 V 0 H 0"></path>
<animateTransform attributeName="transform" attributeType="XML" type="translate" from="0" to="-548" dur="2s" repeatCount="indefinite"></animateTransform>
</g>
<g fill="rgba(93, 147, 252, 0.5)">
<path d="M 0 137 Q 102 60, 274 137 T 548 137 T 822 137 T 1096 137 T 1370 137 V 0 H 0"></path>
<animateTransform attributeName="transform" attributeType="XML" type="translate" from="0" to="-548" dur="3s" repeatCount="indefinite"></animateTransform>
</g>
<g fill="rgba(93, 147, 252, 0.3)">
<path d="M 0 120 Q 140 60, 274 120 T 548 120 T 822 120 T 1096 120 T 1370 120 V 0 H 0"></path>
<animateTransform attributeName="transform" attributeType="XML" type="translate" from="0" to="-548" dur="4s" repeatCount="indefinite"></animateTransform>
</g>
</svg>

SVG