SVG 急速入门教程(12.<defs><g><use>元素)

547 阅读2分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第1天,点击查看活动详情

上一篇:变换(transform)

就像编程时,我们使用 function class 等语言特性,来组织代码、复用代码;类似的,SVG 也支持代码结构化、代码复用等。

本节我们介绍如何使用 <defs> <g> <use> 元素实现代码复用。

1. <defs> 元素

defs 的意思是 definitions,即许多图形、渐变颜色等定义的集合。在 <defs> 里的图形都不会显示,而是在其他地方被引用。

<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>

2. <g> 元素

<g> 元素的全名是 group,是一组图形的容器,并可以统一设置所有的图形的 fill stroke 等属性。

<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>

3. <use> 元素

<use> 引用此 SVG 或其他 SVG 文件里的图形并显示出来。

<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>
  • href:类似于 HTML <a> 的 href
  • x,y:设置引用图形的左上角坐标为 (x,y) ;
  • width height:设置引用图形的宽和高;
  • 另外,<use> 和 <g> 一样,还可以设置 fill stroke stroke-width transform 等 Presentation Attributes

4. 举例说明

  • 我们在 <defs> 定义了一个 <rect> 当作边框,一个 <text> 当作数字 5,一个 <svg> 当作黑色梅花,一个 <g> 当作红色梅花,一个 <path> 当作蓝色梅花,一个 <linearGradient> 用于背景渐变色;

    • 这些图形都不会显示,而是通过 id 引用它们
    • <linearGradient> 是线性渐变,我们在后面的课程中详细讲解
  • 然后,我们使用了一个 <g> 图形容器,在它里面使用 <use> 通过 id 引用 <defs>里的图形、颜色渐变等

5. 小结

本节我们使用 <g> <defs> <use> 达到复用图形和组织代码的效果,接下来我们介绍如何使用 <symbol> 元素来达到图形复用的目的。

下一篇:symbol 元素