Skip to content

SVG Hoja de referencia

Gráficos vectoriales escalables para imágenes independientes de la resolución.

01

Estructura básica

Esqueleto del documento SVG

El atributo xmlns declara el espacio de nombres SVG. width/height fijan el tamaño renderizado en píxeles. viewBox define el sistema de coordenadas interno. El SVG puede ser un archivo .svg independiente o incrustarse en línea en el HTML, donde la declaración XML y xmlns son opcionales.

svg
<?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>

Incrustar SVG en HTML

El SVG en línea es el más flexible — puedes estilizarlo con CSS y scriptearlo con JS igual que el HTML. <img> y background-image tratan el SVG como imagen estática (sin CSS/JS internos). <object> lo carga como documento separado con su propio DOM, permitiendo algo de scripting.

svg
<!-- 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>

Sistema de coordenadas

SVG usa un sistema de coordenadas zurdo: origen arriba a la izquierda, X a la derecha, Y hacia abajo. El atributo viewBox define el espacio de coordenadas interno — el SVG escala el contenido para encajar en el width/height del elemento, así que un viewBox de 0 0 100 100 en un elemento de 200px renderiza la totalidad al doble.

svg
<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>

Width, height y unidades

Las unidades de usuario (sin sufijo) equivalen a px. Los porcentajes son relativos al padre. Para SVG responsivo, omite width/height y fja viewBox — el SVG escala a su contenedor conservando la relación de aspecto. 'auto' en height con un viewBox conserva las proporciones.

svg
<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>

Espacios de nombres y xlink

SVG 2 introdujo el soporte directo de href en <use>, <image> y <a>, dejando obsoleto xlink:href. Los navegadores modernos soportan el href plano. Conserva el espacio de nombres xlink solo si necesitas soportar navegadores muy antiguos. El SVG en línea en HTML no necesita estrictamente el atributo xmlns.

svg
<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 -->

Comentarios y metadatos

<title> y <desc> aportan texto de accesibilidad leído por los lectores de pantalla — inclúyelos siempre en los SVG significativos. <metadata> guarda datos estructurados (RDF, Dublin Core) para las herramientas. Los comentarios usan la misma sintaxis <!-- --> que el HTML.

svg
<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>
02

Formas

Rectángulo (rect)

rect exige x, y, width, height. rx/ry crean esquinas redondeadas (si solo se fija rx, ry pasa por defecto a rx). fill='none' hace el interior transparente. stroke-width queda centrado sobre el borde, así que la mitad se extiende fuera de la geometría.

svg
<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>

Círculo y elipse

circle se define por el centro (cx, cy) y el radio r. ellipse tiene rx y ry separadas para estirar. Ambos ponen cx/cy a 0 por defecto si se omiten. A diferencia de rect, círculos y elipses no pueden tener esquinas redondeadas — ya son curvas.

svg
<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>

Línea

line conecta dos puntos. No tiene relleno (solo trazo). stroke-dasharray crea líneas discontinuas — el patrón es 'longitud-de-guion,longitud-de-hueco' repetido. stroke-linecap (butt, round, square) controla los extremos.

svg
<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>

Polilínea y polígono

polyline dibuja segmentos de línea conectados sin cerrar la forma (el fill se aplica como si estuviera cerrada, pero ningún trazo conecta los extremos). polygon se cierra automáticamente conectando el último punto con el primero. points es una lista de pares x,y separados por espacios o comas.

svg
<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>

Atributos comunes de formas

fill y stroke son las dos propiedades principales de pintura. opacity afecta al elemento completo; fill-opacity y stroke-opacity actúan independientemente. stroke-linecap (butt/round/square) da forma a los extremos de línea; stroke-linejoin (miter/round/bevel) a las esquinas.

svg
<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>

Reglas de relleno (evenodd)

fill-rule determina cómo se rellenan las regiones solapadas de una forma. 'nonzero' (por defecto) rellena según la dirección de enrollado. 'evenodd' rellena las regiones encerradas un número impar de veces — esto crea el clásico efecto de 'agujero de donut' para paths auto-intersecados y polígonos concéntricos.

svg
<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>
03

Path

Visión general de comandos de path

El elemento <path> es la forma SVG más potente — su atributo d guarda una cadena de comandos de dibujo. Los comandos en mayúscula usan coordenadas absolutas; en minúscula usan coordenadas relativas a la posición actual del lápiz. M, L, C, Q, A, Z son los comandos centrales.

svg
<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 (líneas)

M mueve el lápiz sin dibujar. L dibuja hasta un punto. H/V dibujan líneas horizontales/verticales (una coordenada). Z cierra el path de vuelta al inicio. Las versiones en minúscula (l, h, v, z) interpretan las coordenadas como desplazamientos desde la posición actual, haciendo los subpaths reutilizables.

svg
<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 y S (bezier cúbica)

C dibuja una bezier cúbica con dos puntos de control que tiran de la curva. El primer control (x1,y1) afecta a la tangente inicial; el segundo (x2,y2) a la tangente final. S continúa suavemente reflejando el segundo punto de control de la curva anterior — solo especificas el nuevo segundo control y el punto final.

svg
<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 y T (bezier cuadrática)

Q usa un punto de control en lugar de dos — más simple pero menos flexible que C. T continúa una Q suavemente reflejando su punto de control, exigiendo solo el punto final. Las curvas cuadráticas son comunes en glifos de fuentes y paths de iconos simples donde basta un punto de control.

svg
<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 (arco)

A dibuja un arco elíptico. rx, ry son los radios; x-rotation inclina la elipse. large-arc-flag (0/1) elige el arco más corto o más largo entre los puntos. sweep-flag (0/1) elige antihorario u horario. Los arcos son delicados — muchos diseñadores usan curvas C en su lugar por previsibilidad.

svg
<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>

Ejemplos prácticos de paths

Los iconos reales combinan M, L, C y Z para trazar formas. El corazón usa beziers cúbicas para curvas suaves. El checkmark son solo tres puntos con extremos redondeados. La burbuja de diálogo mezcla líneas H/V para el rectángulo y comandos L para la cola. Empieza simple y luego refina los puntos de control.

svg
<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>
04

Texto

Texto básico

La coordenada y se refiere a la línea base del texto por defecto, no a la parte superior. text-anchor (start/middle/end) controla la alineación horizontal respecto a x. dominant-baseline (auto/middle/hanging/...) controla la alineación vertical. Ambos son esenciales para centrar texto.

svg
<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>

Estilo del texto

El texto SVG soporta la mayoría de propiedades de fuente de CSS como atributos. font-family acepta stacks de fuentes estándar. stroke sobre el texto dibuja un contorno — usa un stroke-width pequeño para no tapar el relleno. letter-spacing y word-spacing funcionan como en CSS.

svg
<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 (subtexto)

<tspan> te permite estilizar o posicionar partes del texto de forma distinta — como <span> en HTML. dx/dy desplazan respecto al carácter anterior; x/y absolutos saltan a una posición nueva (usa x con el valor original y dy para saltos de línea). tspan es cómo construyes texto multilínea en SVG.

svg
<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>

Texto sobre un path

<textPath> renderiza texto a lo largo de cualquier elemento path. Referencia el path por id vía href (moderno) o xlink:href (heredado). startOffset (una longitud o porcentaje) posiciona el texto a lo largo del path. Es la técnica estándar para etiquetas curvadas sobre arcos, círculos o formas personalizadas.

svg
<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>

Modo de escritura y dirección

writing-mode='tb' hace que el texto fluya de arriba abajo (común en la tipografía de Asia Oriental). direction='rtl' invierte el orden de los caracteres para escrituras de derecha a izquierda. Para rotación arbitraria, usa el atributo transform — rotate(ángulo, cx, cy) rota alrededor del punto (cx, cy).

svg
<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>

Accesibilidad del texto

El texto SVG es seleccionable y accesible por defecto, pero los SVG decorativos deberían tener <title> y <desc>. Para SVG en línea usados como elementos de UI, añade role='img' y aria-label para que los lectores de pantalla anuncien el significado. Evita poner información esencial solo en texto SVG — el texto HTML es más accesible.

svg
<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>
05

Degradados

Degradado lineal

linearGradient transiciona colores a lo largo de una línea. x1/y1 a x2/y2 definen la dirección (0% 0% a 100% 0% es de izquierda a derecha). Los elementos <stop> definen los puntos de color; offset va de 0-100% o 0-1. Referencia el degradado con fill='url(#id)'. Los degradados deben vivir en <defs>.

svg
<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>

Degradado radial

radialGradient irradia desde un punto central. cx/cy es el centro, r el radio. fx/fy es el punto focal (donde empieza el color del 0%) — desplazarlo crea un efecto de luz direccional. Valores por defecto: cx/cy al 50%, r al 50%, fx/fy reflejando cx/cy.

svg
<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>

Unidades y propagación del degradado

gradientUnits='objectBoundingBox' (por defecto) hace las coordenadas relativas a cada forma (0-1), así que el mismo degradado encaja en cualquier elemento. 'userSpaceOnUse' usa coordenadas SVG absolutas, así que el degradado se posiciona en el documento — útil para alinear degradados a través de varias formas.

svg
<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>

Opacidad de parada y paradas múltiples

Cada stop puede llevar stop-opacity (0-1) para transiciones de transparencia. Combina muchos stops para rampas de color complejas. Este degradado de atardecer se desvanece de azul transparente arriba a rojo oscuro opaco abajo — una técnica común para fondos atmosféricos.

svg
<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>

Reutilizar degradados

Define un degradado una vez en <defs> y referéncialo en cualquier número de formas vía fill='url(#id)'. Usa href para derivar un degradado nuevo de uno existente, sobrescribiendo solo algunos atributos (como la dirección). Esto mantiene tu SVG DRY y reduce el tamaño del archivo.

svg
<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>
06

Patrones

Patrón básico

Un <pattern> tesela un gráfico repetido. Los hijos del patrón definen una tesela; width/height fijan el tamaño de la tesela. patternUnits='userSpaceOnUse' (recomendado) significa que las dimensiones de la tesela están en unidades de usuario SVG, independientes de la forma rellenada. Referéncialo con fill='url(#id)'.

svg
<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>

Unidades del patrón

patternUnits='objectBoundingBox' (por defecto) dimensiona las teselas como fracción de la forma — el patrón escala con cada forma. 'userSpaceOnUse' usa unidades absolutas, así que el patrón es consistente entre formas sin importar el tamaño. La mayoría de patrones reales usan userSpaceOnUse.

svg
<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>

Rayas y tablero de ajedrez

patternTransform rota, escala o cizalla el patrón entero. Para rayas, rellena la mitad de la tesela con un color y la otra mitad con otro, y luego rota. El tablero usa cuatro rects (o dos pares en L) por tesela. Estos patrones son comunes en diagramas y texturas.

svg
<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>

Unidades de contenido del patrón

patternContentUnits controla el sistema de coordenadas de los elementos hijos del patrón (no del tamaño de la tesela). 'objectBoundingBox' hace las coordenadas de los hijos fracciones de la forma — útil cuando quieres que el detalle del patrón escale proporcionalmente con cada forma. Raro pero potente.

svg
<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>

Patrones anidados

Los patrones pueden contener degradados, otros patrones o cualquier contenido SVG. Este patrón de cuadrícula rellena cada celda con un degradado sutil y dibuja líneas de cuadrícula encima. El anidamiento te permite construir texturas complejas. Mantén los tamaños de tesela razonables para evitar problemas de rendimiento con teselas muy pequeñas.

svg
<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>
07

Transform

Translate

translate(tx, ty) mueve un elemento por tx, ty. Si se omite ty, pasa por defecto a 0. La transformación se aplica al sistema de coordenadas del elemento, así que los atributos x/y son relativos al origen trasladado. Las transformaciones CSS (vía style) funcionan sobre SVG en línea en los navegadores modernos y pueden animarse con transiciones CSS.

svg
<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(ángulo, cx, cy) rota por grados alrededor del punto (cx, cy). Sin cx/cy, rota alrededor del origen (0,0), que a menudo no es lo que quieres. Los ángulos son horarios (positivos) o antihorarios (negativos). Especifica siempre el centro para rotar un elemento en el sitio.

svg
<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 y skew

scale(sx, sy) multiplica dimensiones; un argumento escala ambas por igual. Escalar también afecta al stroke-width y a las posiciones. skewX/skewY cizallan el elemento a lo largo de un eje por un ángulo. Todas las transformaciones son relativas al origen (0,0), así que escalar una forma en x=100 también la mueve.

svg
<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>

Transformación de matriz

matrix(a,b,c,d,e,f) es la forma subyacente de todas las transformaciones. a,d escalan; b,c cizallan; e,f trasladan. La mayoría de desarrolladores usan las transformaciones con nombre (translate, rotate, etc.) por legibilidad, pero matrix es lo que generan las herramientas y es útil para combinar transformaciones o parsear.

svg
<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>

Combinar transformaciones

Varias transformaciones en el atributo se aplican de derecha a izquierda (la más a la derecha ocurre primero). Esto significa que 'translate(100,100) rotate(45)' rota primero la forma alrededor de su propio origen y luego la mueve — normalmente lo que quieres. Las transformaciones CSS con transform-origin suelen ser más intuitivas para SVG en línea.

svg
<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)

Al animar SVG con CSS, fija transform-origin explícitamente (en unidades de usuario SVG) y transform-box (fill-box para la caja envolvente del elemento, view-box para el lienzo SVG). Sin esto, la rotación se centra en el origen del SVG, no en el elemento. Las animaciones y transiciones CSS funcionan sobre SVG en línea.

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>
08

Grupo (g)

Agrupamiento básico

<g> agrupa elementos para que compartan atributos (fill, stroke, transform, etc.) y puedan manipularse como una unidad. Los hijos heredan los atributos de presentación del grupo. Los grupos son esenciales para organizar SVGs complejos y aplicar transformaciones a varias formas a la vez.

svg
<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>

Transformaciones de grupo

Una transformación sobre <g> crea un nuevo sistema de coordenadas para sus hijos. Esta es la clave para construir componentes reutilizables: diseña alrededor de (0,0) y luego posiciona el grupo entero con translate. Las coordenadas de los hijos son relativas al origen transformado del grupo.

svg
<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>

Grupos anidados

Los grupos pueden anidarse a cualquier profundidad. Cada transformación anidada se compone — el elemento más interno queda afectado por todas las transformaciones de los ancestros en orden. Así construyes escenas jerárquicas (por ejemplo, un personaje con extremidades rotantes, cada extremidad con manos móviles). Mantén el anidamiento razonable por rendimiento.

svg
<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>

IDs y referencias de grupo

Dale a un grupo un id y referéncialo con <use href='#id'> para duplicarlo. Esta es la base de los sprites SVG y los componentes reutilizables. El grupo puede vivir en <defs> (no renderizado directamente) e instanciarse muchas veces con transformaciones distintas. Sobrescribir atributos en <use> está limitado.

svg
<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>

Grupos condicionales

Los grupos con ids son puntos de enganche perfectos para CSS (hover, estados activos) y el manejo de eventos de JavaScript. Trata un <g> como un componente: agrupa sus formas, dale un id e interactúa con él como unidad. Los listeners de eventos sobre un grupo atrapan los eventos de la totalidad de sus hijos.

svg
<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>

Grupo vs symbol

<symbol> está hecho a propósito para iconos reutilizables: nunca se renderiza directamente y tiene su propio viewBox, así que <use> puede dimensionarlo independientemente. <g> en <defs> también funciona pero carece de la característica viewBox. Para sistemas de iconos, prefiere <symbol> — maneja el escalado y la relación de aspecto automáticamente.

svg
<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>
09

Use / Symbol / Defs

Elemento defs

<defs> guarda definiciones reutilizables que no se dibujan hasta referenciarse: degradados, patrones, filtros, rutas de recorte, máscaras, símbolos y grupos. Ponerlos en defs mantiene limpia la salida renderizada y señala la intención. Cualquier cosa fuera de defs se renderiza de inmediato.

svg
<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>

Elemento use

<use> clona y renderiza un elemento definido (g, symbol o cualquier forma). x/y posicionan la instancia. fill/stroke en <use> sobrescriben al original solo si el original no los especificó (herencia CSS). transform se aplica a la instancia. Así funcionan los sprites SVG.

svg
<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>

Elemento symbol

<symbol> define un gráfico reutilizable con su propio viewBox. A diferencia de <g>, nunca se renderiza directamente y escala para encajar en las dimensiones del elemento <use>. fill='currentColor' deja que el consumidor fije el color vía la propiedad CSS color. Este es el patrón estándar de los sistemas de iconos SVG.

svg
<!-- 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>

Referencias SVG externas

<use> puede referenciar símbolos en archivos SVG externos vía href='archivo.svg#id'. Sin embargo, el soporte de navegadores es irregular (sin IE, restricciones CORS) y se rompe con file://. El enfoque fiable es incrustar en línea un sprite SVG oculto al principio de tu HTML y referenciar símbolos dentro del mismo documento.

svg
<!-- 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. -->

Sobrescribir atributos de use

Cuando la forma original omite un atributo de presentación (como fill), <use> puede fijarlo — la instancia hereda el valor. Si el original especifica fill, el fill del use se ignora (los atributos de presentación vencen a la herencia CSS). Para hacer símbolos personalizables, omite los atributos que quieras sobrescribir.

svg
<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>

Anidamiento de símbolos y sprite

Este es el patrón de producción para iconos SVG: un sprite SVG oculto al principio del documento que contiene la totalidad de los iconos como <symbol>, y luego <use> para renderizarlos en cualquier lugar. currentColor hace que los iconos hereden el color del texto. CSS controla el tamaño. El sprite se cachea tras la primera carga, rápido en cada página.

svg
<!-- 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>
10

Filtros

Fundamentos de filtros

Un <filter> contiene una o más primitivas de filtro (elementos fe*) que procesan el gráfico. in='SourceGraphic' toma el renderizado propio del elemento. Aplícalo con filter='url(#id)'. Los filtros pueden ser caros — úsalos con moderación en elementos pequeños, no en fondos grandes.

svg
<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>

Sombra proyectada

Una sombra proyectada combina feOffset (mover), feGaussianBlur (suavizar), feFlood (color), feComposite (aplicar color a la sombra) y feMerge (poner la sombra bajo el original). El x/y/width/height del filtro (por defecto -10% a 110%) debe agrandarse o la sombra se recorta.

svg
<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>

Sombra simple (CSS)

Para sombras simples sobre SVG en línea, el filter: drop-shadow() de CSS es mucho más simple que construir un filtro SVG. Respeta el contorno real de la forma (no solo la caja envolvente como box-shadow). Usa filtros SVG solo para efectos complejos de varios pasos que el CSS no pueda expresar.

svg
<!-- 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 -->

Matriz de color

feColorMatrix transforma colores vía una matriz 5x4 (RGBA de entrada, RGBA de salida). type='saturate' con valores 0-1 desatura; type='hueRotate' rota el tono en grados; type='luminanceToAlpha' convierte el brillo en alfa. Útil para escala de grises, sepia y ajustes de color sobre contenido SVG.

svg
<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>

Efectos de iluminación

feSpecularLighting y feDiffuseLighting simulan iluminación 3D sobre el mapa de alturas de una forma 2D (derivado del alfa). surfaceScale controla la profundidad; el elemento de luz (fePointLight, feDistantLight, feSpotLight) fija la dirección. Combinado con feComposite obtienes efectos de grabado, bisel y texto 3D.

svg
<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>

Turbulencia (textura)

feTurbulence genera ruido procedimental (tipo fractal o turbulencia) — útil para texturas como estática, nubes, agua o grano de papel. baseFrequency controla la escala (0.5 = fina, 0.05 = nubosa). numOctaves añade detalle al coste de velocidad. Combínalo con feColorMatrix o feDisplacementMap para efectos.

svg
<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>
11

Recorte y enmascarado

Clip path

clipPath define un límite de borde duro — los píxeles dentro son visibles, los de fuera ocultos. La forma de recorte en sí no se dibuja. clip-path lo referencia vía url(#id). El recorte es binario (dentro o fuera); para transiciones suaves, usa máscaras. El texto como ruta de recorte crea el clásico efecto 'imagen dentro del texto'.

svg
<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>

Máscara

A diferencia de clip-path (binaria), las máscaras soportan alfa — las zonas blancas son totalmente visibles, las negras ocultas, y las grises parcialmente transparentes. Usa un degradado como contenido de la máscara para fundidos suaves. Las máscaras son más pesadas que las rutas de recorte pero esenciales para transiciones suaves y efectos fotográficos.

svg
<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>

Unidades del clip path

clipPathUnits='objectBoundingBox' hace que la ruta de recorte escale a la caja envolvente de cada elemento (coordenadas 0-1), así que una ruta de recorte funciona para formas de tamaños distintos. 'userSpaceOnUse' (por defecto) usa coordenadas SVG absolutas. La mayoría de recortes reutilizables usan objectBoundingBox.

svg
<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

El CSS clip-path soporta formas básicas (circle, ellipse, polygon, inset) directamente sin SVG, y puede referenciar elementos clipPath de SVG vía url(#id). Funciona también sobre elementos HTML, no solo SVG. El enmascarado CSS también está soportado en navegadores modernos vía mask-image.

svg
<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>

Práctico: imagen en texto

Recortar un degradado o imagen al texto es una técnica de diseño popular. El clipPath contiene un elemento <text>; el rect recortado se rellena con el degradado, visible solo dentro de las formas de las letras. Funciona también con <image> — mete una foto dentro del texto para cabeceras estilo revista.

svg
<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>
12

Animación (SMIL)

animate (básico)

<animate> transiciona un atributo a lo largo del tiempo. attributeName es el objetivo; from/to definen el rango; dur la duración; repeatCount='indefinite' repite para siempre. Las animaciones SMIL son declarativas (sin JS) y funcionan en la mayoría de navegadores salvo IE. La animación vive como hijo del elemento objetivo.

svg
<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> anima el atributo transform. type selecciona la operación (rotate, scale, translate, skewX, skewY). Para rotate, from/to son 'ángulo cx cy' (punto central). Así giras elementos sin JavaScript. Solo puede correr un animateTransform por elemento salvo que uses additive='sum'.

svg
<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> mueve un elemento a lo largo de un path. Referencia el path con <mpath href='#id'> o define path directamente. rotate='auto' orienta el elemento para que mire en la dirección del viaje — esencial para flechas, coches o personajes. Es la forma SVG de hacer animación por path sin JS.

svg
<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 y easing

Para animaciones de varios pasos, usa values (separados por punto y coma), keyTimes (fracciones 0-1) y keySplines (easing bezier por segmento). calcMode='spline' habilita el easing; 'linear' es el valor por defecto. Esto refleja la animación por keyframes de CSS pero en SVG puro. El rect rebota de un lado a otro con easing suave.

svg
<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 y disparadores

begin puede ser un desplazamiento de tiempo (2s), un evento (click, mouseenter) o una referencia al evento de otra animación (anim1.end, anim1.begin+1s). fill='freeze' sostiene el valor final tras terminar la animación (de lo contrario vuelve de golpe). Esto habilita animaciones disparadas por clic y encadenadas sin JavaScript.

svg
<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>

Alternativa de animación CSS

Para SVG en línea en páginas web, las animaciones CSS suelen ser más simples que SMIL y tienen mejores herramientas. Usa transform-box: fill-box para que transform-origin: center se refiera al elemento, no al lienzo SVG. SMIL sigue siendo útil para archivos SVG independientes (sin CSS disponible) y el movimiento por path.

svg
<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 -->
13

Eventos

Eventos de ratón

Los elementos SVG soportan los eventos DOM estándar: click, mouseenter, mouseleave, mousemove, mousedown, mouseup, dblclick. Usa addEventListener como harías en elementos HTML. 'this' dentro de un manejador se refiere al elemento SVG. Usa setAttribute para cambiar propiedades reactivamente.

svg
<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>

Eventos táctiles

SVG soporta touchstart, touchmove, touchend. Convierte coordenadas de pantalla a coordenadas SVG usando createSVGPoint y getScreenCTM().inverse() — esencial cuando el SVG está escalado o es responsivo. preventDefault() en touchstart evita la interferencia de gestos como el scroll.

svg
<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>

Conversión de coordenadas

Cuando un SVG tiene un viewBox distinto de su tamaño en píxeles, las coordenadas de pantalla no se mapean 1:1 a coordenadas SVG. createSVGPoint + getScreenCTM().inverse() convierte correctamente, contando el viewBox, el escalado CSS e incluso las transformaciones de los elementos ancestro. Esencial para una detección de clics precisa.

svg
<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>

Delegación de eventos

La delegación de eventos — un listener en un grupo padre en lugar de muchos en los hijos — es más eficiente y maneja automáticamente las formas añadidas dinámicamente. e.target es la forma clicada; e.currentTarget el elemento con el listener. Usa atributos data-* para guardar metadatos por forma.

svg
<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>

Interacción de arrastre

Este es el patrón clásico de arrastre en SVG: mousedown fija un flag, mousemove actualiza la posición del elemento (usando coordenadas SVG convertidas), mouseup limpia el flag. Adjunta mousemove/mouseup al SVG (no al elemento) para que el arrastre continúe incluso cuando el cursor sale de la forma. Es la fundación de los editores basados en SVG.

svg
<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>
14

DOM de JavaScript

Crear elementos

Los elementos SVG deben crearse con document.createElementNS(espacioDeNombres, nombreEtiqueta) — createElement no funciona para SVG (crea elementos HTML desconocidos). El espacio de nombres SVG es 'http://www.w3.org/2000/svg'. Usa setAttribute para las propiedades. Es la fundación de la generación dinámica de SVG.

svg
<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>

Modificar elementos

Usa setAttribute/getAttribute para los atributos de presentación SVG (fill, stroke, width, etc.). classList funciona de forma fiable entre navegadores. Fjar style.fill funciona porque se mapea a la propiedad CSS. Evita innerHTML para SVG (inconsistente entre navegadores); construye el DOM con createElementNS.

svg
<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>

Leer geometría

getBBox() devuelve la caja envolvente en unidades de usuario SVG (ignorando transformaciones). getBoundingClientRect() devuelve coordenadas de pantalla (tras todas las transformaciones y CSS). getTotalLength() da la longitud del path/línea; getPointAtLength(d) devuelve el punto a la distancia d — esencial para animaciones por path y pruebas de impacto.

svg
<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 y atributos de datos

Los elementos SVG soportan atributos data-* y la propiedad dataset igual que el HTML. Es la forma limpia de asociar datos con formas para aplicaciones interactivas — guarda IDs de nodos, etiquetas o estado sin contaminar los atributos visuales. Lee con element.dataset.clave, escribe con lo mismo.

svg
<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>

Generación dinámica de paths

Generar SVG dinámicamente es la base de los gráficos personalizados. Construye el atributo d del path concatenando comandos M/L desde tus datos y luego crea el elemento con createElementNS. Este enfoque da control total sin librería de gráficos. Para visualizaciones complejas, considera D3.js, que envuelve este patrón con elegancia.

svg
<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>

Consejos de rendimiento

Por rendimiento: agrupa las inserciones del DOM con DocumentFragment (un solo reflow), usa requestAnimationFrame para animaciones JS (sincroniza con el refresco de pantalla) y evita consultar atributos en bucles ajustados (cachea valores). El SVG sobresale hasta unos pocos cientos de elementos; para miles (partículas, gráficos densos), Canvas o WebGL son más rápidos.

svg
<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>
15

SVG responsivo (viewBox)

Fundamentos de viewBox

viewBox='minX minY width height' define el sistema de coordenadas interno. Los dos primeros valores desplazan la vista; los dos últimos hacen zoom. El SVG escala esta región para encajar en su width/height. Esto desacopla tus coordenadas de dibujo del tamaño renderizado — dibuja una vez a cualquier escala, en una caja de 100x100 o 1920x1080.

svg
<!-- 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 controla cómo encaja el viewBox en el elemento cuando las relaciones de aspecto difieren. 'meet' (por defecto) encaja por completo, dejando bandas del exceso. 'slice' llena por completo, recortando el desborde. 'none' estira, distorsionando. La parte xMidYMid controla la alineación: Min/Mid/Max para ambos ejes.

svg
<!-- 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>

SVG totalmente responsivo

Para SVG responsivo: omite los atributos width/height, fja viewBox y controla el tamaño con CSS (width: 100%, height: auto). El SVG escala a su contenedor conservando la relación de aspecto. display: block elimina el hueco de línea base del SVG en línea. Este es el patrón estándar del SVG fluido en layouts responsivos.

svg
<!-- 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>

SVG anidado y overflow

Los elementos <svg> anidados crean viewports independientes con su propio viewBox y preserveAspectRatio. Es potente para gráficos con paneles de aspecto fijo o componentes de UI. overflow='visible' deja que el contenido se dibuje fuera del viewport anidado (oculto por defecto). Cada svg anidado puede escalar su contenido independientemente.

svg
<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>

Tamaño de texto fluido

Los tamaños de fuente dentro de un SVG con viewBox escalan con el SVG — una fuente de 20px en un viewBox de 400 de ancho mostrado a 800px de ancho se renderiza a 40px. Para hacer el texto responsivo al viewport del navegador (no del SVG), usa unidades de viewport CSS (vw, vh) en un atributo style. Así escalan fluidamente los titulares SVG.

svg
<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 -->

Control de relación de aspecto

Combina CSS aspect-ratio en el contenedor con width/height 100% en el SVG para un comportamiento responsivo predecible. Esto previene el salto de layout (CLS) reservando espacio antes de que el SVG cargue. El viewBox coincide con la relación de aspecto para que el contenido no se distorsione. Es la buena práctica moderna para incrustaciones SVG responsivas.

svg
<!-- 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 -->
16

SVG vs Canvas

Modelo de renderizado

SVG es de modo retenido: cada forma es un elemento del DOM que puedes inspeccionar, estilizar y volver a animar después. Canvas es de modo inmediato: emites comandos de dibujo que pintan píxeles, y las formas no persisten como objetos. SVG es mejor para UI interactiva; Canvas para miles de píxeles dinámicos.

svg
<!-- 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>

Cuándo usar SVG

Elige SVG para: gráficos independientes de la resolución (iconos, logos), accesibilidad (los lectores de pantalla recorren el DOM), interactividad (eventos por forma), SEO (el texto es seleccionable) y conteos moderados de elementos (hasta unos pocos cientos). Los archivos SVG son texto (comprimen bien con gzip) y editables en herramientas de diseño.

svg
<!-- 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> -->

Cuándo usar Canvas

Elige Canvas para: conteos altos de elementos (miles de formas), redibujados por fotograma (juegos, partículas), manipulación de píxeles (filtros, efectos) y cuando no necesites accesibilidad por DOM. Canvas es más rápido en puro rendimiento de píxeles pero más difícil de hacer accesible o interactivo a nivel de forma individual.

svg
<!-- 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>

Comparación de rendimiento

El rendimiento de SVG degrada con el conteo de elementos porque cada forma es un nodo del DOM con manejo de eventos, estilos y layout. Canvas tiene una sobrecarga constante por fotograma sin importar el conteo de formas. El cruce está alrededor de 500-2000 elementos según la complejidad. Para gráficos estáticos o poco animados, SVG está bien; para escenas densas en tiempo real, usa Canvas.

svg
<!-- 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)
-->

Enfoque híbrido

Combina ambos: Canvas para la capa densa y redibujada con frecuencia (mapa de calor, partículas) y SVG superpuesto para la UI interactiva (tooltips, tiradores de selección, etiquetas). La capa SVG se mantiene nítida y accesible mientras el Canvas maneja el trabajo pesado de píxeles. Este patrón lo usan librerías de mapas como Leaflet y herramientas de gráficos como ECharts.

svg
<!-- 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>

Comparación de accesibilidad

El SVG es inherentemente más accesible: el DOM es transitable, el texto es seleccionable y buscable, y <title>/<desc> aportan descripciones. Canvas exige trabajo extra — debes añadir role/aria-label y proporcionar contenido de respaldo textual dentro de la etiqueta <canvas>. Para gráficos y visualizaciones de datos, la accesibilidad del SVG es una gran ventaja.

svg
<!-- 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 -->
17

Sprite SVG

Configuración del sprite en línea

Define la totalidad de los iconos como elementos <symbol> dentro de un SVG oculto al principio de la página. Cada symbol tiene su propio viewBox e id. El sprite carga una vez y queda cacheado para la sesión. Usar currentColor para fill/stroke deja que cada uso herede el color del texto circundante, haciendo la tematización trivial.

svg
<!-- 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>

Usar iconos del sprite

Cada <use> instancia un icono. La clase CSS .icon fija un tamaño por defecto; las subclases lo sobrescriben para variantes. Como los symbols usan fill='currentColor', el color del icono sigue a la propiedad CSS color — fja color en un botón y su icono coincide. Así funcionan los grandes sistemas de iconos (GitHub, Bootstrap).

svg
<!-- 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 desde archivo externo

Las referencias de sprite externas (href='archivo.svg#id') tienen soporte irregular de navegadores y problemas de CORS. El enfoque robusto: obtén el archivo sprite con fetch e inyéctalo como HTML en línea al principio del body. Esto cachea vía HTTP y funciona en todas partes. Muchas herramientas de build (svg-sprite-loader, gulp-svg-sprite) lo automatizan.

svg
<!-- 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>

Generación de sprite en build

Las herramientas de build automatizan la creación del sprite: suelta archivos .svg individuales en una carpeta y la herramienta los concatena en un sprite con envoltorios <symbol> adecuados. svg-sprite-loader (webpack), gulp-svg-sprite y vite-plugin-svg son populares. Esto mantiene los iconos como archivos separados durante el desarrollo pero los agrupa para producción.

svg
<!-- 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.svg

Accesibilidad de los iconos del sprite

Por accesibilidad: si un icono es puramente decorativo (junto a texto), márcalo aria-hidden='true'. Si transmite significado por sí solo, añade role='img' y aria-label en el <svg>. Para botones de solo icono, pon el aria-label en el <button>, no en el SVG. Nunca confíes en el icono solo sin un nombre accesible.

svg
<!-- 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>

Iconos de dos tonos y multicolor

Los iconos multicolor son delicados con sprites porque los clones de <use> están limitados en lo que puedes sobrescribir. Para iconos de dos tonos, usa currentColor para el principal y un color fijo para el secundario. Las propiedades personalizadas CSS (variables) dentro del symbol dejan que los consumidores sobrescriban partes concretas — una técnica moderna para temas flexibles.

svg
<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>
18

Optimización de SVG

CLI de SVGO

SVGO es el optimizador de SVG estándar. Elimina metadatos, comentarios, basura de editores (espacios de nombres de Inkscape/Illustrator), defs sin usar y atributos redundantes, a menudo recortando el tamaño del archivo un 30-60%. Córrelo en cada SVG de producción. Usa --show-plugins para ver lo que puede hacer, y un archivo de configuración para habilitar/deshabilitar optimizaciones concretas.

svg
# 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.svg

Optimizaciones comunes

SVGO elimina: declaraciones XML, comentarios y espacios de nombres de editores (Adobe, Inkscape), metadatos, xlink sin usar, enable-background, xml:space, fill-rule='nonzero' redundante (es el valor por defecto). Acorta los valores de color (#FF0000 → red), colapsa espacios en blanco y fusiona paths. El resultado es semánticamente idéntico pero mucho menor.

svg
<!-- 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>

Optimización de paths

SVGO convierte coordenadas absolutas a relativas donde es más corto, usa H/V en lugar de L para líneas horizontales/verticales, elimina decimales innecesarios y puede fusionar paths con formas idénticas. Estas optimizaciones de path a menudo reducen a la mitad la longitud de la cadena del path. El plugin 'convertPath' se encarga de esto; está activado por defecto.

svg
<!-- 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
-->

Agrupación y herencia

Mueve los atributos compartidos (fill, stroke, font) a un <g> padre para que los hijos los hereden. Esto reduce el tamaño del archivo y facilita los cambios de estilo masivos. Los plugins 'mergePaths' y 'moveElemsAttrsToGroup' de SVGO lo automatizan. Al escribir SVG a mano, agrupa desde el principio — es más limpio y mantenible.

svg
<!-- 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 y entrega

El SVG comprime un 70-90% con gzip porque es texto XML repetitivo. Asegúrate de que tu servidor web comprime image/svg+xml con gzip o brotli. Para la entrega: incrusta en línea el SVG crítico (sobre el pliegue) para evitar una petición bloqueante del render; usa <img loading='lazy'> para las ilustraciones bajo el pliegue. Cachea el SVG agresivamente — rara vez cambia.

svg
<!-- 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 -->

Archivo de configuración de SVGO

Un archivo de configuración personaliza SVGO. Ajustes comunes: conservar viewBox (removeViewBox está activado por defecto — desactívalo para que la responsividad funcione), quitar width/height para SVG fluidos (removeDimensions) y habilitar cleanupIDs para sprites (acorta los nombres de id). multipass corre las optimizaciones hasta estabilizarse para la salida más pequeña.

svg
// 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 },
  ],
};
19

Buenas prácticas

Esenciales de accesibilidad

Para un SVG accesible: añade <title> y <desc>, refiérete a ellos vía aria-labelledby, fja role='img' para que los lectores de pantalla anuncien el SVG como imagen, y añade focusable='false' para prevenir problemas de tabulación en IE/Edge. Los SVG decorativos deberían llevar aria-hidden='true'. Estas prácticas hacen el SVG usable con tecnología de asistencia.

svg
<!-- 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 -->

Usa viewBox, no width/height

Incluye siempre viewBox — define el sistema de coordenadas interno y habilita el escalado. Para iconos, fja width/height vía CSS (no atributos) para que el mismo SVG funcione a cualquier tamaño. Para gráficos responsivos, omite width/height por completo y usa width:100%; height:auto en CSS. El plugin removeDimensions de SVGO impone esto.

svg
<!-- 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 para temas

Usa fill='currentColor' (o stroke) para que los iconos hereden el color del texto circundante. Esto hace la tematización trivial — fija color en un padre y la totalidad de los iconos coinciden. También habilita estados hover/active vía transiciones de color CSS. Evita fijar colores a fuego en symbols reutilizables salvo que estén intencionalmente fijados (como el logo de una marca).

svg
<!-- 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>

Agrupación semántica

Agrupa los elementos por su papel lógico (fondo, ejes, datos, etiquetas) con ids significativos, no solo por tipo de forma. Esto hace el SVG más fácil de mantener, estilizar y scriptear — puedes mostrar/ocultar o restilizar grupos enteros. También ayuda con la accesibilidad (aria-labelledby en los grupos) y la depuración.

svg
<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>

Evitar el sobredibujo y la complejidad

El sobredibujo (dibujar formas totalmente cubiertas) desperdicia tiempo de render — elimina los elementos ocultos. Simplifica los paths: usa curvas C/Q en lugar de cientos de segmentos de línea diminutos; reduce la precisión decimal (10.499999 → 10.5). Para ilustraciones complejas, considera si una imagen raster sería menor y más rápida. Perfila con el profiler de pintado del navegador.

svg
<!-- 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 -->

Pruebas y validación

Prueba los SVG como cualquier código: valida el XML, comprueba el renderizado entre navegadores (Safari tiene peculiaridades con algunos filtros), prueba a varios tamaños (iconos de 16px frente a héroes de 500px), verifica la salida del lector de pantalla y comprueba el tamaño del archivo (los iconos deberían pesar menos de 2KB). Corre SVGO en CI para evitar que se publiquen SVG sin optimizar. Un poco de pruebas evita sorpresas en producción.

svg
<!-- 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 -->

Was this helpful?

Learning path

Learn from scratch

Learn this language from the ground up with structured lessons.