# SVG 基本形状

# 基本元素

根据万维网联盟的建议,SVG 图形元素是可以将图形绘制到目标画布上的元素类型。

它们是:rect, circle, ellipse, line, polyline, polygon, path, text, image, use

# 矩形 rect

rect 元素会在屏幕上绘制一个矩形 。其实只要 6 个基本属性就可以控制它在屏幕上的位置和形状。 上面的图例中最先展示了 2 个矩形,虽然这有点冗余了。右边的那个图形设置了 rx 和 ry 属性用来控制圆角。如果没有设置圆角,则默认为 0。

<svg width="310" height="100" style="border:1px solid">
  <rect x="0" y="0" height="100" width="200" style="stroke: #70d5dd; fill: #dd524b" />
</svg>

# 圆形 circle

正如你猜到的,circle 元素会在屏幕上绘制一个圆形。它只有 3 个属性用来设置圆形。

<svg width="310" height="100" style="border:1px solid">
  <circle cx="30" cy="50" r="25" />
  <circle cx="90" cy="50" r="25" class="red" />
  <circle cx="150" cy="50" r="25" class="fancy" />
</svg>

# 椭圆 ellipse

ellipsecircle元素更通用的形式,你可以分别缩放圆的 x 半径和 y 半径(通常数学家称之为长轴半径和短轴半径)。

<svg width="310" height="100" style="border:1px solid">
  <ellipse cx="60" cy="50" ry="40" rx="20" stroke="black" stroke-width="5" fill="silver" />
</svg>

# 线段 line

line绘制线段。它取两个点的位置作为属性,指定这条线段的起点和终点位置。

<svg width="310" height="100" style="border:1px solid">
  <line x1="10" y1="10" x2="290" y2="90" style="stroke:rgb(0,0,0);stroke-width:5" />
</svg>

# 折线 polyline

polyline是一组连接在一起的直线。因为它可以有很多的点,折线的的所有点位置都放在一个points属性中

<svg width="310" height="100" style="border:1px solid">
  <polyline points="10,10 50,50 10,90" fill="none" stroke="black" />
</svg>

# 多边形 polygon

polygon和折线很像,它们都是由连接一组点集的直线构成。不同的是,polygon 的路径在最后一个点处自动回到第一个点。

<svg width="310" height="100" style="border:1px solid">
  <polygon fill="green" stroke="orange" stroke-width="1" points="0,0 100,0 100,100 0,100 0,0" />
</svg>

# 路径 path

<svg width="310" height="100" style="border:1px solid">
  <path d="M 20 30 Q 40 5, 50 30 T 90 30"/>
</svg>

# 复用 use

<use>标签用于复制一个形状。

<svg width="310" height="100" viewBox="0 0 30 10" style="border:1px solid">
  <circle id="myCircle" cx="5" cy="5" r="4" />
  <use href="#myCircle" x="10" y="0" fill="blue" />
  <use href="#myCircle" x="20" y="0" fill="white" stroke="blue" />
</svg>

<use>的 href 属性指定所要复制的节点,x 属性和 y 属性是<use>左上角的坐标。另外,还可以指定 width 和 height 坐标。

# 复用 g

<g>标签用于将多个形状组成一个组group,方便复用。

<svg width="310" height="100" style="border:1px solid">
  <g id="myCircle">
    <text x="35" y="20">圆形</text>
    <circle cx="50" cy="50" r="20" />
  </g>
  <use href="#myCircle" x="150" y="50" fill="blue" />
  <use href="#myCircle" x="250" y="50" fill="white" stroke="blue" />
</svg>

圆形

# 复用 defs

<defs>标签用于自定义形状,它内部的代码不会显示,仅供引用。

<svg width="310" height="100" style="border:1px solid">
  <defs>
    <g id="myCircle">
      <text x="25" y="20">圆形</text>
      <circle cx="50" cy="50" r="20" />
    </g>
  </defs>
  <use href="#myCircle" x="0" y="50" />
  <use href="#myCircle" x="100" y="50" fill="blue" />
  <use href="#myCircle" x="200" y="50" fill="white" stroke="blue" />
</svg>

圆形