【SVG专题】SVG 复用

SVG允许我们定义以后需要重复使用的图形元素。

建议把所有需要再次使用的引用元素定义在defs元素里面。这样做可以增加SVG内容的易读性和无障碍。在defs元素中定义的图形元素不会直接呈现。你可以在你的视口的任意地方利用 use元素呈现这些元素。<use>元素从SVG文档中获取节点,并将它们复制到其他地方。其效果与将这些节点深度克隆到一个不可导出的DOM中,然后粘贴到use元素所在的位置相同,这与克隆的模版元素类似。

  • 示例
1
2
3
4
5
6
7
8
9
10
11
12
13
<svg width="80px" height="30px" viewBox="0 0 80 30"
xmlns="http://www.w3.org/2000/svg">

<defs>
<linearGradient id="Gradient01">
<stop offset="20%" stop-color="#39F" />
<stop offset="90%" stop-color="#F3F" />
</linearGradient>
</defs>

<rect x="10" y="10" width="60" height="10"
fill="url(#Gradient01)" />
</svg>

  • 示例
    1
    2
    3
    4
    5
    6
    <svg viewBox="0 0 30 10" xmlns="http://www.w3.org/2000/svg">
    <circle id="myCircle" cx="5" cy="5" r="4" stroke="blue" />
    <use href="#myCircle" x="10" fill="blue" />
    <!-- stroke="red" 将被忽略,因为描边已在 myCircle 上设置 -->
    <use href="#myCircle" x="20" fill="white" stroke="red" />
    </svg>

  • 示例
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    <svg width="200" height="200" xmlns="http://www.w3.org/2000/svg" version="1.1">
    <defs>
    <style><![CDATA[
    #MyRect {
    stroke: black;
    fill: red;
    }
    ]]></style>
    </defs>
    <rect x="10" height="180" y="10" width="180" id="MyRect"/>
    </svg>