Skip to content

Latest commit

 

History

History
72 lines (52 loc) · 2.09 KB

24.SVG-defs元素.md

File metadata and controls

72 lines (52 loc) · 2.09 KB

SVG defs元素


SVG<defs>元素中嵌套了在SVG图片中可重用的定义。例如,你可以将多个SVG图形组织在一起,将其当作一个可重用的图形。

一个defs示例

下面是一个简单的<defs>元素例子:

<svg>
    <defs>
        <g>
            <rect x="100" y="100" width="100" height="100" />
            <circle cx="100" cy="100" r="100" />
        </g>
    </defs>
</svg>

<def>元素内定义的图形不会展示在SVG图片上。必须通过<use>元素来引用。示例如下:

<svg>
  <defs>
    <g id="shape">
        <rect x="50" y="50" width="50" height="50" />
        <circle cx="50" cy="50" r="50" />
    </g>
  </defs>

  <use xlink:href="#shape" x="50" y="50" />
  <use xlink:href="#shape" x="200" y="50" />

</svg>

引用<g>元素前,必须设置其id属性。<use>元素通过xlink:href属性引用<g>元素。请注意属性值ID前面的#

<use>元素通过xy属性指定显示可重用图形的位置。请注意,<g>元素中的图形位于0,0处。这样做是因为它们的位置在<use>元素中指定。

最终图片如下:

<use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#shape" x="50" y="50"></use>
<use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#shape" x="200" y="50"></use>

<circle cx="50" cy="50" r="5" style="fill:#0000ff;"></circle>
<circle cx="200" cy="50" r="5" style="fill:#0000ff;"></circle>

蓝色点不是示例的部分。只是为了显示两个<use>元素的位置。

defs元素内可以定义什么元素?

你可以将下列元素放在<defs>元素内:

  • 任何形状元素(rectline等)
  • g
  • symbol