English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

SVG <defs> Element

Das SVG <defs>-Element wird verwendet, um Definitionen zu integrieren, die im SVG-Bild wiederverwendet werden können. Zum Beispiel können Sie SVG-Formen zusammenfassen und sie als eine einzige Form wiederholen.

defs-Beispiel

Dies ist ein einfaches Beispiel für ein <defs>-Element:

<svg>
    <defs>
        <g>
            <rect x="100"y="100"width="100"height="100" />
            <circle cx="100"cy="100"r="100" />
        </g>
    </defs>
</svg>
Test and see‹/›

Formen, die im <defs>-Element definiert sind, werden in SVG-Bildern nicht angezeigt. Sie müssen vor ihrer Anzeige durch ein <use>-Element referenziert werden. Ein Beispiel ist:

<svg width="500"height="100">
    <defs>
        <g id="shape">
            <rect x="0" y="0" width="50"height="50"></rect>
            <circle cx="0" cy="0" r="50"></circle>
        </g>
    </defs>
    <use xlink:href="#shape" x="50"y="50"></use>
    <use 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>
</svg>
Test and see‹/›

Before you can refer to the <g> element, you must set an ID for it through its id attribute. The <use> element references the <g> element through its xlink:href attribute. Note the '#' before the ID in the attribute value.

The <use> element specifies where to display the repeated shape by its x and y attributes. Note that the shapes inside the <g> element are located at 0,0. This is because their positions have been added to the position specified in the <use> element.

Image effect after running:

The blue dot is not in the example. It is added to show the x and y of two <use> elements.

Which elements can be defined within the <defs> element?

You can place the following elements inside the <defs> element:

  • Any shape element (rect, line, etc.)

  • g

  • symbol