SVG基础:可重用元素的定义与应用 - DEFS、SYMBOL与USE
1、 DEFS元素
SVG的**<defs>标签用于预先定义可在整个SVG文档中重复使用的图形组件**。通过将一组图形元素组合起来并在<defs>中定义,您可以在SVG图像中像使用基本图形一样多次引用它们。
<svg>
<defs>
<g>
<rect x="30" y="30" width="60" height="40"></rect>
<ellipse cx="60" cy="50" rx="25" ry="20"></ellipse>
</g>
</defs>
</svg>
在<defs>标签内定义的图形默认情况下不会直接渲染。要显示这些预定义的图形,需要借助<use>元素来引用它们
<svg>
<defs>
<g id="composite-shape">
<rect x="60" y="60" width="40" height="40"></rect>
<polygon points="60,60 100,60 80,100"></polygon>
<circle cx="80" cy="80" r="8" style="fill: #E74C3C;"></circle>
</g>
</defs>
<use xlink:href="#composite-shape" x="70" y="70" />
</svg>
2、SYMBOL元素
SVG <symbol>标签用于创建可复用的图形符号。放置在<symbol>标签内的图形本身不会直接显示,必须通过<use>元素来引用才能显示
<svg>
<symbol id="star">
<polygon points="50,10 61,40 95,40 68,60 79,90 50,70 21,90 32,60 5,40 39,40"
style="fill:#9B59B6"></polygon>
</symbol>
<use xlink:href="#star"></use>
</svg>
<symbol>元素支持preserveAspectRatio和viewBox属性,而<g>元素则不支持。因此,与使用<g>标签创建可复用图形相比,使用<symbol>标签通常更为灵活和强大
3、USE元素
SVG <use>元素允许在SVG文档中多次引用预定义的图形组件,包括<g>组和<symbol>符号。被引用的图形可以定义在<defs>标签内部(直到通过<use>引用前不可见)或外部
<svg>
<defs>
<g id="geometric-pattern">
<rect x="0" y="0" width="40" height="40" fill="#3498DB" />
<circle cx="20" cy="20" r="15" fill="#E74C3C" />
<rect x="10" y="10" width="20" height="20" fill="#F1C40F" />
</g>
</defs>
<use xlink:href="#geometric-pattern" x="50" y="50" />
<use xlink:href="#geometric-pattern" x="150" y="50" />
</svg>
<svg width="400" height="120">
<g id="triangle-shape">
<polygon points="25,0 0,50 50,50" fill="#2ECC71" />
</g>
<use xlink:href="#triangle-shape" x="100" y="30" />
</svg>
注意:原始图形和复制的图形都会被显示。这是因为原始图形并未定义在<defs>或<symbol>标签中,因此它是可见的
可以为引用的图形应用CSS样式。您可以在<use>元素中使用style属性来为复制的图形设置样式
<svg>
<symbol id="hexagon">
<polygon points="50,10 90,30 90,70 50,90 10,70 10,30" />
</symbol>
<use xlink:href="#hexagon"></use>
<use xlink:href="#hexagon" style="fill: #3498DB;" x="120"></use>
<use xlink:href="#hexagon" style="stroke:#2C3E50;stroke-width: 3;fill: none;" x="240"></use>
</svg>