1、 DEFS元素

SVG的<defs>元素用于预定义一个元素使其能够在SVG图像中重复使用。例如你可以将一些图形制作为一个组,并用<defs>元素来定义它,然后你就可以在SVG图像中将它当做简单图形来重复使用。

<svg>
    <defs >
        <g>
            <rect x="20" y="20" width="50" height="60"></rect>
            <circle x="50" y="50" r="30"></circle>
        </g>
    </defs>
</svg>

<defs>元素中定义的图形不会直接显示在SVG图像上。要显示它们需要使用<use>元素来引入它们

<svg>
    <defs >
        <g id="shape">
            <rect x="50" y="50" width="30" height="30"></rect>
            <circle cx="50" cy="50" r="30"></circle>
            <circle cx="50" cy="50" r="5" style="fill: #27AE60;"></circle>
        </g>
    </defs>
    <use xlink:href="#shape" x="50" y="50" />
</svg>

2、SYMBOL元素

SVG <symbol>元素用于定义可重复使用的符号。嵌入在<symbol>元素中的图形是不会被直接显示的,除非你使用<use>元素来引用它

<svg>
    <symbol id="circle">
        <circle cx="50" cy="50" r="30" style="fill:#1D7DB1"></circle>
    </symbol>
    <use xlink:href="#circle"></use>
</svg>

一个<symbol>元素可以有preserveAspectRatioviewBox属性。而<g>元素不能拥有这些属性。因此相比于在<defs>元素中使用<g>的方式来复用图形,使用<symbol>元素也许是一个更好的选择

3、USE元素

SVG <use>元素可以在SVG图像中多次重用一个预定义的SVG图形,包括<g>元素和<symbol>元素。被重用的图形可以在定义<defs>的内部(图形将不可见直到使用use来引用它)或外部

<svg>
    <defs >
        <g id="shape">
            <rect x="50" y="50" width="30" height="30"></rect>
            <circle cx="50" cy="50" r="30"></circle>
            <circle cx="50" cy="50" r="5" style="fill: #27AE60;"></circle>
        </g>
    </defs>
    <use xlink:href="#shape" x="50" y="50" />
    <use xlink:href="#shape" x="150" y="50" />
</svg> 

 

<svg width="500" height="110">
    <g id="shape2">
        <rect x="0" y="0" width="50" height="50" />
    </g>
    <use xlink:href="#shape2" x="200" y="50" />
</svg>

注:注意这里原始图形和复用的图形都会被显示。因为原始的图形并没有定义在<defs><symbol>元素中。所以它是可见的

可以为引用的图形设置CSS样式。你可以在<use>元素中使用style属性来为复用的图形设置它的样式

<svg>
    <symbol id="circle">
        <circle cx="50" cy="50" r="30"></circle>
    </symbol>
    <use xlink:href="#circle"></use>
    <use xlink:href="#circle" style="fill: #1D7DB1;" x="70"></use>
    <use xlink:href="#circle" style="stroke:#191919;stroke-width: 5;fill: none;" x="150"></use>
</svg>

 

posted on 2015-09-09 16:39  苏荷酒吧  阅读(436)  评论(0)    收藏  举报