SVG学习笔记

208 阅读1分钟

基本介绍

SVG是一种基于XML的矢量图形语言,保存着一组图形之间的关系。

画布标签

<!-- width,height表示画布大小,单位px -->
<svg width="200" height="200">

</svg>

可选属性

viewBox

SVG中图形元素单位是相对于viewBox容器的虚拟单位。默认情况下viewBox和画布大小一致,不过可以通过设置viewBox实现SVG的自适应缩放。

<svg width="200" height="200" viewBox="0 0 400 400">
  <!-- 这里的100是相对于400而言的,实际映射到画布上只有200*(100/400)等于50px -->
  <rect width="100" height="100" />
</svg>

形状标签

矩形(rect)

<svg width="200" height="200">
  <rect x="50" y="50" width="100" height="100" fill="transparent" stroke="red" />
</svg>

image.png

圆形(circle)


<svg width="200" height="200">
  <circle cx="100" cy="100" r="50" fill="transparent" stroke="red" />
</svg>

image.png

椭圆(ellipse)

<svg width="200" height="200">
  <ellipse cx="100" cy="100" rx="100" ry="50" fill="transparent" stroke="red" />
</svg>

image.png

直线(line)

<svg width="200" height="200">
  <line x1="10" y1="100" x2="190" y2="100" stroke="red" />
</svg>

image.png

折线(polyline)

<svg width="200" height="200">
  <polyline
    points="10 100 50 50 100 100 150 50 190 100"
    fill="transparent"
    stroke="red"
  />
</svg>

image.png

多边形(polygon)

多边形和折现参数相同,区别是多边形会将终点和起点相连接。

<svg width="200" height="200">
  <polygon
    points="10 100 50 50 100 100 150 50 190 100"
    fill="transparent"
    stroke="red"
  />
</svg>

image.png

路径标签

路径标签path是SVG中最强大的标签,通过一组指令的集合表述绘制的过程,可以画出所有上述形状。

移动指令

把画笔移动到指定坐标,path的第一个指令必须是M指令。

<svg width="200" height="200">
  <path d="M 10 100" />
</svg>

直线指令

<svg width="200" height="200">
  <path d="M 10 100 L 100 100" stroke="red" />
</svg>

image.png

曲线指令

<svg width="200" height="200">
  <path d="M 10 100 Q 100 10 190 100" fill="none" stroke="red" />
</svg>

image.png

动画

SMIL动画

设置属性(set)

<svg width="200" height="200">
  <circle cx="100" cy="100" r="50" fill="none" stroke="red">
    <set attributeName="r" to="100" begin="1s" />
  </circle>
</svg>

set.gif

补间动画(animate)

<svg width="200" height="200">
  <circle cx="100" cy="100" r="50" fill="none" stroke="red">
    <animate attributeName="r" to="100" dur="2s" repeatCount="indefinite" />
  </circle>
</svg>

animate.gif

transform动画(animateTransform)

<svg width="200" height="200">
  <circle cx="100" cy="100" r="50" fill="none" stroke="red">
    <animateTransform
      attributeName="transform"
      type="translate"
      from="-200,0"
      to="200,0"
      dur="2s"
      repeatCount="indefinite"
    />
  </circle>
</svg>

transform.gif

沿轨迹(path)运动(animateMotion)

元素定位的坐标系以path起点为原点。

<svg width="200" height="200">
  <circle r="10" fill="none" stroke="red">
    <animateMotion
      path="M 10 100 Q 100 10 190 100"
      dur="2s"
      repeatCount="indefinite"
    />
  </circle>
</svg>

animationMotion.gif