暗黑模式
defs、g、use 元素 
前端教程SVG
就像编程时,我们使用 function class 等语言特性来组织代码、复用代码;类似的,SVG 也支持代码结构化、代码复用等。
本节我们介绍如何使用 <defs> <g> <use> 元素实现代码复用。
<defs> 元素 
defs 即 definitions,是图形、渐变颜色等 SVG 元素的集合。在 <defs> 里的图形都不会显示,而是在其他地方被引用。
html
<svg viewBox="0 0 10 10" xmlns="http://www.w3.org/2000/svg">
  <!-- 定义图形对象 -->
  <defs>
    <circle id="myCircle" cx="0" cy="0" r="5" />
    <linearGradient id="myGradient" gradientTransform="rotate(90)">
      <stop offset="20%" stop-color="gold" />
      <stop offset="90%" stop-color="red" />
    </linearGradient>
  </defs>
  <!-- 通过 <use> 元素引用上面定义的图形对象 -->
  <use x="5" y="5" href="#myCircle" fill="url('#myGradient')" />
</svg>1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
<g> 元素 
<g> 即 group,是一组图形的容器,并可以统一设置所有的图形的 fill stroke 等属性。
html
<svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">
  <!-- 使用 <g> 元素把 2 个 <circle> 组成组,并统一设置样式  -->
  <g fill="white" stroke="green" stroke-width="5" transform="translate(10, 10)">
    <circle cx="40" cy="40" r="25" />
    <circle cx="60" cy="60" r="25" />
  </g>
</svg>1
2
3
4
5
6
7
2
3
4
5
6
7
<g>支持设置fillstrokestroke-widthtransform等 Presentation Attributes。
<use> 元素 
<use> 引用此 SVG 或其他 SVG 文件里的图形并显示出来。
html
<svg viewBox="0 0 10 10" xmlns="http://www.w3.org/2000/svg">
  <!-- 定义图形对象 -->
  <defs>
    <circle id="myCircle" cx="0" cy="0" r="5" />
    <symbol id="mySymbol" viewBox="0 0 1024 1024"> ...... </symbol>
  </defs>
  <!-- 通过 <use> 元素引用上面定义的图形对象,并设置样式(会覆盖被引用图形的样式) -->
  <use href="#myCircle" x="5" y="5" fill="red" />
  <!-- 通过 <use> 元素引用其他 SVG 文件里的图形对象 -->
  <use href="https://xxx.xxx.com/xxx.svg#myCircle" x="5" y="5" transform="scale(2)" />
  
  <!-- 通过 <use> 元素引用 <symbol> 元素,并设置宽和高 -->
  <use href="#mySymbol" x="5" y="5" width="5" height="5" />
</svg>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
href:类似于 HTML<a>的href;x,y:设置引用图形的左上角坐标为(x,y);widthheight:设置引用图形的宽和高;- 另外,
<use>和<g>一样,还可以设置fillstrokestroke-widthtransform等 Presentation Attributes。 
举例说明 
- 我们在 
<defs>定义了一个<rect>当作边框,一个<text>当作数字 5,一个<svg>当作黑色梅花,一个<g>当作红色梅花,一个<path>当作蓝色梅花,一个<linearGradient>用于背景渐变色;- 这些图形都不会显示,而是通过 
id引用它们 <linearGradient>是线性渐变,我们在后面的课程中详细讲解
 - 这些图形都不会显示,而是通过 
 - 然后,我们使用了一个 
<g>图形容器,在它里面使用<use>通过id引用<defs>里的图形、颜色渐变等 
小结 
本节我们使用 <g> <defs> <use> 达到复用图形和组织代码的效果,接下来我们介绍如何使用 <symbol> 元素来达到图形复用的目的。






