Grundstruktur
SVG-Dokument-Gerüst
Das xmlns-Attribut deklariert den SVG-Namensraum. width/height setzen die gerenderte Größe in Pixeln. viewBox definiert das interne Koordinatensystem. SVG kann eine eigenständige .svg-Datei oder inline in HTML eingebettet sein, wo die XML-Deklaration und xmlns optional sind.
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg"
width="200" height="200"
viewBox="0 0 200 200">
<!-- SVG content goes here -->
<rect x="0" y="0" width="200" height="200" fill="#eee"/>
</svg>SVG in HTML einbetten
Inline-SVG ist am flexibelsten — du kannst es mit CSS stylen und mit JS skripten wie HTML. <img> und background-image behandeln SVG als statisches Bild (kein internes CSS/JS). <object> lädt es als eigenes Dokument mit eigenem DOM und erlaubt etwas Skripting.
<!-- 1. Inline (best for styling and scripting) -->
<svg width="100" height="100">
<circle cx="50" cy="50" r="40" fill="red"/>
</svg>
<!-- 2. As an image (no CSS/JS interaction) -->
<img src="icon.svg" alt="Icon" width="100" height="100">
<!-- 3. As a background (limited styling) -->
<div style="background: url('icon.svg') no-repeat;"></div>
<!-- 4. Via object/embed (allows scripting) -->
<object data="icon.svg" type="image/svg+xml"></object>Koordinatensystem
SVG nutzt ein linkshändiges Koordinatensystem: Ursprung oben links, X nach rechts, Y nach unten. Das viewBox-Attribut definiert den internen Koordinatenraum — SVG skaliert Inhalte auf die width/height des Elements, ein viewBox von 0 0 100 100 in einem 200px-Element rendert also alles mit 2x.
<svg width="200" height="100" viewBox="0 0 200 100">
<!-- Origin (0,0) is top-left, like Canvas -->
<!-- X increases rightward, Y increases downward -->
<!-- A point at (50, 25) -->
<circle cx="50" cy="25" r="3" fill="black"/>
<!-- The viewBox stretches content to fill width/height -->
<!-- viewBox="minX minY width height" -->
</svg>
<!-- viewBox 0 0 100 100 in a 200x200 element = 2x zoom -->
<svg width="200" height="200" viewBox="0 0 100 100">
<circle cx="50" cy="50" r="50" fill="blue"/>
</svg>Breite, Höhe & Einheiten
Nutzereinheiten (ohne Suffix) entsprechen px. Prozentwerte sind relativ zum Parent. Für responsives SVG width/height weglassen und viewBox setzen — das SVG skaliert auf seinen Container und erhält das Seitenverhältnis. 'auto' bei height mit einem viewBox hält die Proportionen.
<svg width="200" height="100">
<!-- Default unit is the user unit (px equivalent) -->
</svg>
<!-- Common units: px, em, %, pt, cm, mm, in -->
<svg width="50%" height="auto" viewBox="0 0 100 100">
<!-- % is relative to the parent element -->
</svg>
<!-- No width/height + viewBox = fully responsive -->
<svg viewBox="0 0 100 100" style="width:100%;height:auto;">
<!-- Scales to container, preserves aspect ratio -->
</svg>Namensräume & xlink
SVG 2 führte direkte href-Unterstützung auf <use>, <image> und <a> ein und veraltet xlink:href. Moderne Browser unterstützen plain href. Den xlink-Namensraum nur halten, wenn sehr alte Browser unterstützt werden müssen. Inline-SVG in HTML braucht das xmlns-Attribut streng genommen nicht.
<svg xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink">
<!-- Modern SVG 2: use href directly -->
<use href="#icon"/>
<!-- Legacy SVG 1.1: use xlink:href -->
<use xlink:href="#icon"/>
</svg>
<!-- In HTML5 inline SVG, the xmlns is optional -->
<!-- But xlink namespace is needed if you use xlink:href -->Kommentare & Metadaten
<title> und <desc> liefern Barrierefreiheitstexte, die Screenreader vorlesen — für bedeutungsvolle SVGs immer einschließen. <metadata> hält strukturierte Daten (RDF, Dublin Core) für Tooling. Kommentare nutzen dieselbe <!-- -->-Syntax wie HTML.
<svg width="100" height="100" viewBox="0 0 100 100">
<!-- This is an XML comment (same as HTML) -->
<!-- Metadata is hidden from rendering -->
<metadata>
<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
<dc:title xmlns:dc="http://purl.org/dc/elements/1.1/">My Icon</dc:title>
</rdf:RDF>
</metadata>
<!-- title and desc for accessibility -->
<title>Shopping Cart Icon</title>
<desc>A red shopping cart with 3 items</desc>
<circle cx="50" cy="50" r="40" fill="red"/>
</svg>Formen
Rechteck (rect)
rect verlangt x, y, width, height. rx/ry erzeugen abgerundete Ecken (ist nur rx gesetzt, übernimmt ry den Wert von rx). fill='none' macht das Innere transparent. stroke-width ist auf der Kante zentriert, die Hälfte ragt also außerhalb der Geometrie.
<svg width="200" height="100" viewBox="0 0 200 100">
<!-- Basic rectangle -->
<rect x="10" y="10" width="80" height="50" fill="steelblue"/>
<!-- Rounded corners -->
<rect x="110" y="10" width="80" height="50"
rx="10" ry="10" fill="tomato"/>
<!-- Stroked, no fill -->
<rect x="10" y="70" width="80" height="20"
fill="none" stroke="black" stroke-width="2"/>
</svg>Kreis & Ellipse
circle ist durch Zentrum (cx, cy) und Radius r definiert. ellipse hat getrennte rx und ry zum Strecken. Beide setzen cx/cy bei Fehlen auf 0. Anders als rect können Kreise/Ellipsen keine abgerundeten Ecken haben — sie sind bereits gekrümmt.
<svg width="200" height="120" viewBox="0 0 200 120">
<!-- circle: cx, cy (center), r (radius) -->
<circle cx="50" cy="60" r="40" fill="gold"/>
<!-- ellipse: cx, cy, rx (x radius), ry (y radius) -->
<ellipse cx="150" cy="60" rx="50" ry="30" fill="mediumpurple"/>
<!-- Circle as an ellipse (rx == ry) -->
<ellipse cx="100" cy="20" rx="15" ry="15" fill="black"/>
</svg>Linie
line verbindet zwei Punkte. Sie hat kein fill (nur stroke). stroke-dasharray erzeugt gestrichelte Linien — das Muster ist 'Strichlänge,Lückenlänge', wiederholt. stroke-linecap (butt, round, square) steuert die Endkappen.
<svg width="200" height="100" viewBox="0 0 200 100">
<!-- line: x1,y1 (start) to x2,y2 (end) -->
<line x1="10" y1="10" x2="190" y2="10" stroke="black" stroke-width="2"/>
<!-- Diagonal line -->
<line x1="10" y1="90" x2="190" y2="10" stroke="red" stroke-width="3"/>
<!-- Dashed line -->
<line x1="10" y1="50" x2="190" y2="50"
stroke="blue" stroke-width="2" stroke-dasharray="10,5"/>
</svg>Polyline & Polygon
polyline zeichnet verbundene Liniensegmente, ohne die Form zu schließen (fill greift, als wäre geschlossen, aber kein stroke verbindet die Enden). polygon schließt automatisch, indem es den letzten Punkt mit dem ersten verbindet. points ist eine leer- oder kommaseparierte Liste von x,y-Paaren.
<svg width="200" height="120" viewBox="0 0 200 120">
<!-- polyline: open shape (no auto-close) -->
<polyline points="10,10 50,90 100,10 150,90 190,10"
fill="none" stroke="green" stroke-width="2"/>
<!-- polygon: closed shape (auto-connects last to first) -->
<polygon points="100,10 190,110 10,110"
fill="lime" stroke="black" stroke-width="1"/>
<!-- Star (polygon with 10 points) -->
<polygon points="50,5 61,38 95,38 67,58 78,90 50,70 22,90 33,58 5,38 39,38"
fill="gold" stroke="orange"/>
</svg>Häufige Formattribute
fill und stroke sind die beiden Haupt-Farbeigenschaften. opacity betrifft das ganze Element; fill-opacity und stroke-opacity wirken unabhängig. stroke-linecap (butt/round/square) formt Linienenden; stroke-linejoin (miter/round/bevel) formt Ecken.
<svg width="200" height="100" viewBox="0 0 200 100">
<rect x="10" y="10" width="80" height="80"
fill="#3498db"
fill-opacity="0.5"
stroke="#2c3e50"
stroke-width="3"
stroke-opacity="0.8"
stroke-dasharray="5,3"
stroke-linecap="round"
stroke-linejoin="round"
opacity="0.9"/>
<!-- opacity affects the whole element -->
<!-- fill-opacity/stroke-opacity affect parts independently -->
</svg>Füllregeln (evenodd)
fill-rule bestimmt, wie sich überlappende Regionen einer Form füllen. 'nonzero' (Standard) füllt nach Umlaufrichtung. 'evenodd' füllt Regionen, die eine ungerade Anzahl von Malen umschlossen werden — das erzeugt den klassischen 'Donut-Loch'-Effekt bei sich selbst schneidenden Pfaden und konzentrischen Polygonen.
<svg width="200" height="100" viewBox="0 0 200 100">
<!-- Default fill-rule: nonzero -->
<polygon points="50,10 90,90 10,90 50,30 80,80 20,80"
fill="red" fill-rule="nonzero"/>
<!-- fill-rule: evenodd creates holes in overlapping shapes -->
<polygon points="150,10 190,90 110,90 150,30 180,80 120,80"
fill="blue" fill-rule="evenodd"/>
</svg>Path
Path-Befehle im Überblick
Das <path>-Element ist die mächtigste SVG-Form — sein d-Attribut hält einen String aus Zeichenbefehlen. Großbuchstaben-Befehle nutzen absolute Koordinaten; Kleinbuchstaben Koordinaten relativ zur aktuellen Stiftposition. M, L, C, Q, A, Z sind die Kernbefehle.
<svg width="200" height="100" viewBox="0 0 200 100">
<!-- The d attribute contains all path commands -->
<path d="M 10 10 L 190 10 L 100 90 Z" fill="none" stroke="black"/>
<!-- Uppercase = absolute, lowercase = relative -->
<!-- M = moveto (lift pen, move) -->
<!-- L = lineto (draw straight line) -->
<!-- H = horizontal lineto, V = vertical lineto -->
<!-- C = cubic bezier, S = smooth cubic -->
<!-- Q = quadratic bezier, T = smooth quadratic -->
<!-- A = arc, Z = closepath -->
</svg>M, L, H, V, Z (Linien)
M bewegt den Stift, ohne zu zeichnen. L zeichnet zu einem Punkt. H/V zeichnen horizontale/vertikale Linien (eine Koordinate). Z schließt den Pfad zum Start zurück. Die Kleinbuchstaben-Versionen (l, h, v, z) interpretieren Koordinaten als Versatz von der aktuellen Position — Teilpfade werden so wiederverwendbar.
<svg width="200" height="120" viewBox="0 0 200 120">
<!-- M = moveto, L = lineto, Z = close path -->
<path d="M 10 10 L 190 10 L 190 110 L 10 110 Z"
fill="none" stroke="black"/>
<!-- H = horizontal line, V = vertical line (one coord each) -->
<path d="M 10 60 H 190" stroke="red"/>
<!-- Relative commands (lowercase): coords are offsets -->
<path d="M 10 80 l 30 -20 l 30 20 l 30 -20 l 30 20"
fill="none" stroke="blue"/>
<!-- Multiple M's create subpaths (disconnected segments) -->
<path d="M 10 100 L 50 100 M 100 100 L 150 100" stroke="green"/>
</svg>C & S (Kubische Bezier)
C zeichnet eine kubische Bezier mit zwei Kontrollpunkten, die die Kurve ziehen. Der erste Kontrollpunkt (x1,y1) wirkt auf die Starttangente; der zweite (x2,y2) auf die Endtangente. S setzt glatt fort, indem es den zweiten Kontrollpunkt der vorherigen Kurve spiegelt — nur der neue zweite Kontrollpunkt und Endpunkt werden angegeben.
<svg width="240" height="120" viewBox="0 0 240 120">
<!-- C = cubic bezier: two control points + endpoint -->
<!-- C x1 y1, x2 y2, x y -->
<path d="M 10 60 C 60 10, 180 110, 230 60"
fill="none" stroke="red" stroke-width="2"/>
<!-- S = smooth cubic: control point mirrors the previous -->
<!-- S x2 y2, x y (first control point is auto-mirrored) -->
<path d="M 10 100 C 60 50, 100 50, 120 100 S 200 150, 230 100"
fill="none" stroke="blue" stroke-width="2"/>
<!-- Multiple cubics in one path -->
<path d="M 10 20 C 40 0, 70 40, 100 20 C 130 0, 160 40, 190 20"
fill="none" stroke="green"/>
</svg>Q & T (Quadratische Bezier)
Q nutzt einen Kontrollpunkt statt zweier — einfacher, aber weniger flexibel als C. T setzt ein Q glatt fort, indem es seinen Kontrollpunkt spiegelt, und verlangt nur den Endpunkt. Quadratische Kurven sind üblich bei Schriftglyphen und einfachen Icon-Pfaden, wo ein Kontrollpunkt genügt.
<svg width="200" height="120" viewBox="0 0 200 120">
<!-- Q = quadratic bezier: one control point + endpoint -->
<!-- Q x1 y1, x y -->
<path d="M 10 100 Q 100 0, 190 100"
fill="none" stroke="purple" stroke-width="2"/>
<!-- T = smooth quadratic: control point auto-mirrored -->
<path d="M 10 60 Q 50 20, 90 60 T 170 60"
fill="none" stroke="orange" stroke-width="2"/>
<!-- Q is simpler than C but less precise — good for curves -->
<!-- with a single bend, like basic arcs and waves -->
</svg>A (Bogen)
A zeichnet einen elliptischen Bogen. rx, ry sind die Radien; x-rotation kippt die Ellipse. large-arc-flag (0/1) wählt den kürzeren oder längeren Bogen zwischen den Punkten. sweep-flag (0/1) wählt gegen oder im Uhrzeigersinn. Bögen sind knifflig — viele Designer nutzen stattdessen C-Kurven für Vorhersagbarkeit.
<svg width="200" height="150" viewBox="0 0 200 150">
<!-- A rx ry, x-rotation, large-arc-flag, sweep-flag, x y -->
<path d="M 10 75 A 60 60, 0, 0, 1, 130 75"
fill="none" stroke="red" stroke-width="2"/>
<!-- large-arc-flag: 0 = small arc, 1 = large arc -->
<!-- sweep-flag: 0 = counterclockwise, 1 = clockwise -->
<!-- Large arc (the long way around) -->
<path d="M 10 75 A 60 60, 0, 1, 1, 130 75"
fill="none" stroke="blue" stroke-width="2"/>
<!-- Elliptical arc (rx != ry) -->
<path d="M 10 120 A 80 30, 0, 0, 0, 170 120"
fill="none" stroke="green" stroke-width="2"/>
</svg>Praktische Path-Beispiele
Echte Icons kombinieren M, L, C und Z, um Formen nachzuziehen. Das Herz nutzt kubische Beziers für glatte Kurven. Das Häkchen sind nur drei Punkte mit runden Linienkappen. Die Sprechblase mischt H/V-Linien für das Rechteck und L-Befehle für den Schwanz. Einfach beginnen, dann Kontrollpunkte verfeinern.
<svg width="200" height="120" viewBox="0 0 200 120">
<!-- Heart shape -->
<path d="M 100 30
C 70 0, 20 20, 20 60
C 20 90, 60 110, 100 120
C 140 110, 180 90, 180 60
C 180 20, 130 0, 100 30 Z"
fill="red"/>
<!-- Checkmark -->
<path d="M 20 60 L 50 90 L 100 20"
fill="none" stroke="green" stroke-width="6"
stroke-linecap="round" stroke-linejoin="round"/>
<!-- Speech bubble (combines lines and curves) -->
<path d="M 20 20 H 180 V 80 H 60 L 40 100 L 45 80 H 20 Z"
fill="lightblue" stroke="navy"/>
</svg>Text
Einfacher Text
Die y-Koordinate verweist standardmäßig auf die Textgrundlinie, nicht auf den oberen Rand. text-anchor (start/middle/end) steuert die horizontale Ausrichtung relativ zu x. dominant-baseline (auto/middle/hanging/...) steuert die vertikale Ausrichtung. Beide sind essenziell, um Text zu zentrieren.
<svg width="200" height="100" viewBox="0 0 200 100">
<text x="10" y="50" font-family="Arial" font-size="24"
fill="black">Hello SVG!</text>
<!-- x, y sets the baseline position (y is the text baseline) -->
<!-- Use dominant-baseline to change the vertical anchor -->
<text x="100" y="50" font-size="20" fill="blue"
text-anchor="middle" dominant-baseline="middle">Centered</text>
</svg>Text-Styling
SVG-Text unterstützt die meisten CSS-Schrifteigenschaften als Attribute. font-family akzeptiert Standard-Schriftstapel. stroke auf Text zeichnet eine Kontur — eine kleine stroke-width nutzen, damit das fill nicht verdeckt wird. letter-spacing und word-spacing funktionieren wie in CSS.
<svg width="300" height="120" viewBox="0 0 300 120">
<text x="10" y="30"
font-family="Georgia, serif"
font-size="28"
font-weight="bold"
font-style="italic"
fill="darkblue"
stroke="navy"
stroke-width="0.5"
text-decoration="underline"
letter-spacing="2">Styled Text</text>
<!-- font-family uses CSS font stacks -->
<!-- font-weight: normal, bold, 100-900 -->
<!-- font-style: normal, italic, oblique -->
</svg>tspan (Teiltext)
<tspan> erlaubt es, Textteile unterschiedlich zu stylen oder zu positionieren — wie <span> in HTML. dx/dy versetzen relativ zum vorherigen Zeichen; absolute x/y springen an eine neue Position (x mit dem Originalwert nutzen und dy für Zeilenumbrüche). tspan ist der Weg, mehrzeiligen Text in SVG zu bauen.
<svg width="300" height="100" viewBox="0 0 300 100">
<text x="10" y="50" font-size="20" fill="black">
<tspan font-weight="bold" fill="red">Bold red</tspan>
<tspan dx="10" font-style="italic">italic</tspan>
<tspan x="10" dy="30">New line via dy</tspan>
<tspan dx="10" font-size="14">smaller</tspan>
</text>
<!-- dx/dy: relative offset from previous position -->
<!-- x/y: absolute position (useful for line breaks) -->
</svg>Text auf einem Pfad
<textPath> rendert Text entlang eines beliebigen Pfad-Elements. Den Pfad per id referenzieren über href (modern) oder xlink:href (Legacy). startOffset (eine Länge oder ein Prozentsatz) positioniert den Text entlang des Pfads. Die Standardtechnik für gekrümmte Labels auf Bögen, Kreisen oder eigenen Formen.
<svg width="300" height="150" viewBox="0 0 300 150">
<!-- Define a path (can be invisible) -->
<defs>
<path id="curve" d="M 20 100 Q 150 0, 280 100" fill="none"/>
</defs>
<!-- Text follows the path via xlink:href / href -->
<text font-size="20" fill="purple">
<textPath href="#curve">Text along a curved path!</textPath>
</text>
<!-- startOffset shifts where the text begins on the path -->
<text font-size="14" fill="gray">
<textPath href="#curve" startOffset="50%" text-anchor="middle">
Centered on path
</textPath>
</text>
</svg>Schreibmodus & Richtung
writing-mode='tb' lässt Text von oben nach unten fließen (üblich in ostasiatischer Typografie). direction='rtl' kehrt die Zeichenreihenfolge für rechts-nach-links-Schriften um. Für beliebige Rotation das transform-Attribut nutzen — rotate(angle, cx, cy) rotiert um den Punkt (cx, cy).
<svg width="200" height="200" viewBox="0 0 200 200">
<!-- Vertical text (top-to-bottom) -->
<text x="50" y="20" writing-mode="tb" font-size="20">Vertical</text>
<!-- Right-to-left text -->
<text x="190" y="100" direction="rtl" font-size="20"
text-anchor="end">RTL text</text>
<!-- Rotated text (via transform) -->
<text x="100" y="100" font-size="20"
transform="rotate(45, 100, 100)">Rotated 45°</text>
</svg>Text-Barrierefreiheit
SVG-Text ist standardmäßig auswählbar und zugänglich, aber dekoratives SVG sollte <title> und <desc> haben. Für inline SVG als UI-Elemente role='img' und aria-label ergänzen, damit Screenreader die Bedeutung ansagen. Essenzielle Information nie nur in SVG-Text legen — HTML-Text ist zugänglicher.
<svg width="200" height="80" viewBox="0 0 200 80">
<title>Error Icon</title>
<desc>A red circle with a white exclamation mark</desc>
<!-- role and aria-label for screen readers -->
<text role="img" aria-label="Error: 3 items need attention"
x="100" y="45" text-anchor="middle"
font-size="24" fill="red">! Error</text>
</svg>Verläufe
Linearer Verlauf
linearGradient überblendet Farben entlang einer Linie. x1/y1 bis x2/y2 definieren die Richtung (0 % 0 % bis 100 % 0 % ist links nach rechts). <stop>-Elemente definieren Farbpunkte; offset ist 0-100 % oder 0-1. Den Verlauf mit fill='url(#id)' referenzieren. Verläufe müssen in <defs> liegen.
<svg width="200" height="100" viewBox="0 0 200 100">
<defs>
<linearGradient id="grad1" x1="0%" y1="0%" x2="100%" y2="0%">
<stop offset="0%" stop-color="red"/>
<stop offset="50%" stop-color="yellow"/>
<stop offset="100%" stop-color="green"/>
</linearGradient>
</defs>
<rect x="10" y="10" width="180" height="80" fill="url(#grad1)"/>
</svg>Radialer Verlauf
radialGradient strahlt von einem Zentrum aus. cx/cy ist das Zentrum, r der Radius. fx/fy ist der Fokuspunkt (wo die 0-%-Farbe beginnt) — ein Versatz erzeugt einen gerichteten Lichteffekt. Defaults: cx/cy bei 50 %, r bei 50 %, fx/fy spiegeln cx/cy.
<svg width="200" height="200" viewBox="0 0 200 200">
<defs>
<radialGradient id="grad2" cx="50%" cy="50%" r="50%" fx="50%" fy="50%">
<stop offset="0%" stop-color="white"/>
<stop offset="50%" stop-color="orange"/>
<stop offset="100%" stop-color="darkred"/>
</radialGradient>
</defs>
<circle cx="100" cy="100" r="90" fill="url(#grad2)"/>
</svg>Verlaufseinheiten & Ausbreitung
gradientUnits='objectBoundingBox' (Standard) macht Koordinaten relativ zu jeder Form (0-1), derselbe Verlauf passt also auf jedes Element. 'userSpaceOnUse' nutzt absolute SVG-Koordinaten, der Verlauf ist also im Dokument positioniert — nützlich, um Verläufe über mehrere Formen hinweg auszurichten.
<svg width="300" height="100" viewBox="0 0 300 100">
<defs>
<!-- objectBoundingBox (default): coords are 0-1 relative to the shape -->
<linearGradient id="g1" x1="0" y1="0" x2="1" y2="0">
<stop offset="0" stop-color="blue"/>
<stop offset="1" stop-color="cyan"/>
</linearGradient>
<!-- userSpaceOnUse: coords are in the SVG's user units -->
<linearGradient id="g2" x1="0" y1="0" x2="200" y2="0"
gradientUnits="userSpaceOnUse">
<stop offset="0" stop-color="red"/>
<stop offset="1" stop-color="yellow"/>
</linearGradient>
<!-- spreadMethod: pad (default), reflect, repeat -->
<linearGradient id="g3" x1="0" y1="0" x2="0.3" y2="0"
spreadMethod="repeat">
<stop offset="0" stop-color="green"/>
<stop offset="1" stop-color="lime"/>
</linearGradient>
</defs>
<rect width="100" height="100" x="0" fill="url(#g1)"/>
<rect width="100" height="100" x="100" fill="url(#g2)"/>
<rect width="100" height="100" x="200" fill="url(#g3)"/>
</svg>Stop-Deckkraft & mehrere Stops
Jeder Stop kann stop-opacity (0-1) für Transparenzübergänge haben. Viele Stops kombinieren für komplexe Farbrampen. Dieser Sonnenuntergangsverlauf blendet von transparentem Blau oben zu deckendem Dunkelrot unten — eine übliche Technik für atmosphärische Hintergründe.
<svg width="200" height="200" viewBox="0 0 200 200">
<defs>
<linearGradient id="sunset" x1="0" y1="0" x2="0" y2="1">
<stop offset="0%" stop-color="deepskyblue" stop-opacity="0"/>
<stop offset="40%" stop-color="orange" stop-opacity="0.8"/>
<stop offset="70%" stop-color="orangered"/>
<stop offset="100%" stop-color="darkred"/>
</linearGradient>
</defs>
<rect width="200" height="200" fill="url(#sunset)"/>
</svg>Verläufe wiederverwenden
Einen Verlauf einmal in <defs> definieren und auf beliebig vielen Formen via fill='url(#id)' referenzieren. href nutzen, um aus einem bestehenden Verlauf einen neuen abzuleiten, wobei nur manche Attribute überschrieben werden (etwa die Richtung). Das hält dein SVG DRY und verkleinert die Datei.
<svg width="300" height="100" viewBox="0 0 300 100">
<defs>
<!-- A reusable gradient -->
<linearGradient id="metal" x1="0" y1="0" x2="0" y2="1">
<stop offset="0%" stop-color="#eee"/>
<stop offset="50%" stop-color="#999"/>
<stop offset="100%" stop-color="#333"/>
</linearGradient>
<!-- Gradient referencing another via href -->
<linearGradient id="metal-horizontal" href="#metal"
x1="0" y1="0" x2="1" y2="0"/>
</defs>
<!-- Same gradient on multiple shapes -->
<rect x="10" y="10" width="80" height="80" fill="url(#metal)"/>
<circle cx="150" cy="50" r="40" fill="url(#metal)"/>
<rect x="210" y="10" width="80" height="80" fill="url(#metal-horizontal)"/>
</svg>Muster
Einfaches Muster
Ein <pattern> kachelt eine sich wiederholende Grafik. Die Kinder des Musters definieren eine Kachel; width/height setzen die Kachelgröße. patternUnits='userSpaceOnUse' (empfohlen) heißt, die Kacheldimensionen sind in SVG-Nutzereinheiten, unabhängig von der gefüllten Form. Referenz mit fill='url(#id)'.
<svg width="200" height="200" viewBox="0 0 200 200">
<defs>
<pattern id="dots" x="0" y="0" width="20" height="20"
patternUnits="userSpaceOnUse">
<circle cx="10" cy="10" r="3" fill="steelblue"/>
</pattern>
</defs>
<rect width="200" height="200" fill="url(#dots)"/>
</svg>Muster-Einheiten
patternUnits='objectBoundingBox' (Standard) bemisst Kacheln als Bruchteil der Form — das Muster skaliert mit jeder Form. 'userSpaceOnUse' nutzt absolute Einheiten, das Muster ist also über Formen hinweg konsistent, egal welche Größe. Die meisten realen Muster nutzen userSpaceOnUse.
<svg width="300" height="100" viewBox="0 0 300 100">
<defs>
<!-- objectBoundingBox (default): tile size is relative to shape -->
<!-- 0.1 = 10% of the shape's width/height -->
<pattern id="p1" width="0.1" height="0.1">
<rect width="10" height="10" fill="red" opacity="0.5"/>
</pattern>
<!-- userSpaceOnUse: tile size is in SVG units -->
<pattern id="p2" width="20" height="20"
patternUnits="userSpaceOnUse">
<rect width="10" height="10" fill="blue" opacity="0.5"/>
</pattern>
</defs>
<rect width="150" height="100" fill="url(#p1)"/>
<rect x="150" width="150" height="100" fill="url(#p2)"/>
</svg>Streifen & Schachbrett
patternTransform rotiert, skaliert oder schert das gesamte Muster. Für Streifen eine halbe Kachel in einer Farbe füllen, die andere in einer anderen, dann rotieren. Das Schachbrett nutzt vier Rechtecke (oder zwei L-förmige Paare) pro Kachel. Diese Muster sind häufig in Diagrammen und Texturen.
<svg width="200" height="200" viewBox="0 0 200 200">
<defs>
<!-- Diagonal stripes -->
<pattern id="stripes" width="20" height="20"
patternUnits="userSpaceOnUse"
patternTransform="rotate(45)">
<rect width="20" height="10" fill="gold"/>
<rect y="10" width="20" height="10" fill="black"/>
</pattern>
<!-- Checkerboard -->
<pattern id="checker" width="40" height="40"
patternUnits="userSpaceOnUse">
<rect width="40" height="40" fill="white"/>
<rect width="20" height="20" fill="black"/>
<rect x="20" y="20" width="20" height="20" fill="black"/>
</pattern>
</defs>
<rect width="100" height="200" fill="url(#stripes)"/>
<rect x="100" width="100" height="200" fill="url(#checker)"/>
</svg>Muster-Inhaltseinheiten
patternContentUnits steuert das Koordinatensystem für die Kindelemente des Musters (nicht die Kachelgröße). 'objectBoundingBox' macht die Koordinaten der Kinder Bruchteile der Form — nützlich, wenn Musterdetails proportional mit jeder Form skalieren sollen. Selten, aber mächtig.
<svg width="200" height="200" viewBox="0 0 200 200">
<defs>
<!-- patternContentUnits: how the pattern's children are measured -->
<!-- userSpaceOnUse (default): children use SVG units -->
<!-- objectBoundingBox: children are relative to the shape -->
<pattern id="pb" width="0.25" height="0.25"
patternContentUnits="objectBoundingBox">
<circle cx="0.125" cy="0.125" r="0.05" fill="green"/>
</pattern>
</defs>
<!-- The dots scale with each shape's bounding box -->
<rect width="100" height="100" fill="url(#pb)"/>
<rect x="100" width="100" height="200" fill="url(#pb)"/>
</svg>Verschachtelte Muster
Muster können Verläufe, andere Muster oder beliebigen SVG-Inhalt enthalten. Dieses Rastermuster füllt jede Zelle mit einem dezenten Verlauf und zeichnet oben Rasterlinien. Verschachtelung erlaubt komplexe Texturen. Kachelgrößen vernünftig halten, um Performance-Probleme bei sehr kleinen Kacheln zu vermeiden.
<svg width="200" height="200" viewBox="0 0 200 200">
<defs>
<!-- A pattern can reference another pattern or gradient -->
<pattern id="grid" width="40" height="40"
patternUnits="userSpaceOnUse">
<rect width="40" height="40" fill="url(#cellGrad)"/>
<path d="M 40 0 L 0 0 0 40" fill="none" stroke="#ccc"/>
</pattern>
<linearGradient id="cellGrad">
<stop offset="0" stop-color="#f0f8ff"/>
<stop offset="1" stop-color="#e0e0ff"/>
</linearGradient>
</defs>
<rect width="200" height="200" fill="url(#grid)"/>
</svg>Transform
Translate
translate(tx, ty) verschiebt ein Element um tx, ty. Fehlt ty, ist der Default 0. Die Transformation gilt für das Koordinatensystem des Elements, x/y-Attribute sind also relativ zum verschobenen Ursprung. CSS-Transforms (via style) funktionieren bei inline SVG in modernen Browsern und lassen sich mit CSS-Übergängen animieren.
<svg width="200" height="100" viewBox="0 0 200 100">
<!-- Original -->
<rect x="10" y="10" width="40" height="40" fill="red"/>
<!-- Translated 80px right -->
<rect x="10" y="10" width="40" height="40" fill="blue"
transform="translate(80, 0)"/>
<!-- translate with one arg moves only horizontally -->
<rect x="10" y="10" width="40" height="40" fill="green"
transform="translate(0, 50)"/>
<!-- Equivalent in CSS (for inline SVG in HTML) -->
<rect x="10" y="10" width="40" height="40" fill="orange"
style="transform: translate(150px, 0);"/>
</svg>Rotate
rotate(angle, cx, cy) rotiert um angle Grad um den Punkt (cx, cy). Ohne cx/cy rotiert er um den Ursprung (0,0) — oft nicht gewollt. Winkel sind im Uhrzeigersinn (positiv) oder dagegen (negativ). Das Zentrum immer angeben, um ein Element an Ort und Stelle zu drehen.
<svg width="200" height="200" viewBox="0 0 200 200">
<rect x="50" y="50" width="100" height="20" fill="red"/>
<!-- rotate(angle) around origin (0,0) -->
<rect x="50" y="50" width="100" height="20" fill="blue"
transform="rotate(45)"/>
<!-- rotate(angle, cx, cy) around point (cx, cy) -->
<rect x="50" y="50" width="100" height="20" fill="green"
transform="rotate(45, 100, 60)"/>
<!-- Negative angles rotate counterclockwise -->
<rect x="50" y="50" width="100" height="20" fill="orange"
transform="rotate(-30, 100, 60)"/>
</svg>Scale & Skew
scale(sx, sy) multipliziert Dimensionen; ein Argument skaliert beide gleich. Skalieren wirkt auch auf stroke-width und Positionen. skewX/skewY scheren das Element entlang einer Achse um einen Winkel. Alle Transforms sind relativ zum Ursprung (0,0) — eine Form bei x=100 zu skalieren bewegt sie also auch.
<svg width="200" height="200" viewBox="0 0 200 200">
<!-- Original square -->
<rect x="10" y="10" width="50" height="50" fill="red"/>
<!-- scale(2): 2x in both dimensions -->
<rect x="10" y="10" width="50" height="50" fill="blue"
transform="scale(2)"/>
<!-- scale(sx, sy): different x and y scaling -->
<rect x="10" y="10" width="50" height="50" fill="green"
transform="scale(1, 2)"/>
<!-- skewX / skewY: shear the shape -->
<rect x="10" y="10" width="50" height="50" fill="orange"
transform="skewX(30)"/>
</svg>Matrix-Transform
matrix(a,b,c,d,e,f) ist die zugrunde liegende Form aller Transforms. a,d skalieren; b,c scheren; e,f verschieben. Die meisten Entwickler nutzen die benannten Transforms (translate, rotate usw.) für Lesbarkeit, aber matrix ist, was Tools ausgeben, und nützlich zum Kombinieren oder Parsen.
<svg width="200" height="200" viewBox="0 0 200 200">
<!-- transform="matrix(a, b, c, d, e, f)" -->
<!-- Represents: [a c e] [b d f] [0 0 1] -->
<!-- New x = a*x + c*y + e -->
<!-- New y = b*x + d*y + f -->
<!-- Identity (no change) -->
<rect width="50" height="50" fill="red" transform="matrix(1,0,0,1,0,0)"/>
<!-- Translate (100, 50) -->
<rect width="50" height="50" fill="blue" transform="matrix(1,0,0,1,100,50)"/>
<!-- Scale 2x and translate -->
<rect width="50" height="50" fill="green" transform="matrix(2,0,0,2,50,0)"/>
</svg>Transforms kombinieren
Mehrere Transforms im Attribut gelten von rechts nach links (der rechteste zuerst). Das heißt 'translate(100,100) rotate(45)' rotiert die Form zuerst um ihren eigenen Ursprung und verschiebt sie dann — meist das Gewollte. CSS-Transforms mit transform-origin sind bei inline SVG oft intuitiver.
<svg width="200" height="200" viewBox="0 0 200 200">
<!-- Multiple transforms apply right-to-left -->
<rect x="0" y="0" width="40" height="40" fill="red"
transform="translate(100, 100) rotate(45) scale(2)"/>
<!-- This means: scale, then rotate, then translate -->
<!-- Order matters! rotate then translate != translate then rotate -->
<!-- transform-origin via CSS (for inline SVG) -->
<rect x="80" y="80" width="40" height="40" fill="blue"
style="transform: rotate(45deg); transform-origin: center;"/>
<!-- transform-origin: center, 50% 50%, or explicit coords -->
</svg>transform-origin (CSS)
Beim Animieren von SVG mit CSS transform-origin explizit setzen (in SVG-Nutzereinheiten) und transform-box (fill-box für die Bounding-Box des Elements, view-box für die SVG-Leinwand). Ohne diese rotiert es um den SVG-Ursprung, nicht das Element. CSS-Animationen und -Übergänge funktionieren bei inline SVG.
<svg width="200" height="200" viewBox="0 0 200 200">
<style>
.gear {
transform-origin: 100px 100px; /* SVG user units */
transform-box: fill-box; /* or view-box */
animation: spin 4s linear infinite;
}
@keyframes spin {
to { transform: rotate(360deg); }
}
</style>
<circle class="gear" cx="100" cy="100" r="50" fill="orange"/>
<circle cx="100" cy="100" r="10" fill="black"/>
</svg>Gruppe (g)
Einfaches Gruppieren
<g> gruppiert Elemente, sodass sie Attribute teilen (fill, stroke, transform usw.) und als Einheit manipulierbar sind. Kinder erben Präsentationsattribute von der Gruppe. Gruppen sind essenziell, um komplexe SVGs zu organisieren und Transforms auf mehrere Formen auf einmal anzuwenden.
<svg width="200" height="200" viewBox="0 0 200 200">
<g fill="steelblue" stroke="navy" stroke-width="2">
<!-- Children inherit the group's attributes -->
<circle cx="60" cy="60" r="30"/>
<rect x="100" y="30" width="60" height="60" rx="5"/>
<path d="M 30 150 L 100 110 L 170 150 Z"/>
</g>
<!-- Without g, you'd repeat fill/stroke on each element -->
</svg>Gruppen-Transforms
Ein Transform auf <g> erzeugt ein neues Koordinatensystem für seine Kinder. Das ist der Schlüssel zu wiederverwendbaren Komponenten: um (0,0) herum entwerfen, dann die ganze Gruppe mit translate positionieren. Die Koordinaten der Kinder sind relativ zum transformierten Ursprung der Gruppe.
<svg width="200" height="200" viewBox="0 0 200 200">
<!-- A transform on a group applies to all children -->
<g transform="translate(100, 100) rotate(45)">
<rect x="-30" y="-30" width="60" height="60" fill="red"/>
<circle cx="0" cy="0" r="15" fill="white"/>
</g>
<!-- The group defines its own coordinate system -->
<!-- Children use coords relative to the group's origin -->
<g transform="translate(50, 150)">
<text x="0" y="0">Origin here</text>
<circle cx="0" cy="-20" r="5"/>
</g>
</svg>Verschachtelte Gruppen
Gruppen dürfen beliebig tief verschachteln. Jede verschachtelte Transformation akkumuliert sich — das innerste Element wird von allen Vorfahren-Transforms der Reihe nach beeinflusst. So baut man hierarchische Szenen (z. B. eine Figur mit rotierenden Gliedmaßen, jede mit bewegten Händen). Verschachtelung für die Performance vernünftig halten.
<svg width="200" height="200" viewBox="0 0 200 200">
<g transform="translate(100, 100)"> <!-- outer group -->
<g transform="scale(0.5)"> <!-- inner group -->
<circle r="80" fill="blue"/>
<g transform="translate(40, 0)"> <!-- innermost -->
<circle r="20" fill="white"/>
</g>
</g>
</g>
<!-- Transforms compound: the innermost circle is -->
<!-- translated, scaled, and translated again -->
</svg>Gruppen-IDs & Referenzen
Einer Gruppe eine id geben und sie mit <use href='#id'> referenzieren, um sie zu duplizieren. Die Basis von SVG-Sprites und wiederverwendbaren Komponenten. Die Gruppe kann in <defs> liegen (nicht direkt gerendert) und mit verschiedenen Transforms vielfach instanziiert werden. Attribute auf <use> zu überschreiben ist begrenzt.
<svg width="200" height="100" viewBox="0 0 200 100">
<defs>
<g id="star">
<polygon points="50,5 61,38 95,38 67,58 78,90 50,70 22,90 33,58 5,38 39,38"
fill="gold" stroke="orange"/>
</g>
</defs>
<!-- Reference the group with <use> -->
<use href="#star" transform="translate(0, 0) scale(0.5)"/>
<use href="#star" transform="translate(100, 0) scale(0.5)"/>
<use href="#star" transform="translate(0, 50) scale(0.3)"/>
</svg>Bedingte Gruppen
Gruppen mit ids sind perfekte Hook-Punkte für CSS (Hover, aktive Zustände) und JavaScript-Eventbehandlung. Ein <g> wie eine Komponente behandeln: seine Formen bündeln, eine id geben und als Einheit mit ihm interagieren. Event-Listener auf einer Gruppe fangen Events aller Kinder.
<svg width="200" height="100" viewBox="0 0 200 100">
<!-- <g> can have ids for CSS targeting and JS selection -->
<g id="button" class="interactive" data-action="save">
<rect width="80" height="30" rx="5" fill="steelblue"/>
<text x="40" y="20" text-anchor="middle" fill="white">Save</text>
</g>
<style>
#button:hover rect { fill: royalblue; }
#button { cursor: pointer; }
</style>
<script>
document.getElementById("button").addEventListener("click", save);
</script>
</svg>Gruppe vs. Symbol
<symbol> ist eigens für wiederverwendbare Icons gebaut: es wird nie direkt gerendert und hat einen eigenen viewBox, sodass <use> es unabhängig bemessen kann. <g> in <defs> funktioniert auch, hat aber das viewBox-Feature nicht. Für Icon-Systeme <symbol> bevorzugen — es handhabt Skalierung und Seitenverhältnis automatisch.
<svg width="0" height="0" viewBox="0 0 0 0">
<!-- <g> in <defs>: original is hidden, use can instantiate -->
<defs>
<g id="icon-g">
<rect width="20" height="20" fill="red"/>
</g>
</defs>
<!-- <symbol> is like <g> but supports viewBox and is never rendered -->
<symbol id="icon-s" viewBox="0 0 20 20">
<rect width="20" height="20" fill="blue"/>
</symbol>
<!-- Use with explicit size (symbol scales to fit) -->
<use href="#icon-g" x="0" y="0"/>
<use href="#icon-s" x="40" y="0" width="40" height="40"/>
</svg>Use / Symbol / Defs
defs-Element
<defs> hält wiederverwendbare Definitionen, die erst bei Referenz gezeichnet werden: Verläufe, Muster, Filter, Clip-Pfade, Masken, Symbole und Gruppen. In defs halten sie die gerenderte Ausgabe sauber und signalisieren die Absicht. Alles außerhalb von defs rendert sofort.
<svg width="200" height="100" viewBox="0 0 200 100">
<defs>
<!-- Anything in defs is defined but NOT rendered -->
<linearGradient id="myGrad">
<stop offset="0" stop-color="red"/>
<stop offset="1" stop-color="blue"/>
</linearGradient>
<pattern id="myPattern" width="20" height="20">
<circle cx="10" cy="10" r="5" fill="url(#myGrad)"/>
</pattern>
<g id="myShape">
<rect width="40" height="40" rx="5"/>
</g>
</defs>
<!-- Reference and render them -->
<rect width="100" height="100" fill="url(#myPattern)"/>
<use href="#myShape" x="120" y="30" fill="green"/>
</svg>use-Element
<use> klont und rendert ein definiertes Element (g, symbol oder jede Form). x/y positionieren die Instanz. fill/stroke auf <use> überschreiben das Original nur, wenn das Original sie nicht angegeben hat (CSS-Vererbung). transform gilt für die Instanz. So funktionieren SVG-Sprites.
<svg width="300" height="100" viewBox="0 0 300 100">
<defs>
<g id="cloud">
<circle cx="30" cy="50" r="20" fill="white"/>
<circle cx="50" cy="45" r="25" fill="white"/>
<circle cx="75" cy="50" r="20" fill="white"/>
</g>
</defs>
<!-- Basic use -->
<use href="#cloud"/>
<!-- Positioned and styled -->
<use href="#cloud" x="120" y="0" fill="lightgray"/>
<use href="#cloud" x="200" y="10" transform="scale(0.5)" fill="silver"/>
</svg>symbol-Element
<symbol> definiert eine wiederverwendbare Grafik mit eigenem viewBox. Anders als <g> wird es nie direkt gerendert und skaliert auf die Dimensionen des <use>-Elements. fill='currentColor' erlaubt dem Konsumenten, die Farbe via CSS color zu setzen. Das Standardmuster für SVG-Icon-Systeme.
<!-- In a hidden sprite file or <defs> -->
<svg width="0" height="0" style="position:absolute">
<symbol id="heart" viewBox="0 0 32 32">
<path d="M16 28 C 4 18, 4 8, 12 8 C 14 8, 16 10, 16 12
C 16 10, 18 8, 20 8 C 28 8, 28 18, 16 28 Z"
fill="currentColor"/>
</symbol>
<symbol id="star" viewBox="0 0 32 32">
<polygon points="16,2 20,12 31,12 22,19 25,30 16,23 7,30 10,19 1,12 12,12"
fill="currentColor"/>
</symbol>
</svg>
<!-- Usage: size with width/height, color with CSS -->
<svg width="24" height="24"><use href="#heart"/></svg>
<svg width="48" height="48"><use href="#star" style="color: gold"/></svg>Externe SVG-Referenzen
<use> kann Symbole in externen SVG-Dateien referenzieren via href='file.svg#id'. Die Browserunterstützung ist jedoch uneinheitlich (kein IE, CORS-Beschränkungen), und es scheitert bei file://. Der verlässliche Ansatz: ein verstecktes SVG-Sprite oben im HTML inline setzen und Symbole im selben Dokument referenzieren.
<!-- Reference a symbol in an external .svg file -->
<svg width="24" height="24">
<use href="icons.svg#heart"/>
</svg>
<!-- The external file (icons.svg) would contain: -->
<!-- <svg xmlns="http://www.w3.org/2000/svg" style="display:none"> -->
<!-- <symbol id="heart" viewBox="0 0 32 32">...</symbol> -->
<!-- </svg> -->
<!-- Note: external references have limited browser support -->
<!-- and don't work with file:// protocol. Inline is more reliable. -->
<!-- For production, inline the sprite at the top of your HTML body. -->Use-Attribute überschreiben
Lässt die Originalform ein Präsentationsattribut weg (etwa fill), kann <use> es setzen — die Instanz erbt den Wert. Gibt das Original fill an, wird das fill des use ignoriert (Präsentationsattribute schlagen CSS-Vererbung). Um anpassbare Symbole zu bauen, die zu überschreibenden Attribute weglassen.
<svg width="300" height="100" viewBox="0 0 300 100">
<defs>
<!-- Shape without explicit fill — inherits from use -->
<circle id="ball" cx="20" cy="20" r="15"/>
</defs>
<!-- Each use can set its own fill -->
<use href="#ball" fill="red"/>
<use href="#ball" x="50" fill="green"/>
<use href="#ball" x="100" fill="blue" stroke="black" stroke-width="2"/>
</svg>Symbol-Verschachtelung & Sprite
Das ist das Produktionsmuster für SVG-Icons: ein verstecktes Sprite-SVG oben im Dokument, das alle Icons als <symbol> enthält, dann <use>, um sie überall zu rendern. currentColor lässt Icons die Textfarbe erben. CSS steuert die Größe. Das Sprite cache-t nach dem ersten Laden und ist auf jeder Seite schnell.
<!-- A complete inline SVG sprite system -->
<svg style="display:none" aria-hidden="true">
<symbol id="icon-home" viewBox="0 0 24 24">
<path d="M12 3 L2 12 H5 V21 H10 V14 H14 V21 H19 V12 H22 Z"/>
</symbol>
<symbol id="icon-search" viewBox="0 0 24 24">
<circle cx="11" cy="11" r="7" fill="none" stroke="currentColor" stroke-width="2"/>
<line x1="16" y1="16" x2="21" y2="21" stroke="currentColor" stroke-width="2"/>
</symbol>
</svg>
<!-- Reference anywhere in HTML -->
<svg class="icon"><use href="#icon-home"/></svg>
<svg class="icon"><use href="#icon-search"/></svg>
<style>
.icon { width: 24px; height: 24px; fill: currentColor; }
</style>Filter
Filter-Grundlagen
Ein <filter> enthält eine oder mehrere Filter-Primitive (fe*-Elemente), die die Grafik verarbeiten. in='SourceGraphic' nimmt das eigene Rendering des Elements. Anwenden mit filter='url(#id)'. Filter können teuer sein — sparsam auf kleinen Elementen einsetzen, nicht auf großen Hintergründen.
<svg width="200" height="120" viewBox="0 0 200 120">
<defs>
<filter id="blur1">
<!-- feGaussianBlur: stdDeviation is the blur radius -->
<feGaussianBlur in="SourceGraphic" stdDeviation="3"/>
</filter>
</defs>
<!-- Without filter -->
<text x="10" y="30" font-size="24" fill="red">Sharp</text>
<!-- With filter -->
<text x="10" y="70" font-size="24" fill="red"
filter="url(#blur1)">Blurred</text>
</svg>Drop-Shadow
Ein Drop-Shadow kombiniert feOffset (verschieben), feGaussianBlur (weichen), feFlood (einfärben), feComposite (Farbe auf den Schatten anwenden) und feMerge (Schatten unter das Original schichten). Die x/y/width/height des Filters (Standard -10 % bis 110 %) müssen vergrößert werden, sonst wird der Schatten beschnitten.
<svg width="200" height="120" viewBox="0 0 200 120">
<defs>
<filter id="shadow" x="-20%" y="-20%" width="140%" height="140%">
<!-- Offset the source -->
<feOffset in="SourceAlpha" dx="4" dy="4" result="offset"/>
<!-- Blur the offset copy -->
<feGaussianBlur in="offset" stdDeviation="3" result="blur"/>
<!-- Color the shadow -->
<feFlood flood-color="black" flood-opacity="0.5" result="color"/>
<feComposite in="color" in2="blur" operator="in" result="shadow"/>
<!-- Put shadow under the original -->
<feMerge>
<feMergeNode in="shadow"/>
<feMergeNode in="SourceGraphic"/>
</feMerge>
</filter>
</defs>
<rect x="20" y="20" width="80" height="60" fill="white"
filter="url(#shadow)"/>
</svg>Einfacher Drop-Shadow (CSS)
Für einfache Schatten bei inline SVG ist CSS filter: drop-shadow() weit einfacher als der Bau eines SVG-Filters. Er respektiert die tatsächliche Kontur der Form (nicht nur die Bounding-Box wie box-shadow). SVG-Filter nur für komplexe mehrstufige Effekte nutzen, die CSS nicht ausdrücken kann.
<!-- Modern browsers: use CSS filter instead of SVG filter -->
<svg width="200" height="100" viewBox="0 0 200 100">
<rect x="50" y="20" width="100" height="60" fill="white"
style="filter: drop-shadow(4px 4px 4px rgba(0,0,0,0.5));"/>
</svg>
<!-- In CSS -->
<style>
.shadowed { filter: drop-shadow(0 0 10px rgba(0,0,0,0.3)); }
</style>
<!-- CSS drop-shadow follows the shape's alpha, unlike box-shadow -->
<!-- which only shadows the bounding box -->Farbmatrix
feColorMatrix transformiert Farben über eine 5x4-Matrix (RGBA rein, RGBA raus). type='saturate' mit Werten 0-1 entsättigt; type='hueRotate' rotiert den Farbton in Grad; type='luminanceToAlpha' konvertiert Helligkeit in Alpha. Nützlich für Graustufen, Sepia und Farbanpassungen an SVG-Inhalten.
<svg width="200" height="100" viewBox="0 0 200 100">
<defs>
<!-- Convert to grayscale -->
<filter id="grayscale">
<feColorMatrix type="matrix"
values="0.33 0.33 0.33 0 0
0.33 0.33 0.33 0 0
0.33 0.33 0.33 0 0
0 0 0 1 0"/>
</filter>
<!-- Built-in saturation -->
<filter id="desaturate">
<feColorMatrix type="saturate" values="0"/>
</filter>
</defs>
<image href="photo.jpg" width="100" height="100" filter="url(#grayscale)"/>
<image href="photo.jpg" x="100" width="100" height="100" filter="url(#desaturate)"/>
</svg>Lichteffekte
feSpecularLighting und feDiffuseLighting simulieren 3D-Beleuchtung auf der Höhenkarte einer 2D-Form (abgeleitet aus Alpha). surfaceScale steuert die Tiefe; das Lichtelement (fePointLight, feDistantLight, feSpotLight) setzt die Richtung. Kombiniert mit feComposite ergeben sich Prägung, Fase und 3D-Texteffekte.
<svg width="200" height="120" viewBox="0 0 200 120">
<defs>
<filter id="emboss">
<!-- Create a height map from the alpha -->
<feGaussianBlur in="SourceAlpha" stdDeviation="2" result="blur"/>
<!-- Lighting from upper-left -->
<feSpecularLighting in="blur" surfaceScale="5"
specularConstant="0.8" specularExponent="20"
lighting-color="white" result="spec">
<fePointLight x="-50" y="-50" z="200"/>
</feSpecularLighting>
<feComposite in="spec" in2="SourceGraphic"
operator="in" result="lit"/>
<feComposite in="SourceGraphic" in2="lit" operator="arithmetic"
k1="0" k2="1" k3="1" k4="0"/>
</filter>
</defs>
<text x="10" y="70" font-size="48" font-weight="bold"
fill="gray" filter="url(#emboss)">3D</text>
</svg>Turbulenz (Textur)
feTurbulence erzeugt prozedurales Rauschen (fraktal oder turbulence-Typ) — nützlich für Texturen wie Rauschen, Wolken, Wasser oder Papierkorn. baseFrequency steuert die Skala (0.5 = fein, 0.05 = wolkig). numOctaves ergänzt Detail auf Kosten der Geschwindigkeit. Mit feColorMatrix oder feDisplacementMap kombinieren für Effekte.
<svg width="200" height="200" viewBox="0 0 200 200">
<defs>
<!-- feTurbulence generates Perlin noise -->
<filter id="noise" x="0" y="0" width="100%" height="100%">
<feTurbulence type="fractalNoise" baseFrequency="0.65"
numOctaves="3" stitchTiles="stitch"/>
<feColorMatrix type="matrix"
values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.1 0"/>
</filter>
</defs>
<rect width="200" height="200" fill="steelblue"/>
<rect width="200" height="200" filter="url(#noise)"/>
<!-- type: "fractalNoise" or "turbulence" -->
<!-- baseFrequency: lower = larger blobs, higher = finer grain -->
<!-- numOctaves: more = more detail (slower) -->
</svg>Clipping & Masking
Clip-Pfad
clipPath definiert eine hartkantige Grenze — Pixel innen sind sichtbar, außen verborgen. Die Clip-Form selbst wird nicht gezeichnet. clip-path referenziert sie via url(#id). Clipping ist binär (rein oder raus); für weiche Übergänge Masken nutzen. Text als Clip-Pfad erzeugt den klassischen 'Bild im Text'-Effekt.
<svg width="200" height="200" viewBox="0 0 200 200">
<defs>
<!-- A clip path: only the inside is visible -->
<clipPath id="circleClip">
<circle cx="100" cy="100" r="80"/>
</clipPath>
</defs>
<!-- The image is clipped to the circle -->
<rect width="200" height="200" fill="steelblue"
clip-path="url(#circleClip)"/>
<!-- Any shape can be a clip path -->
<clipPath id="textClip">
<text x="100" y="120" font-size="80" text-anchor="middle"
font-weight="bold">SVG</text>
</clipPath>
<rect width="200" height="200" fill="gold" clip-path="url(#textClip)"/>
</svg>Maske
Anders als clip-path (binär) unterstützen Masken Alpha — weiße Bereiche sind voll sichtbar, schwarze verborgen, Grautöne teilweise transparent. Einen Verlauf als Maskeninhalt nutzen für weiche Verblendungen. Masken sind schwerer als Clip-Pfade, aber essenziell für weiche Übergänge und Fotoeffekte.
<svg width="200" height="200" viewBox="0 0 200 200">
<defs>
<!-- A mask: white = visible, black = hidden, gray = partial -->
<mask id="fadeMask">
<linearGradient id="fadeGrad" x1="0" y1="0" x2="0" y2="1">
<stop offset="0" stop-color="white"/>
<stop offset="1" stop-color="black"/>
</linearGradient>
<rect width="200" height="200" fill="url(#fadeGrad)"/>
</mask>
</defs>
<!-- The image fades from top to bottom -->
<rect width="200" height="200" fill="red" mask="url(#fadeMask)"/>
</svg>Clip-Pfad-Einheiten
clipPathUnits='objectBoundingBox' lässt den Clip-Pfad auf die Bounding-Box jedes Elements skalieren (Koordinaten 0-1), ein Clip-Pfad funktioniert also für unterschiedlich große Formen. 'userSpaceOnUse' (Standard) nutzt absolute SVG-Koordinaten. Die meisten wiederverwendbaren Clips nutzen objectBoundingBox.
<svg width="300" height="100" viewBox="0 0 300 100">
<defs>
<!-- userSpaceOnUse (default): clip coords in SVG units -->
<clipPath id="clip1" clipPathUnits="userSpaceOnUse">
<rect x="10" y="10" width="50" height="50"/>
</clipPath>
<!-- objectBoundingBox: coords are 0-1 relative to the element -->
<clipPath id="clip2" clipPathUnits="objectBoundingBox">
<rect x="0.1" y="0.1" width="0.8" height="0.8"/>
</clipPath>
</defs>
<rect width="100" height="100" fill="red" clip-path="url(#clip1)"/>
<rect x="100" width="100" height="80" fill="blue" clip-path="url(#clip2)"/>
<rect x="200" width="100" height="60" fill="green" clip-path="url(#clip2)"/>
</svg>CSS clip-path
CSS clip-path unterstützt Basisformen (circle, ellipse, polygon, inset) direkt ohne SVG und kann SVG-clipPath-Elemente via url(#id) referenzieren. Das funktioniert auch auf HTML-Elementen, nicht nur SVG. CSS-Masking wird in modernen Browsern ebenfalls über mask-image unterstützt.
<style>
/* CSS clip-path works on SVG and HTML elements */
.circle {
clip-path: circle(50% at 50% 50%);
}
.triangle {
clip-path: polygon(50% 0%, 100% 100%, 0% 100%);
}
/* Reference an SVG clipPath */
.svg-clip {
clip-path: url(#myClip);
}
</style>
<svg width="200" height="100">
<defs>
<clipPath id="myClip">
<circle cx="50" cy="50" r="40"/>
</clipPath>
</defs>
<rect class="svg-clip" width="200" height="100" fill="purple"/>
</svg>Praktisch: Bild im Text
Einen Verlauf oder ein Bild auf Text zu clippen ist eine beliebte Designtechnik. Der clipPath enthält ein <text>-Element; das geclippte Rechteck füllt sich mit dem Verlauf, sichtbar nur innerhalb der Buchstabenformen. Das funktioniert auch mit <image> — ein Foto im Text für Magazin-Header.
<svg width="400" height="120" viewBox="0 0 400 120">
<defs>
<clipPath id="textShape">
<text x="200" y="90" font-size="80" font-weight="900"
text-anchor="middle" font-family="Arial">SUMMER</text>
</clipPath>
</defs>
<!-- Background (visible only through the text) -->
<rect width="400" height="120" fill="black"/>
<!-- Image clipped to the text shape -->
<rect width="400" height="120" fill="url(#sunsetGrad)"
clip-path="url(#textShape)"/>
<linearGradient id="sunsetGrad" x1="0" y1="0" x2="0" y2="1">
<stop offset="0" stop-color="#ff6b6b"/>
<stop offset="0.5" stop-color="#feca57"/>
<stop offset="1" stop-color="#ff9ff3"/>
</linearGradient>
</svg>Animation (SMIL)
animate (einfach)
<animate> überblendet ein Attribut über die Zeit. attributeName ist das Ziel; from/to definieren den Bereich; dur die Dauer; repeatCount='indefinite' loopt für immer. SMIL-Animationen sind deklarativ (kein JS nötig) und funktionieren in den meisten Browsern außer IE. Die Animation ist ein Kind des Zielelements.
<svg width="200" height="100" viewBox="0 0 200 100">
<rect x="0" y="40" width="20" height="20" fill="red">
<animate attributeName="x"
from="0" to="180"
dur="2s"
repeatCount="indefinite"/>
</rect>
<!-- The rect moves from x=0 to x=180 over 2 seconds, forever -->
</svg>animateTransform
<animateTransform> animiert das transform-Attribut. type wählt die Operation (rotate, scale, translate, skewX, skewY). Bei rotate sind from/to 'Winkel cx cy' (Zentrumspunkt). So drehst du Elemente ohne JavaScript. Nur ein animateTransform kann pro Element laufen, außer mit additive='sum'.
<svg width="200" height="200" viewBox="0 0 200 200">
<rect x="80" y="80" width="40" height="40" fill="blue">
<animateTransform attributeName="transform"
type="rotate"
from="0 100 100" to="360 100 100"
dur="3s"
repeatCount="indefinite"/>
</rect>
<!-- type can be: rotate, scale, translate, skewX, skewY -->
<!-- For rotate, the values are "angle cx cy" -->
</svg>animateMotion
<animateMotion> bewegt ein Element entlang eines Pfads. Den Pfad mit <mpath href='#id'> referenzieren oder path direkt definieren. rotate='auto' richtet das Element in Fahrtrichtung aus — essenziell für Pfeile, Autos oder Figuren. Der SVG-Weg, pfadbasierte Animation ohne JS zu machen.
<svg width="200" height="150" viewBox="0 0 200 150">
<defs>
<path id="motionPath" d="M 10 75 Q 100 0, 190 75" fill="none"/>
</defs>
<!-- A circle follows the path -->
<circle r="10" fill="red">
<animateMotion dur="3s" repeatCount="indefinite">
<mpath href="#motionPath"/>
</animateMotion>
</circle>
<!-- Show the path for reference -->
<use href="#motionPath" stroke="gray" stroke-width="1"/>
<!-- rotate="auto" makes the element face the direction of motion -->
<circle r="5" fill="blue">
<animateMotion dur="3s" repeatCount="indefinite" rotate="auto">
<mpath href="#motionPath"/>
</animateMotion>
</circle>
</svg>Keyframes & Easing
Für mehrstufige Animationen values (semikolongetrennt), keyTimes (0-1-Anteile) und keySplines (Bezier-Easing pro Segment) nutzen. calcMode='spline' aktiviert Easing; 'linear' ist der Standard. Das spiegelt CSS-Keyframe-Animation wider, aber in purem SVG. Das Rechteck springt mit weichem Easing hin und her.
<svg width="200" height="100" viewBox="0 0 200 100">
<rect x="0" y="40" width="20" height="20" fill="green">
<animate attributeName="x"
values="0; 80; 180; 80; 0"
keyTimes="0; 0.25; 0.5; 0.75; 1"
keySplines="0.5 0 0.5 1; 0 0 1 1; 0.5 0 0.5 1; 0 0 1 1"
calcMode="spline"
dur="4s"
repeatCount="indefinite"/>
</rect>
<!-- values: the animated values at each keyTime -->
<!-- keyTimes: 0-1 fractions of dur (semicolon-separated) -->
<!-- keySplines: cubic-bezier easing between each pair -->
<!-- calcMode: "discrete", "linear", "paced", or "spline" -->
</svg>begin, end & Trigger
begin kann ein Zeitversatz (2s), ein Event (click, mouseenter) oder eine Referenz auf das Event einer anderen Animation sein (anim1.end, anim1.begin+1s). fill='freeze' hält den Endwert nach Animationsende (sonst springt er zurück). So entstehen klickausgelöste und verkettete Animationen ohne JavaScript.
<svg width="200" height="100" viewBox="0 0 200 100">
<!-- begin: when to start (time or event) -->
<rect x="10" y="10" width="30" height="30" fill="red">
<animate attributeName="width" from="30" to="100"
dur="1s" begin="2s" fill="freeze"/>
</rect>
<!-- begin on a click event -->
<rect x="10" y="60" width="30" height="30" fill="blue" id="trigger">
<animate attributeName="x" from="10" to="150"
dur="1s" begin="click" fill="freeze"/>
</rect>
<!-- begin when another animation ends -->
<rect x="10" y="80" width="30" height="10" fill="green">
<animate attributeName="x" from="10" to="150"
dur="1s" begin="trigger.click+1s" fill="freeze"/>
</rect>
</svg>CSS-Animations-Alternative
Für inline SVG in Webseiten sind CSS-Animationen oft einfacher als SMIL und haben besseres Tooling. transform-box: fill-box nutzen, damit sich transform-origin: center auf das Element bezieht, nicht die SVG-Leinwand. SMIL bleibt nützlich für eigenständige SVG-Dateien (kein CSS verfügbar) und pfadbasierte Bewegung.
<svg width="200" height="100" viewBox="0 0 200 100">
<style>
.pulse {
animation: pulse 1.5s ease-in-out infinite;
transform-origin: center;
transform-box: fill-box;
}
@keyframes pulse {
0%, 100% { transform: scale(1); opacity: 1; }
50% { transform: scale(1.2); opacity: 0.7; }
}
</style>
<circle class="pulse" cx="100" cy="50" r="20" fill="red"/>
</svg>
<!-- CSS animations are more maintainable for web pages -->
<!-- SMIL is better for standalone .svg files -->Events
Maus-Events
SVG-Elemente unterstützen Standard-DOM-Events: click, mouseenter, mouseleave, mousemove, mousedown, mouseup, dblclick. addEventListener wie bei HTML-Elementen nutzen. 'this' innerhalb eines Handlers verweist auf das SVG-Element. setAttribute nutzen, um Eigenschaften reaktiv zu ändern.
<svg width="200" height="100" viewBox="0 0 200 100">
<rect id="box" x="10" y="10" width="80" height="80" fill="steelblue"/>
<script>
var box = document.getElementById("box");
box.addEventListener("click", function (e) {
alert("Clicked at " + e.clientX + "," + e.clientY);
});
box.addEventListener("mouseenter", function () {
this.setAttribute("fill", "tomato");
});
box.addEventListener("mouseleave", function () {
this.setAttribute("fill", "steelblue");
});
</script>
</svg>Touch-Events
SVG unterstützt touchstart, touchmove, touchend. Bildschirmkoordinaten mit createSVGPoint und getScreenCTM().inverse() in SVG-Koordinaten konvertieren — essenziell, wenn das SVG skaliert oder responsiv ist. preventDefault() bei touchstart verhindert Gesten-Interferenz wie Scrollen.
<svg width="200" height="200" viewBox="0 0 200 200">
<circle id="touch" cx="100" cy="100" r="30" fill="purple"/>
<script>
var circle = document.getElementById("touch");
circle.addEventListener("touchstart", function (e) {
e.preventDefault(); // prevent scrolling
this.setAttribute("fill", "orange");
});
circle.addEventListener("touchend", function () {
this.setAttribute("fill", "purple");
});
// touchmove for dragging
circle.addEventListener("touchmove", function (e) {
var touch = e.touches[0];
var pt = svg.createSVGPoint();
pt.x = touch.clientX; pt.y = touch.clientY;
var svgP = pt.matrixTransform(svg.getScreenCTM().inverse());
this.setAttribute("cx", svgP.x);
this.setAttribute("cy", svgP.y);
});
</script>
</svg>Koordinatenkonvertierung
Hat ein SVG einen viewBox, der von seiner Pixelgröße abweicht, mappen Bildschirmkoordinaten nicht 1:1 auf SVG-Koordinaten. createSVGPoint + getScreenCTM().inverse() konvertiert korrekt und berücksichtigt viewBox, CSS-Skalierung und sogar Transforms auf Vorfahren-Elementen. Essenziell für genaue Klick-Erkennung.
<svg width="500" height="300" viewBox="0 0 1000 600" id="mysvg">
<rect width="1000" height="600" fill="lightblue"/>
<script>
var svg = document.getElementById("mysvg");
svg.addEventListener("click", function (e) {
// Convert screen (clientX/Y) to SVG user coordinates
var pt = svg.createSVGPoint();
pt.x = e.clientX;
pt.y = e.clientY;
// getScreenCTM maps SVG coords to screen; inverse maps back
var svgPoint = pt.matrixTransform(
svg.getScreenCTM().inverse()
);
console.log("SVG coords:", svgPoint.x, svgPoint.y);
// This accounts for viewBox scaling and CSS sizing
});
</script>
</svg>Event-Delegation
Event-Delegation — ein Listener auf einer Parent-Gruppe statt vieler auf Kindern — ist effizienter und behandelt dynamisch ergänzte Formen automatisch. e.target ist die geklickte Form; e.currentTarget das Element mit dem Listener. data-*-Attribute nutzen, um Metadaten pro Form zu speichern.
<svg width="300" height="100" viewBox="0 0 300 100">
<g id="shapes">
<circle cx="50" cy="50" r="30" fill="red" data-name="circle1"/>
<rect x="100" y="20" width="60" height="60" fill="blue" data-name="rect1"/>
<polygon points="220,20 280,20 250,80" fill="green" data-name="tri1"/>
</g>
<script>
// One listener on the parent group handles all children
document.getElementById("shapes").addEventListener("click", function (e) {
var target = e.target;
var name = target.getAttribute("data-name");
console.log("Clicked:", name, target.tagName);
// e.target is the actual shape; e.currentTarget is the group
});
</script>
</svg>Drag-Interaktion
Das ist das klassische SVG-Drag-Muster: mousedown setzt ein Flag, mousemove aktualisiert die Elementposition (mit konvertierten SVG-Koordinaten), mouseup löscht das Flag. mousemove/mouseup an das SVG anhängen (nicht das Element), damit das Ziehen weitergeht, selbst wenn der Cursor die Form verlässt. Das Fundament SVG-basierter Editoren.
<svg width="400" height="300" viewBox="0 0 400 300" id="canvas">
<circle id="draggable" cx="200" cy="150" r="30" fill="orange" cursor="grab"/>
<script>
var circle = document.getElementById("draggable");
var svg = document.getElementById("canvas");
var dragging = false;
function getSVGPoint(e) {
var pt = svg.createSVGPoint();
pt.x = e.clientX; pt.y = e.clientY;
return pt.matrixTransform(svg.getScreenCTM().inverse());
}
circle.addEventListener("mousedown", function () {
dragging = true;
this.setAttribute("cursor", "grabbing");
});
svg.addEventListener("mousemove", function (e) {
if (!dragging) return;
var p = getSVGPoint(e);
circle.setAttribute("cx", p.x);
circle.setAttribute("cy", p.y);
});
svg.addEventListener("mouseup", function () {
dragging = false;
circle.setAttribute("cursor", "grab");
});
</script>
</svg>JavaScript-DOM
Elemente erzeugen
SVG-Elemente müssen mit document.createElementNS(Namensraum, tagName) erzeugt werden — createElement funktioniert für SVG nicht (er erzeugt unbekannte HTML-Elemente). Der SVG-Namensraum ist 'http://www.w3.org/2000/svg'. setAttribute für Eigenschaften nutzen. Das Fundament dynamischer SVG-Generierung.
<svg id="canvas" width="200" height="200" viewBox="0 0 200 200">
<script>
var svg = document.getElementById("canvas");
var NS = "http://www.w3.org/2000/svg";
// createElementNS is required for SVG elements
var circle = document.createElementNS(NS, "circle");
circle.setAttribute("cx", "100");
circle.setAttribute("cy", "100");
circle.setAttribute("r", "50");
circle.setAttribute("fill", "red");
svg.appendChild(circle);
// Create a path
var path = document.createElementNS(NS, "path");
path.setAttribute("d", "M 10 10 L 100 100");
path.setAttribute("stroke", "black");
svg.appendChild(path);
</script>
</svg>Elemente ändern
setAttribute/getAttribute für SVG-Präsentationsattribute nutzen (fill, stroke, width usw.). classList funktioniert zuverlässig über Browser hinweg. style.fill zu setzen funktioniert, weil es auf die CSS-Eigenschaft mappt. innerHTML für SVG vermeiden (browserspezifisch inkonsistent); das DOM stattdessen mit createElementNS bauen.
<svg width="200" height="100" viewBox="0 0 200 100">
<rect id="r" x="10" y="10" width="50" height="50" fill="blue"/>
<script>
var r = document.getElementById("r");
// Change attributes
r.setAttribute("fill", "red");
r.setAttribute("width", "80");
// Get attribute values
var w = r.getAttribute("width"); // "80"
// Remove attributes
r.removeAttribute("fill");
// Class manipulation (use classList, not className for SVG in some browsers)
r.classList.add("highlight");
r.classList.toggle("active");
// Style (use setAttribute for presentation attributes)
r.style.fill = "green"; // works via CSS
</script>
</svg>Geometrie lesen
getBBox() liefert die Bounding-Box in SVG-Nutzereinheiten (ignoriert Transforms). getBoundingClientRect() liefert Bildschirmkoordinaten (nach allen Transforms und CSS). getTotalLength() gibt die Pfad-/Linienlänge; getPointAtLength(d) liefert den Punkt bei Distanz d — essenziell für pfadbasierte Animationen und Treffertests.
<svg width="200" height="100" viewBox="0 0 200 100">
<rect id="r" x="10" y="10" width="80" height="50" fill="blue"/>
<script>
var r = document.getElementById("r");
// Get bounding box in SVG user units
var bbox = r.getBBox();
console.log(bbox.x, bbox.y, bbox.width, bbox.height);
// Get bounding box in screen coordinates (after transforms)
var cbox = r.getBoundingClientRect();
console.log(cbox.left, cbox.top, cbox.width, cbox.height);
// Total length of a path or line
var path = document.querySelector("path");
var len = path.getTotalLength();
var point = path.getPointAtLength(len / 2); // midpoint
</script>
</svg>Dataset & Datenattribute
SVG-Elemente unterstützen data-*-Attribute und die dataset-Eigenschaft wie HTML. Der saubere Weg, Daten mit Formen für interaktive Anwendungen zu verknüpfen — Knoten-IDs, Labels oder Zustand speichern, ohne visuelle Attribute zu verschmutzen. Lesen mit element.dataset.key, setzen ebenso.
<svg width="200" height="100" viewBox="0 0 200 100">
<circle cx="50" cy="50" r="20" fill="red"
data-id="123" data-label="node"/>
<script>
var circle = document.querySelector("circle");
// dataset reads data-* attributes
console.log(circle.dataset.id); // "123"
console.log(circle.dataset.label); // "node"
// Set data attributes
circle.dataset.selected = "true"; // adds data-selected="true"
// Use for storing state
circle.dataset.visits = "0";
circle.dataset.visits = String(+circle.dataset.visits + 1);
</script>
</svg>Dynamische Pfadgenerierung
SVG dynamisch zu generieren ist die Basis eigener Charts. Das path-d-Attribut aufbauen, indem M/L-Befehle aus den Daten konkateniert werden, dann das Element mit createElementNS erzeugen. Dieser Ansatz gibt volle Kontrolle ohne Chart-Bibliothek. Für komplexe Visualisierungen D3.js erwägen, das dieses Muster elegant umhüllt.
<svg width="300" height="150" viewBox="0 0 300 150" id="chart">
<script>
var NS = "http://www.w3.org/2000/svg";
var svg = document.getElementById("chart");
var data = [10, 50, 30, 80, 45, 90, 25];
// Build a path string from data points
var d = "M 0 " + (150 - data[0]);
for (var i = 1; i < data.length; i++) {
d += " L " + (i * 40) + " " + (150 - data[i]);
}
var path = document.createElementNS(NS, "path");
path.setAttribute("d", d);
path.setAttribute("fill", "none");
path.setAttribute("stroke", "steelblue");
path.setAttribute("stroke-width", "2");
svg.appendChild(path);
// Add dots at each point
data.forEach(function (val, i) {
var c = document.createElementNS(NS, "circle");
c.setAttribute("cx", i * 40);
c.setAttribute("cy", 150 - val);
c.setAttribute("r", 3);
c.setAttribute("fill", "red");
svg.appendChild(c);
});
</script>
</svg>Performance-Tipps
Für Performance: DOM-Einfügungen mit DocumentFragment bündeln (ein Reflow), requestAnimationFrame für JS-Animationen nutzen (synchron zur Anzeigeaktualisierung) und das Abfragen von Attributen in engen Schleifen vermeiden (Werte cachen). SVG glänzt bis zu einigen Hundert Elementen; bei Tausenden (Partikel, dichte Plots) ist Canvas oder WebGL schneller.
<script>
// Batch DOM operations with document fragments
var fragment = document.createDocumentFragment();
for (var i = 0; i < 1000; i++) {
var c = document.createElementNS(NS, "circle");
c.setAttribute("cx", i);
c.setAttribute("cy", 50);
c.setAttribute("r", 2);
fragment.appendChild(c);
}
svg.appendChild(fragment); // one reflow, not 1000
// Use requestAnimationFrame for animations
function animate() {
element.setAttribute("cx", +element.getAttribute("cx") + 1);
requestAnimationFrame(animate);
}
animate();
// For many elements, consider <canvas> instead (faster)
// SVG slows down with thousands of nodes due to DOM overhead
</script>Responsives SVG (ViewBox)
viewBox-Grundlagen
viewBox='minX minY width height' definiert das interne Koordinatensystem. Die ersten zwei Werte schwenken die Sicht; die letzten zwei zoomen. Das SVG skaliert diesen Bereich auf seine width/height. Das entkoppelt deine Zeichenkoordinaten von der gerenderten Größe — einmal zeichnen bei beliebiger Skala, in einer 100x100- oder 1920x1080-Box.
<!-- viewBox="minX minY width height" -->
<svg viewBox="0 0 100 100" width="200" height="200">
<!-- A circle at center of a 100x100 coordinate system -->
<circle cx="50" cy="50" r="50" fill="blue"/>
</svg>
<!-- viewBox shifts the visible area -->
<svg viewBox="50 50 50 50" width="200" height="200">
<!-- Now showing only the bottom-right quadrant -->
<!-- The same circle, but zoomed in 2x on that corner -->
<circle cx="50" cy="50" r="50" fill="blue"/>
</svg>preserveAspectRatio
preserveAspectRatio steuert, wie der viewBox ins Element passt, wenn die Seitenverhältnisse abweichen. 'meet' (Standard) passt vollständig ein und leterboxt den Überschuss. 'slice' füllt vollständig und schneidet den Überhang ab. 'none' streckt und verzerrt. Der xMidYMid-Teil steuert die Ausrichtung: Min/Mid/Max für beide Achsen.
<!-- Default: preserve aspect ratio, center, letterbox -->
<svg viewBox="0 0 100 50" width="200" height="200"
preserveAspectRatio="xMidYMid meet">
<rect width="100" height="50" fill="blue"/>
</svg>
<!-- "slice": fill entirely, crop overflow -->
<svg viewBox="0 0 100 50" width="200" height="200"
preserveAspectRatio="xMidYMid slice">
<rect width="100" height="50" fill="red"/>
</svg>
<!-- "none": stretch to fill (distorts) -->
<svg viewBox="0 0 100 50" width="200" height="200"
preserveAspectRatio="none">
<rect width="100" height="50" fill="green"/>
</svg>Voll responsives SVG
Für responsives SVG: width/height-Attribute weglassen, viewBox setzen und die Größe mit CSS steuern (width: 100 %, height: auto). Das SVG skaliert auf seinen Container und erhält das Seitenverhältnis. display: block entfernt den Inline-SVG-Basislinienabstand. Das Standardmuster für fluides SVG in responsiven Layouts.
<!-- Omit width/height, set viewBox, use CSS to size -->
<svg viewBox="0 0 100 100" style="width: 100%; height: auto; display: block;">
<circle cx="50" cy="50" r="50" fill="orange"/>
</svg>
<!-- In a container with max-width -->
<div style="max-width: 500px; margin: auto;">
<svg viewBox="0 0 400 300" style="width: 100%; height: auto;">
<rect width="400" height="300" fill="steelblue"/>
</svg>
</div>Verschachteltes SVG & overflow
Verschachtelte <svg>-Elemente erzeugen unabhängige Viewports mit eigenem viewBox und preserveAspectRatio. Mächtig für Charts mit festen Seitenverhältnis-Panels oder UI-Komponenten. overflow='visible' lässt Inhalte außerhalb des verschachtelten Viewports zeichnen (Standard verborgen). Jedes verschachtelte svg kann seinen Inhalt unabhängig skalieren.
<svg width="300" height="200" viewBox="0 0 300 200">
<!-- Nested SVG creates a new viewport -->
<svg x="10" y="10" width="100" height="100" viewBox="0 0 50 50">
<circle cx="25" cy="25" r="25" fill="red"/>
</svg>
<!-- overflow="hidden" (default) clips content outside -->
<svg x="120" y="10" width="100" height="100" viewBox="0 0 50 50"
overflow="visible">
<circle cx="25" cy="25" r="30" fill="blue"/>
</svg>
<!-- Each nested svg can have its own preserveAspectRatio -->
<svg x="230" y="10" width="60" height="100" viewBox="0 0 50 50"
preserveAspectRatio="xMidYMid slice">
<circle cx="25" cy="25" r="25" fill="green"/>
</svg>
</svg>Fluide Textgrößen
Schriftgrößen in einem SVG mit viewBox skalieren mit dem SVG — ein 20px-Font in einem 400-breiten viewBox, angezeigt bei 800px Breite, rendert bei 40px. Damit Text auf den Browser-Viewport reagiert (nicht das SVG), CSS-Viewport-Einheiten (vw, vh) in einem style-Attribut nutzen. So skalieren SVG-Headlines fluide.
<svg viewBox="0 0 400 100" style="width:100%;height:auto;">
<style>
/* Use viewBox units for font-size — scales with the SVG */
text { font-size: 20px; }
/* Note: 'px' here means SVG user units, not CSS px */
</style>
<text x="200" y="50" text-anchor="middle">Scales with SVG</text>
</svg>
<!-- For truly responsive text relative to viewport, use CSS: -->
<svg viewBox="0 0 400 100" style="width:100%;height:auto;">
<text x="200" y="50" text-anchor="middle"
style="font-size: 5vw;">5% of viewport width</text>
</svg>
<!-- Or use container queries / media queries on the SVG element -->Seitenverhältnis-Steuerung
CSS aspect-ratio auf dem Container mit width/height 100 % auf dem SVG kombinieren für vorhersagbares responsives Verhalten. Das verhindert Layout-Shift (CLS), indem Platz reserviert wird, bevor das SVG lädt. Der viewBox passt zum Seitenverhältnis, Inhalte werden also nicht verzerrt. Die moderne Best-Practice für responsive SVG-Einbettungen.
<!-- Use CSS aspect-ratio for consistent sizing -->
<div style="width: 100%; max-width: 600px; aspect-ratio: 16/9;">
<svg viewBox="0 0 1600 900" style="width:100%;height:100%;">
<rect width="1600" height="900" fill="black"/>
<text x="800" y="450" text-anchor="middle" dominant-baseline="middle"
fill="white" font-size="48">16:9 Container</text>
</svg>
</div>
<!-- aspect-ratio ensures the container keeps proportions -->
<!-- even before the SVG loads, preventing layout shift -->SVG vs. Canvas
Rendering-Modell
SVG ist retained mode: Jede Form ist ein DOM-Element, das du inspizieren, stylen und später neu animieren kannst. Canvas ist immediate mode: Du gibst Zeichnenbefehle, die Pixel malen, und die Formen bestehen nicht als Objekte. SVG ist besser für interaktive UI; Canvas besser für Tausende dynamische Pixel.
<!-- SVG: retained mode (DOM-based) -->
<svg width="200" height="100">
<circle cx="50" cy="50" r="30" fill="red"/>
<!-- Each element is a DOM node, accessible via JS -->
</svg>
<!-- Canvas: immediate mode (pixel-based) -->
<canvas id="c" width="200" height="100"></canvas>
<script>
var ctx = document.getElementById("c").getContext("2d");
ctx.beginPath();
ctx.arc(50, 50, 30, 0, Math.PI * 2);
ctx.fillStyle = "red";
ctx.fill();
// Pixels are drawn; the circle isn't an object anymore
</script>Wann SVG
SVG wählen für: auflösungsunabhängige Grafiken (Icons, Logos), Barrierefreiheit (Screenreader durchlaufen das DOM), Interaktivität (Events pro Form), SEO (Text ist auswählbar) und moderate Elementanzahl (bis einige Hundert). SVG-Dateien sind Text (gzippt gut) und in Design-Tools editierbar.
<!-- SVG is ideal for:
- Icons and logos (crisp at any size)
- Charts with few elements (D3.js)
- Interactive diagrams (clickable shapes)
- Illustrations with editable layers
- Accessibility-required graphics
-->
<svg viewBox="0 0 24 24" width="48" height="48">
<path d="M12 2 L2 22 H22 Z" fill="triangle"/>
</svg>
<!-- Stays sharp whether displayed at 16px or 1024px -->
<!-- Each part can have its own click handler -->
<!-- Screen readers can access <title> and <desc> -->Wann Canvas
Canvas wählen für: hohe Elementanzahl (Tausende Formen), Neuzeichnen pro Frame (Spiele, Partikel), Pixelmanipulation (Filter, Effekte) und wenn DOM-Barrierefreiheit nicht gebraucht wird. Canvas ist schneller bei reiner Pixel-Performance, aber schwerer zugänglich oder interaktiv auf Ebene einzelner Formen zu machen.
<!-- Canvas is ideal for:
- Games (hundreds of sprites per frame)
- Particle systems
- Real-time image processing
- Heatmaps with thousands of cells
- Physics simulations
-->
<canvas id="particles" width="800" height="600"></canvas>
<script>
var ctx = document.getElementById("particles").getContext("2d");
var particles = [];
for (var i = 0; i < 5000; i++) {
particles.push({ x: Math.random()*800, y: Math.random()*600 });
}
function draw() {
ctx.clearRect(0, 0, 800, 600);
particles.forEach(function (p) {
ctx.fillRect(p.x, p.y, 2, 2);
});
requestAnimationFrame(draw);
}
draw();
</script>Performance-Vergleich
Die SVG-Performance verschlechtert sich mit der Elementanzahl, weil jede Form ein DOM-Knoten mit Eventbehandlung, Styling und Layout ist. Canvas hat konstanten Overhead pro Frame, unabhängig von der Formanz. Der Übergang liegt um 500-2000 Elemente, je nach Komplexität. Für statische oder leicht animierte Grafiken ist SVG fein; für dichte Echtzeitszenen Canvas nutzen.
<!-- SVG DOM overhead grows with element count -->
<!-- 100 circles: SVG ~0.1ms, Canvas ~0.1ms (both fine) -->
<!-- 1000 circles: SVG ~10ms, Canvas ~1ms (Canvas pulls ahead) -->
<!-- 10000 circles: SVG ~500ms+, Canvas ~10ms (SVG struggles) -->
<!-- SVG advantages:
- No redraw needed for CSS changes (browser handles it)
- Hardware-accelerated transforms
- Only changed elements re-render (incremental)
-->
<!-- Canvas advantages:
- Constant redraw cost regardless of history
- No DOM memory overhead per shape
- Direct pixel access (getImageData, putImageData)
-->Hybrid-Ansatz
Beides kombinieren: Canvas für die dichte, häufig neu gezeichnete Schicht (Heatmap, Partikel) und SVG darüber für interaktive UI (Tooltips, Auswahlgriffe, Labels). Die SVG-Schicht bleibt scharf und zugänglich, während Canvas die schwere Pixelarbeit macht. Dieses Muster nutzen Kartierungsbibliotheken wie Leaflet und Chart-Tools wie ECharts.
<!-- SVG for UI chrome, Canvas for dense content -->
<div style="position:relative; width:800px; height:600px;">
<!-- Canvas renders the heatmap (fast for thousands of cells) -->
<canvas width="800" height="600" style="position:absolute; top:0; left:0;">
</canvas>
<!-- SVG overlay for interactive tooltips and selection -->
<svg width="800" height="600" viewBox="0 0 800 600"
style="position:absolute; top:0; left:0;">
<g id="overlay"></g>
</svg>
</div>
<script>
// Draw heatmap on canvas (performant)
// Add hover tooltips as SVG elements (accessible, styled)
</script>Barrierefreiheit im Vergleich
SVG ist inhärent zugänglicher: das DOM ist durchlaufbar, Text auswählbar und durchsuchbar, und <title>/<desc> liefern Beschreibungen. Canvas braucht Extra-Arbeit — role/aria-label ergänzen und Text-Fallback-Inhalte innerhalb des <canvas>-Tags liefern. Für Charts und Datenvisualisierungen ist SVGs Barrierefreiheit ein großer Vorteil.
<!-- SVG: screen readers traverse the DOM -->
<svg role="img" aria-label="Sales chart showing 20% growth">
<title>Sales Chart</title>
<desc>Bar chart with 5 quarters, Q3 highest at $2M</desc>
<rect .../> <!-- each bar is a DOM element -->
</svg>
<!-- Text in SVG is selectable and searchable -->
<!-- Canvas: just pixels to a screen reader -->
<canvas role="img" aria-label="Sales chart showing 20% growth">
<!-- Must provide text fallback inside the canvas tag -->
Sales chart: Q1 $1M, Q2 $1.3M, Q3 $2M, Q4 $1.8M
</canvas>
<!-- No DOM, no selectable text, harder to make accessible -->SVG-Sprite
Inline-Sprite einrichten
Alle Icons als <symbol>-Elemente innerhalb eines versteckten SVG oben auf der Seite definieren. Jedes Symbol hat seinen eigenen viewBox und seine id. Das Sprite lädt einmal und wird für die Session gecacht. currentColor für fill/stroke nutzen, damit jede Verwendung die umgebende Textfarbe erbt — Theming wird trivial.
<!-- Place this hidden SVG at the top of your HTML body -->
<svg xmlns="http://www.w3.org/2000/svg" style="display:none" aria-hidden="true">
<symbol id="icon-home" viewBox="0 0 24 24">
<path d="M12 3 L2 12 H5 V21 H10 V14 H14 V21 H19 V12 H22 Z"/>
</symbol>
<symbol id="icon-user" viewBox="0 0 24 24">
<circle cx="12" cy="8" r="4"/>
<path d="M4 21 C 4 16, 8 14, 12 14 C 16 14, 20 16, 20 21 Z"/>
</symbol>
<symbol id="icon-search" viewBox="0 0 24 24">
<circle cx="11" cy="11" r="7" fill="none" stroke="currentColor" stroke-width="2"/>
<line x1="16" y1="16" x2="21" y2="21" stroke="currentColor" stroke-width="2"/>
</symbol>
</svg>Sprite-Icons nutzen
Jedes <use> instanziiert ein Icon. Die CSS-.icon-Klasse setzt eine Standardgröße; Unterklassen überschreiben für Varianten. Weil die Symbole fill='currentColor' nutzen, folgt die Icon-Farbe der CSS-Eigenschaft color — color auf einem Button setzen und sein Icon passt sich an. So funktionieren große Icon-Systeme (GitHub, Bootstrap).
<!-- Reference any icon with <use> -->
<svg class="icon"><use href="#icon-home"/></svg>
<svg class="icon"><use href="#icon-user"/></svg>
<svg class="icon icon-large"><use href="#icon-search"/></svg>
<style>
.icon {
width: 24px;
height: 24px;
fill: currentColor; /* inherits text color */
display: inline-block;
vertical-align: middle;
}
.icon-large { width: 48px; height: 48px; }
</style>
<!-- Color via CSS color (because fill="currentColor") -->
<button style="color: red;">
<svg class="icon"><use href="#icon-home"/></svg> Home
</button>Sprite aus externer Datei
Externe Sprite-Referenzen (href='file.svg#id') haben lückenhafte Browserunterstützung und CORS-Probleme. Der robuste Ansatz: die Sprite-Datei fetchen und als Inline-HTML oben im body injizieren. Das cache-t über HTTP und funktioniert überall. Viele Build-Tools (svg-sprite-loader, gulp-svg-sprite) automatisieren das.
<!-- icons.svg (a separate file) -->
<svg xmlns="http://www.w3.org/2000/svg" style="display:none">
<symbol id="icon-home" viewBox="0 0 24 24">...</symbol>
</svg>
<!-- Reference external symbols (limited browser support) -->
<svg class="icon"><use href="icons.svg#icon-home"/></svg>
<!-- More reliable: fetch and inject the sprite -->
<script>
fetch("icons.svg")
.then(r => r.text())
.then(text => {
var div = document.createElement("div");
div.style.display = "none";
div.innerHTML = text;
document.body.insertBefore(div, document.body.firstChild);
});
</script>Sprite-Generierung zur Build-Zeit
Build-Tools automatisieren die Sprite-Erzeugung: einzelne .svg-Dateien in einen Ordner legen, und das Tool konkateniert sie zu einem Sprite mit passenden <symbol>-Wrappern. svg-sprite-loader (webpack), gulp-svg-sprite und vite-plugin-svg sind beliebt. So bleiben Icons während der Entwicklung separate Dateien und werden für Produktion gebündelt.
<!-- Using svg-sprite-loader (webpack) -->
// import all icons in a folder
const req = require.context("./icons", true, /\.svg$/);
req.keys().forEach(req);
// In your component:
<svg class="icon"><use href="#icon-home"/></svg>
<!-- Using gulp-svg-sprite -->
// gulpfile.js
const svgSprite = require("gulp-svg-sprite");
gulp.task("sprite", () =>
gulp.src("icons/*.svg")
.pipe(svgSprite({ mode: { symbol: { dest: "." } } }))
.pipe(gulp.dest("dist"))
);
// Outputs dist/symbol/svg/sprite.symbol.svgBarrierefreiheit für Sprite-Icons
Für Barrierefreiheit: Ist ein Icon rein dekorativ (neben Text), aria-hidden='true' setzen. Vermittelt es allein Bedeutung, role='img' und aria-label auf dem <svg> ergänzen. Bei Icon-only-Buttons das aria-label auf den <button> legen, nicht das SVG. Sich nie allein auf das Icon ohne zugänglichen Namen verlassen.
<!-- Decorative icon (hidden from screen readers) -->
<svg class="icon" aria-hidden="true">
<use href="#icon-decoration"/>
</svg>
<!-- Meaningful icon (with label) -->
<svg class="icon" role="img" aria-label="Home">
<use href="#icon-home"/>
</svg>
<!-- Icon button with visible text (icon is decorative) -->
<button>
<svg class="icon" aria-hidden="true"><use href="#icon-home"/></svg>
<span>Home</span>
</button>
<!-- Icon-only button (needs aria-label on the button) -->
<button aria-label="Search">
<svg class="icon" aria-hidden="true"><use href="#icon-search"/></svg>
</button>Zwei- & Mehrfarben-Icons
Mehrfarbige Icons sind mit Sprites knifflig, weil <use>-Klone beim Überschreiben begrenzt sind. Für Zweiton-Icons currentColor für das Primäre und eine fixe Farbe für das Sekundäre nutzen. CSS-eigene Variablen innerhalb des Symbols erlauben es Konsumenten, bestimmte Teile zu überschreiben — eine moderne Technik für flexibles Theming.
<svg style="display:none">
<!-- Icon with two fill regions -->
<symbol id="icon-mail" viewBox="0 0 24 24">
<rect x="2" y="4" width="20" height="16" rx="2" fill="currentColor"/>
<path d="M2 6 L12 13 L22 6" fill="white"/>
</symbol>
</svg>
<!-- Override individual parts via CSS (limited: works if the
symbol uses currentColor and CSS variables) -->
<svg class="icon" style="color: steelblue;">
<use href="#icon-mail"/>
</svg>
<!-- For full multi-color control, use CSS custom properties -->
<symbol id="icon-alert" viewBox="0 0 24 24">
<path fill="var(--icon-bg, currentColor)" d="M12 2 L2 22 H22 Z"/>
<text x="12" y="18" text-anchor="middle" fill="var(--icon-fg, white)">!</text>
</symbol>
<svg class="icon" style="--icon-bg: red; --icon-fg: yellow;">
<use href="#icon-alert"/>
</svg>SVG-Optimierung
SVGO-CLI
SVGO ist der Standard-SVG-Optimierer. Er entfernt Metadaten, Kommentare, Editor-Überbleibsel (Inkscape/Illustrator-Namensräume), ungenutzte defs und redundante Attribute und senkt die Dateigröße oft um 30-60 %. Auf allen Produktions-SVGs ausführen. --show-plugins nutzen, um zu sehen, was er kann, und eine Config-Datei, um bestimmte Optimierungen ein-/auszuschalten.
# Install SVGO globally
npm install -g svgo
# Optimize a single file (overwrites)
svgo icon.svg
# Optimize to a new file
svgo icon.svg -o icon.min.svg
# Optimize a folder
svgo -f icons/ -o icons/min/
# Show available plugins
svgo --show-plugins
# Use a specific config
svgo --config=svgo.config.js icon.svgHäufige Optimierungen
SVGO entfernt: XML-Deklarationen, Editor-Kommentare und Namensräume (Adobe, Inkscape), Metadaten, ungenutztes xlink, enable-background, xml:space, redundantes fill-rule='nonzero' (es ist der Default). Er verkürzt Farbwerte (#FF0000 → red), faltet Whitespace zusammen und verschmilzt Pfade. Das Ergebnis ist semantisch identisch, aber viel kleiner.
<!-- Before optimization (from Illustrator) -->
<?xml version="1.0" encoding="utf-8"?>
<!-- Generator: Adobe Illustrator 25.0 -->
<svg xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink"
xmlns:a="http://ns.adobe.com/AdobeSVGViewerExtensions/3.0/"
width="100px" height="100px" viewBox="0 0 100 100"
enable-background="new 0 0 100 100" xml:space="preserve">
<metadata>...</metadata>
<path d="..." fill="#FF0000" fill-rule="nonzero"/>
</svg>
<!-- After SVGO -->
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">
<path d="..." fill="red"/>
</svg>Pfad-Optimierung
SVGO konvertiert absolute Koordinaten zu relativen, wo kürzer, nutzt H/V statt L für horizontale/vertikale Linien, entfernt unnötige Dezimalstellen und kann Pfade mit identischen Formen verschmelzen. Diese Pfadoptimierungen halbieren oft die Pfad-Stringlänge. Das 'convertPath'-Plugin übernimmt das; es ist standardmäßig an.
<!-- SVGO can merge and simplify paths -->
<!-- Before: multiple paths with redundant points -->
<g>
<path d="M 10 10 L 20 10 L 20 20 L 10 20 Z" fill="red"/>
<path d="M 10 10 L 20 10 L 20 20 L 10 20 Z" fill="none" stroke="black"/>
</g>
<!-- After: merged into one path with combined commands -->
<path d="M10 10h10v10H10z" fill="red" stroke="black"/>
<!-- Path command shortcuts:
L 20 10 -> h 10 (relative horizontal)
L 10 20 -> v 10 (relative vertical)
Z closes the path
-->Gruppierung & Vererbung
Geteilte Attribute (fill, stroke, font) an ein Parent-<g> verschieben, damit Kinder sie erben. Das senkt die Dateigröße und erleichtert Massen-Style-Änderungen. SVGOs 'mergePaths'- und 'moveElemsAttrsToGroup'-Plugins automatisieren das. Bei handgeschriebenem SVG von Anfang an gruppieren — sauberer und wartbarer.
<!-- Before: repeated attributes on each element -->
<svg viewBox="0 0 100 100">
<rect x="10" y="10" width="20" height="20" fill="red" stroke="black" stroke-width="2"/>
<rect x="40" y="10" width="20" height="20" fill="red" stroke="black" stroke-width="2"/>
<rect x="70" y="10" width="20" height="20" fill="red" stroke="black" stroke-width="2"/>
</svg>
<!-- After: group with shared attributes -->
<svg viewBox="0 0 100 100">
<g fill="red" stroke="black" stroke-width="2">
<rect x="10" y="10" width="20" height="20"/>
<rect x="40" y="10" width="20" height="20"/>
<rect x="70" y="10" width="20" height="20"/>
</g>
</svg>Gzip & Auslieferung
SVG gzip-t um 70-90 %, weil es repetitiver XML-Text ist. Sicherstellen, dass dein Webserver image/svg+xml mit gzip oder brotli komprimiert. Für die Auslieferung: kritisches (above-the-fold-)SVG inline setzen, um eine render-blockierende Anfrage zu vermeiden; <img loading='lazy'> für Illustrationen unterhalb des Falzes. SVG aggressiv cachen — es ändert sich selten.
<!-- SVG is text, so it gzips very well (70-90% reduction) -->
<!-- Ensure your server sends SVG with gzip/brotli compression: -->
<!-- Apache .htaccess -->
AddType image/svg+xml .svg
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE image/svg+xml
</IfModule>
<!-- Nginx -->
# gzip_types image/svg+xml;
<!-- HTML: use the right loading strategy -->
<img src="hero.svg" loading="lazy" decoding="async">
<!-- For above-the-fold critical SVG, inline it to avoid a request -->
<!-- For below-the-fold, use <img loading="lazy"> to defer -->SVGO-Config-Datei
Eine Config-Datei passt SVGO an. Übliche Justagen: viewBox behalten (removeViewBox ist standardmäßig an — AUSSCHALTEN, damit Responsivität funktioniert), width/height für fluide SVGs entfernen (removeDimensions) und cleanupIDs für Sprites aktivieren (verkürzt id-Namen). multipass führt Optimierungen aus, bis stabil, für die kleinste Ausgabe.
// svgo.config.js (SVGO 2+)
module.exports = {
multipass: true, // run multiple passes for best result
js2svg: {
indent: 2,
pretty: true, // readable output (false for minified)
},
plugins: [
{ name: "preset-default" }, // sensible defaults
{ name: "removeDimensions", active: true }, // remove width/height (use viewBox)
{ name: "removeViewBox", active: false }, // KEEP viewBox (opposite of default)
{ name: "removeXMLNS", active: false }, // keep xmlns for standalone files
{ name: "cleanupIDs", active: true }, // minify id names
{ name: "mergePaths", active: true },
],
};Best Practices
Barrierefreiheits-Essenz
Für zugängliches SVG: <title> und <desc> ergänzen, via aria-labelledby referenzieren, role='img' setzen, damit Screenreader das SVG als Bild ansagen, und focusable='false' ergänzen, um Tab-Stopp-Probleme bei IE/Edge zu vermeiden. Dekorative SVGs sollten aria-hidden='true' sein. Diese Praktiken machen SVG mit assistiver Technologie nutzbar.
<!-- 1. Always include <title> and <desc> for meaningful SVGs -->
<svg role="img" aria-labelledby="title-id desc-id">
<title id="title-id">Annual Revenue Chart</title>
<desc id="desc-id">A bar chart showing revenue from 2019 to 2023,
rising from $1M to $5M.</desc>
<!-- chart content -->
</svg>
<!-- 2. Decorative SVG: hide from screen readers -->
<svg aria-hidden="true" focusable="false">
<!-- purely visual flourish -->
</svg>
<!-- 3. focusable="false" prevents IE/Edge from making SVG focusable -->
<!-- 4. Use role="img" so screen readers treat SVG as a single image -->viewBox statt width/height
viewBox immer einschließen — er definiert das interne Koordinatensystem und ermöglicht Skalierung. Bei Icons width/height via CSS setzen (nicht Attribute), sodass dasselbe SVG in jeder Größe funktioniert. Für responsive Grafiken width/height ganz weglassen und width:100 %; height:auto in CSS nutzen. SVGOs removeDimensions-Plugin erzwingt das.
<!-- GOOD: viewBox makes the SVG scalable -->
<svg viewBox="0 0 24 24" style="width: 24px; height: 24px;">
<path d="..."/>
</svg>
<!-- BAD: fixed width/height limits scalability -->
<svg width="24" height="24">
<path d="..."/>
</svg>
<!-- For responsive: omit width/height, size with CSS -->
<svg viewBox="0 0 100 100" style="width:100%;height:auto;">
<circle cx="50" cy="50" r="50"/>
</svg>currentColor fürs Theming
fill='currentColor' (oder stroke) nutzen, damit Icons die umgebende Textfarbe erben. Das macht Theming trivial — color auf einem Parent setzen und alle Icons passen sich an. Es ermöglicht auch Hover-/Aktiv-Zustände über CSS-Farbübergänge. Farben in wiederverwendbaren Symbolen nicht hartkodieren, außer sie sind absichtlich fix (etwa ein Markenlogo).
<!-- GOOD: use currentColor so the icon inherits text color -->
<symbol id="icon" viewBox="0 0 24 24">
<path fill="currentColor" d="..."/>
</symbol>
<!-- Usage: color via CSS -->
<button style="color: tomato;">
<svg class="icon"><use href="#icon"/></svg> Themed
</button>
<button style="color: steelblue;">
<svg class="icon"><use href="#icon"/></svg> Also themed
</button>
<!-- BAD: hardcoded colors can't be themed -->
<symbol id="icon">
<path fill="#333333" d="..."/> <!-- always gray -->
</symbol>Semantische Gruppierung
Elemente nach ihrer logischen Rolle gruppieren (Hintergrund, Achsen, Daten, Labels) mit sinnvollen ids, nicht bloß nach Formtyp. Das macht das SVG leichter zu pflegen, zu stylen und zu skripten — ganze Gruppen lassen sich zeigen/verbergen oder umstylen. Es hilft auch bei Barrierefreiheit (aria-labelledby auf Gruppen) und beim Debuggen.
<svg viewBox="0 0 200 200">
<!-- Group by logical component, not just by shape type -->
<g id="background">
<rect width="200" height="200" fill="#f0f0f0"/>
</g>
<g id="chart-axis">
<line x1="20" y1="180" x2="180" y2="180" stroke="black"/>
<line x1="20" y1="20" x2="20" y2="180" stroke="black"/>
</g>
<g id="chart-data" fill="steelblue">
<rect x="30" y="100" width="20" height="80"/>
<rect x="60" y="60" width="20" height="120"/>
<rect x="90" y="80" width="20" height="100"/>
</g>
<g id="labels" font-size="10" fill="black">
<text x="40" y="195" text-anchor="middle">Q1</text>
<text x="70" y="195" text-anchor="middle">Q2</text>
</g>
</svg>Overdraw & Komplexität vermeiden
Overdraw (Formen zeichnen, die komplett verdeckt sind) verschwendet Renderzeit — versteckte Elemente entfernen. Pfade vereinfachen: C/Q-Kurven statt Hunderten winziger Liniensegmente nutzen; Dezimalpräzision reduzieren (10.499999 → 10.5). Bei komplexen Illustrationen erwägen, ob ein Rasterbild kleiner und schneller wäre. Mit dem Paint-Profiler des Browsers messen.
<!-- BAD: layered shapes that cover each other (overdraw) -->
<g>
<rect width="100" height="100" fill="red"/>
<rect width="100" height="100" fill="blue"/> <!-- covers red -->
<rect width="100" height="100" fill="green"/> <!-- covers blue -->
</g>
<!-- The red and blue are never visible but still rendered -->
<!-- GOOD: only draw what's visible -->
<rect width="100" height="100" fill="green"/>
<!-- BAD: path with 10,000 points for a simple shape -->
<path d="..."/> <!-- over-tessellated -->
<!-- GOOD: simplify paths; use curves instead of many line segments -->
<path d="M 10 50 Q 50 10, 90 50"/> <!-- one curve vs 100 lines -->Testen & Validieren
SVGs wie jeden Code testen: XML validieren, browserspezifisches Rendering prüfen (Safari hat Eigenheiten bei manchen Filtern), in verschiedenen Größen testen (16px-Icons vs. 500px-Heroes), die Screenreader-Ausgabe verifizieren und die Dateigröße prüfen (Icons sollten unter 2 KB liegen). SVGO in CI ausführen, damit unoptimierte SVGs nicht ausgeliefert werden. Ein wenig Testen verhindert Produktionsüberraschungen.
<!-- 1. Validate SVG XML -->
<!-- Use the W3C validator: https://validator.w3.org/ -->
<!-- 2. Test in multiple browsers -->
<!-- Chrome, Firefox, Safari, Edge, (IE if required) -->
<!-- 3. Test at different sizes -->
<div style="width: 16px;"><svg>...</svg></div> <!-- icon -->
<div style="width: 500px;"><svg>...</svg></div> <!-- hero -->
<!-- 4. Test with screen readers (VoiceOver, NVDA) -->
<!-- 5. Check file size after optimization -->
ls -la icon.svg # should be under 2KB for simple icons
<!-- 6. Verify currentColor theming works -->
<!-- 7. Ensure no hardcoded dimensions block responsiveness -->Verwandte SVG-Snippets
Copy-paste ready code for common tasks.
Basic Shapes
Rect, circle, ellipse, line, polygon, polyline.
Paths
Draw arbitrary curves via the d attribute.
Gradients
Linear and radial color blends.
Transforms
Translate, rotate, scale, and skew groups.
Text
Styled text and tspans.
Filters
Blur, shadow, and other effects.
Animation
SMIL animate, transform, and opacity.
Patterns
Tileable fills defined in defs.
Was this helpful?