SVG/JavaScript

Ricardo Borillo Domenech

http://xml-utils.com

1. Introducción
2. Beneficios de la utilización de SVG
3. SVG: Estructura básica de un documento
4. SVG: Definición del sistema de coordenadas
5. SVG: Geometría
5.1. Rectángulo
5.2. Círculo
5.3. Elipse
5.4. Línea
5.5. Polilínea
5.6. Polígono
5.7. Texto
5.8. Caminos
6. SVG: Elementos disponibles
6.1. SVG
6.2. G
6.3. Referencias dentro de SVG
6.4. DEFS
6.5. DESC y TITLE
6.6. SYMBOL
6.7. USE
6.8. IMAGE
6.9. Transformaciones
7. SVG: Scripting
7.1. Funciones de ejemplo para el de DOM
7.2. Funciones de ejemplo para el uso del modelo de objetos de SVG
8. SMIL
9. HTML/XHTML
10. Implementación, herramientas y enlaces de interés

1. Introducción

Para empezar diremos que SVG significa Scalable Vector Graphics y que define un lenguaje basado en XML para la construcción de gráficos vectoriales 2D con multitud de efectos y características avanzadas.

Repasando algunas de las tecnologías o estándares del W3, tenemos que:

  • XML o XHTML representan los datos, la información a representar. Algunos lenguajes basados en XML como MathML o CML definen conjuntos concretos de tags destinados a un fin específico como son el lenguaje matemático o químico.

  • CSS o XSL definen la presentación que tendrán los datos en diversos medios.

  • SVG define la representación de gráficos dentro de cualquier documento.

  • SMIL permite realizar animaciones basadas en tiempo.

SVG es el equivalente, basado en estándares, a la opción comercial de Macromedia: Flash. SVG es una recomendación del W3, el contenido de cada fichero es XML y no un formato binario cerrado.

 <?xml version="1.0"?>
 <svg xmlns="http://www.w3.org/2000/svg">
   <g style="fill-opacity:0.7; stroke:black; stroke-width:0.1cm;">
     <circle cx="6cm" cy="2cm" r="100" style="fill:red;" transform="translate(0,50)" />
     <circle cx="6cm" cy="2cm" r="100" style="fill:blue;" transform="translate(70,150)" />
     <circle cx="6cm" cy="2cm" r="100" style="fill:green;" transform="translate(-70,150)"/> 
   </g>
 </svg>

Desde Febrero del 2004 la implementación de Mozilla que soporta SVG ha sido dotada con la posibilidad de cambiar el backend de renderizado SVG en función de la plataforma. Actualmente, el más avanzado es el basado en la GDI+ de Windows.

Implicaciones de este cambio:

  • Mozilla soporta documentos que contienen SVG, MathML, XHTML o XUL en un mismo documento. Esto es posible gracias a que Mozilla soporta espacios de nombres (XML Namespaces).

  • Todo este contenido puede ser accedido via scripting utilizando el SVG DOM, el cual es compatible con el XML DOM).

SVG es un lenguaje para la descripción de gráficos vectoriales en 2D en XML.

SVG permite la utlización de tres tipos de objectos gráficos:

  • Objetos gráficos vectoriales (líneas, elipses, rectángulos, etc). Estos pueden ser agrupados, formateados, transformados y compuestos para su visualización.

  • Imágenes.

  • Texto.

SVG soporta características avanzadas como:

  • Transformación anidadas (matrices de transformación).

  • Clipping Paths.

  • Alpha Masks.

  • Filtros gráficos.

  • Interactividad y dinamismo, soportandos tanto de forma declarativa como vía scripting.

El SVG DOM permite a los lenguajes de script el acceso a todos los elementos, propiedades y atributos que componen un documento SVG. Además, existe la posibilidad de asignar eventos a los distintos elementos (onmouseover o onclick).

Gracias a la estandarización de los elementos en SVG y su integración con XHTML, podemos tener conviviendo scripts dentro de XHTML y SVG dentro del mismo documento.

El tipo MIME que utiliza SVG es "image/svg+xml" [RFC3023]. Se recomienda que los ficheros SVG tengan extensión .SVG o .SVGZ (en minúsculas) en todas las plataformas.

Espacio de nombre utilizado por SVG:

http://www.w3.org/2000/svg

DOCTYPE para la versión 1.0:

<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN" "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd">

DOCTYPE para la versión 1.1:

<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">

2. Beneficios de la utilización de SVG

  • Renderizado con antialiasing.

  • Patrones de relleno y gradientes.

  • Filtros y efectos avanzados.

  • Clipping.

  • Animaciones.

  • No pierde calidad si se hace zoom o si se redimensiona.

  • Puede escalarse.

  • Ideal para ser impreso.

  • Pueden mostrase de forma progresiva (igual que los GIF), no teniendo que esperar a que todo el documento sea descargado.

  • Pueden distribuirse en formato comprimido GZIP para la reducción del tiempo de descarga .SVGZ.

  • Pueden ser indexados y buscados debido a que su contenido es XML y es textual.

  • Pueden ser transformados por hojas de estilos (XSL o CSS).

  • Integración con otras tecnologías XML del W3 y compatible con:

    • XML 1.0

    • XML Namespaces

    • XLink y XML Base para la referencia a URIs

    • XPointer

    • CSS

    • XSL

    • DOM nivel 1 y 2 incluyendo DOM-Style y DOM-Event

    • SMIL 1.0. Sólo algunas de sus funcionalidades

    • HTML 4 y XHTML 1.0

    • UNICODE

    • WAI. Accesibilidad a contenidos web

3. SVG: Estructura básica de un documento

<?xml version="1.0"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg xmlns="http://www.w3.org/2000/svg" width="200px" height="200px">
  ...
</svg>

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN"
“http://ww.w3.org/TR/xhtml1/xhtml1-transitional.dtd">
<html>
<body>
  <embed src="http://a.com/b.svg" width="210" height="26" type="image/svg+xml" />
</body>
</html>


<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN"
“http://ww.w3.org/TR/xhtml1/xhtml1-transitional.dtd">
<html>
<body>
  <object type="image/svg+xml" data="layout02.svgz" width="550" height="550">
    <a href="layout02.svgz">
      <img alt="layout02" src="layout02.png"/>
    </a>
  </object>
</body>
</html>

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN"
“http://ww.w3.org/TR/xhtml1/xhtml1-transitional.dtd">
<html>
<body>
  <object type="image/svg+xml" data="layout02.svgz" width="550" height="550">
    <embed src="http://a.com/b.svg" width="210" height="26" type="image/svg+xml" />
  </object>
</body>
</html>

4. SVG: Definición del sistema de coordenadas

En SVG el área de dibujo es infinita. A continuación veremos varias formas de decirle al visor de SVG en qué área estamos interesados. El área utilizado por el documento creado se conoce como Viewport. Podemos establecer el tamaño del Viewport utilizando los atributos "width" y "height" del elemento <SVG>.

Los valores que pueden tomar estos atributos pueden ser simplemente números (si expresamos el tamaño en píxeles) o en unas unidades concretas (puntos, pulgadas, picas, centímetros, milímetros, etc).

El origen de coordenadas comienza en la esquina superior izquierda, incrementándose la coordenada X hacia la derecha y la Y hacia abajo. El punto (0, 0) se conoce como origen de coordenadas.

5. SVG: Geometría

5.1. Rectángulo

<svg xmlns="http://www.w3.org/2000/svg" width="200px" height="200px">
  <rect x="25" y="25" width="100" height="100" fill="blue" opacity="0.5" />
  <rect x="50" y="50" rx="20" ry="20" width="100" height="100" fill="red" opacity="0.5" />
  <rect x="75" y="75" width="100" height="100" fill="green" opacity="0.5" />
</svg>

"x" e "y". Desplazamiento del objeto respecto al origen de coordenadas. “width" y “height". Ancho y alto del objeto. “rx" y “ry". Redondean las esquinas del objeto. El resto de atributos añaden propiedades sobre el estilo de la visualización.

Figure 1. rectangulo.svg

rectangulo.svg

5.2. Círculo

<svg xmlns="http://www.w3.org/2000/svg" width="200px" height="200px">
  <circle cx="100px" cy="100px" r="50px" style="fill:red; stroke:black; stroke-width:0.1cm" transform="translate(-20,20)" /> 
  <circle cx="100px" cy="100px" r="50px" style="fill:green; stroke:black; stroke-width:0.1cm" transform="translate(10,-20)"/> 
  <circle cx="100px" cy="100px" r="50px" style="fill:blue; stroke:black; stroke-width:0.1cm" transform="translate(40,40)" /> 
</svg>

“cx" e “cy". Desplazamiento del objeto respecto al origen de coordenadas el cual indica el centro del objeto. “r". Radio del objeto. El resto de atributos añaden propiedades sobre el estilo de la visualización.

Figure 2. circulo.svg

circulo.svg

5.3. Elipse

<svg xmlns="http://www.w3.org/2000/svg" width="200px" height="200px">
  <ellipse cx="96.5" cy="143" rx="59.5" ry="41" style="fill:rgb(255,229,242); stroke:rgb(242,0,125); stroke-width:3"/>
</svg>

“cx" y “cy". Desplazamiento del objeto respecto al origen de coordenadas el cual indica el centro del objeto. “rx" y “ry". Definen el radio horizontal y vertical de la elipse.

Figure 3. elipse.svg

elipse.svg

5.4. Línea

<svg xmlns="http://www.w3.org/2000/svg" width="200px" height="200px">
  <line x1="10" y1="10" x2="150" y2="150" stroke="red" stroke-width="2" />
</svg>

“x1" y “y1". Coordenadas del inicio de la línea. “x2" y “y2". Coordenadas del fin de la línea.

Figure 4. linea.svg

linea.svg

La continuidad de las líneas pude ser modificada gracias al atributo de estilo "stroke-dasharray". Con este atributo podemos definir la línea como una sucesión de tramos visibles e invisibles. El atributo "stroke-dasharray" permite definir una lista de números separados por comas de forma que por parejas nos marcan la continuidad de la línea.

<?xml version="1.0"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN" "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd">
<svg xmlns="http://www.w3.org/2000/svg" width="200px" height="200px">
  <line x1="10" y1="10" x2="150" y2="150" stroke="red" stroke-width="8" stroke-dasharray="18, 4, 4, 18" />
</svg>

Figure 5. linea-dash.svg

linea-dash.svg

5.5. Polilínea

<svg xmlns="http://www.w3.org/2000/svg" width="300" height="100">
  <polyline points="0,0 0,20 40,20 40,0 80,0 80,20 120,20 120,0 160,0 160,20 200,20 200,0 240,0 240,20" 
            style="stroke:red; stroke-width:2; fill:none;" transform="translate(20,20)" />
</svg>

Figure 6. polilinea.svg

polilinea.svg

5.6. Polígono

<svg xmlns="http://www.w3.org/2000/svg" width="150" height="200">
  <polygon points="100,0,50,174,0,128,0,0" 
           style="stroke:none; stroke-width:1; stroke-opacity:1; fill:#d5fbfd; fill-opacity:1" />
</svg>

Figure 7. poligono.svg

poligono.svg

5.7. Texto

<svg xmlns="http://www.w3.org/2000/svg" width="150" height="200">
  <text style="font-size: 72; font-weight: 900; fill: yellow; stroke: black; stroke-width: 0.6">
    <tspan x="10" y="100">Texto en SVG</tspan>
  </text>
</svg>

Figure 8. texto.svg

texto.svg

También existe la posibilidad de introducir elemenos definidos en otros espacios de nombres como es XHTML. Así, podemos insertar pedazos de XHTML dentro del documento SVG. Este ejemplo no funciona con el plugin de Adobe, para visualizarlo utilizar el Mozilla.

<foreignObject x="82" y="100" width="40px" height="10px" 
               requiredExtensions="http://example.com/SVGExtensions/EmbeddedXHTML">
  <html xmlns="http://www.w3.org/1999/xhtml">
    <span class="forobjpts">(100,100)</span>
  </html>
</foreignObject>

5.8. Caminos

Definición de un conjunto de líneas de forma encadenada y con diferentes formas.

Comandos disponibles para definir caminos:

  • M. Permite moverse a un punto determinado sin pintar ninguna línea.

  • L. Creación de una línea hasta la coordenada indicada.

  • H. Creación de una línea horizontal hasta la coordenada indicada.

  • V. Creación de una línea vertical hasta la coordenada indicada.

  • C. Creación de una línea curva hasta la coordenada indicada.

  • S. Creación de una línea curva suave (smooth) hasta la coordenada indicada.

  • Q. Creación de una línea curva cuadrática de Bezier hasta la coordenada indicada.

  • T. Creación de una línea curva suave cuadrática de Bezier hasta la coordenada indicada.

  • A. Creación de una línea elíptica hasta la coordenada indicada.

  • Z. Cerrar el comino.

Todos estos comandos tienen también su equivalente en minúsculas, de forma que el posicionamiento en este caso se considerará relativo y no absoluto.

<svg xmlns="http://www.w3.org/2000/svg" width="200px" height="200px">
  <path d="M10 10 h 100 v  30 h -100 v -30 Z" fill="blue" />
  <path d="M10 80 H 110 V 130 H   10 V  80 Z" fill="red" />
  <path d="M10 80 C 10 80 60 30 110 80 Z" fill="green" />  
</svg>

Figure 9. caminos.svg

caminos.svg
<path d="M50,100 Q200,0 200,200 100,500 600,200" style="fill:none; stroke:blue; stroke-width:2" />

Figure 10. camino-bezier.svg

camino-bezier.svg
<path d="M 10 10 L 65 90 A 5 10 0 0 0 75 90" style="stroke: black; fill: #ffcccc" />

Figure 11. camino-elipse.svg

camino-elipse.svg

Debido a la complejidad de definir figuras geométricas basadas en caminos, se hace mucho más recomendable el uso de programas gráficos de edición para este menester.

6. SVG: Elementos disponibles

6.1. SVG

El elemento SVG es la raiz de todo documento y pude contener el siguiente conjunto de atributos básicos:

  • Definiciones de espacios de nombres (xmlns="http://www.w3.org/2000/svg").

  • Versión de SVG a la que se refiere el documento (version="1.1").

  • Coordenada x a partir de la cual se definirá el documento (x).

  • Coordenada y a partir de la cual se definirá el documento (Y).

  • Ancho de la representación gráfica (width).

  • Alto de la representación gráfica (height).

<svg xmlns="http://www.w3.org/2000/svg" version="1.1" x="10" y="10" width="500px" height="400px">
  ...
</svg>

6.2. G

El elemento “G" se utiliza como contenedor para agrupar distintos objetos y así poder realizar sobre ellos acciones de forma global. Podemos asignarle un ID y así realizar transformaciones, animaciones u otras acciones. Las definiciones de grupos pueden utilizarse de forma aninada.

<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="500" height="400">
  <g opacity="0.2">
    <rect x="100" y="100" width="100" height="100" fill="red" />
    <rect x="150" y="150" width="100" height="100" fill="blue" />
  </g>
  <rect x="200" y="200" width="100" height="100" fill="navy" />
</svg>

Figure 12. elemento-g.svg

elemento-g.svg

6.3. Referencias dentro de SVG

Las referencias dentro de SVG permiten la reutilización de distintas definiciones de objetos en cualquier punto del documento. Así, podemos definir filtros u otras propiedades de ajuste gráfico de forma general dentro del documento y aplicarlas dinámicamente vía scripting.

<linearGradient id="MyGradient">
</linearGradient>

<rect style="fill:url(#MyGradient)"/>

Otro tipo de referencias aceptadas en SVG y que se refieren a recursos externos al documento, son las realizadas mediante XLink:

<svg xmlns:xlink="http://www.w3.org/1999/xlink">
  <image xlink:href="foo.gif" />
</svg>

Para utlizar enlaces XLink dentro del documento, es necesario especificar previamente la definición del espacio de nombres asociado al mismo:

xmlns:xlink="http://www.w3.org/1999/xlink"

6.4. DEFS

Sección de declaración de los elementos que posteriormente podrán ser referenciados dentro del documento. La forma de referenciar los elementos declarada está descrita en el apartado anterior (Referencias dentro de SVG).

<svg width="8cm" height="3cm" xmlns="http://www.w3.org/2000/svg">
  <defs>
    <linearGradient id="MyGradient">
    </linearGradient>
  </defs>
  <rect style="fill:url(#MyGradient)"/>
</svg>

6.5. DESC y TITLE

Son dos elementos que no tiene ningun tipo de representación gráfica. Sólo se utilizan para la documentación y especificación del documento SVG. Cualquier contenedor o elemento gráfico dentro del documento puede definir su propio título y descripción.

6.6. SYMBOL

Este elemento permite definir patrones de objeto gráfico para después poder instanciarlos con un USE. Mediante SYMBOL conseguimos reutilizar elementos que se declaran de forma reiterativa dentro del documento y así mejoras la legibilidad y la semántica del documento SVG.

6.7. USE

Cualquier elemento gráfico de tipo SYMBOL, G, USE u otros elementos pueden potencialmente ser considerados como patrones y ser susceptibles de reutilizarse mediante la utilización de USE.

<svg width="10cm" height="3cm" viewBox="0 0 100 30" xmlns="http://www.w3.org/2000/svg" 
     xmlns:xlink="http://www.w3.org/1999/xlink">
  <defs>
    <rect id="MyRect" width="60" height="10"/>
  </defs>
  <rect x="0.1" y="0.1" width="99.8" height="29.8" fill="none" stroke="blue" stroke-width="0.2" />
  <use x="20" y="10" xlink:href="#MyRect" />
</svg>

Figure 13. elemento-use-1.svg

elemento-use-1.svg
<svg width="10cm" height="3cm" viewBox="0 0 100 30" xmlns="http://www.w3.org/2000/svg" 
     xmlns:xlink="http://www.w3.org/1999/xlink">
  <defs>
    <symbol id="MySymbol" viewBox="0 0 20 20">
      <desc>MySymbol - four rectangles in a grid</desc>
      <rect x="1" y="1" width="8" height="8"/>
      <rect x="11" y="1" width="8" height="8"/>
      <rect x="1" y="11" width="8" height="8"/>
      <rect x="11" y="11" width="8" height="8"/>
    </symbol>
  </defs>

  <rect x="0.1" y="0.1" width="99.8" height="29.8" fill="none" stroke="blue" stroke-width="0.2" />
  <use x="45" y="10" width="10" height="10" xlink:href="#MySymbol" />
</svg>

Figure 14. elemento-use-2.svg

elemento-use-2.svg
<svg width="10cm" height="3cm" viewBox="0 0 100 30" xmlns="http://www.w3.org/2000/svg" 
     xmlns:xlink="http://www.w3.org/1999/xlink">
  <defs>
    <rect id="MyRect" x="0" y="0" width="60" height="10"/>
  </defs>
  <rect x="0.1" y="0.1" width="99.8" height="29.8" fill="none" stroke="blue" stroke-width="0.2" />
  <use xlink:href="#MyRect" transform="translate(20,2.5) rotate(10)" />
</svg>

Figure 15. elemento-use-3.svg

elemento-use-3.svg
<svg width="12cm" height="3cm" viewBox="0 0 1200 300" xmlns="http://www.w3.org/2000/svg" 
     xmlns:xlink="http://www.w3.org/1999/xlink">
  <defs style="stroke-miterlimit: 10">
    <path id="MyPath" d="M300,50 900,50 900,250 300,250" class="MyPathClass" 
          style="stroke-dasharray:300,100" />
  </defs>
  
  <style type="text/css">
  <![CDATA[
     #MyUse { fill: blue }
     #MyPath { stroke: red }
     use { fill-opacity: .5 }
     path { stroke-opacity: .5 }
     .MyUseClass { stroke-linecap: round }
     .MyPathClass { stroke-linejoin: bevel }
     use > path { shape-rendering: optimizeQuality }
     g > path { visibility: hidden } 
  ]]>
  </style>
  
  <g style="stroke-width:40">
    <use id="MyUse" xlink:href="#MyPath" class="MyUseClass" style="stroke-dashoffset:50" />
  </g>
</svg>

Figure 16. elemento-use-4.svg

elemento-use-4.svg

6.8. IMAGE

Este elemento permite la inclusión de imágenes externas rasterizadas en el área definida por las coordenadas de se adjuntan.

<svg width="200" height="200" version="1.1"
xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
  <image x="50" y="50" width="100px" height="100px" xlink:href="modele33.jpg">
    <title>My image</title>
  </image>
</svg>

Figure 17. elemento-image.svg

elemento-image.svg

6.9. Transformaciones

Permiten realizar cambios de coordenadas sobre los elementos representados. Sobre cualquier objeto dentro de un documento SVG podermos realizar las siguientes transformaciones:

  • Escalado. Utilizado para la redimensión o para el cambio de orientación.

  • Traslación. Cambiar la ubicación actual de un elemento, cambiando asi el origen de coordenadas.

  • Rotación. Giro en grados que debe realizar el elemento con respecto al origen de coordenadas.

<svg width="140" height="170">
  <circle cx="70" cy="95" r="50" style="stroke: black; fill: none;" />
  <circle cx="55" cy="80" r="5" stroke="black" fill="#339933" />
  <circle cx="85" cy="80" r="5" stroke="black" fill="#339933" />
  
  <g id="whiskers">
    <line x1="75" y1="95" x2="135" y2="85" style="stroke: black;" />
    <line x1="75" y1="95" x2="135" y2="105" style="stroke: black;" />
  </g>
  <use xlink:href="#whiskers" transform="scale(-1 1) translate(-140 0)" />
</svg>

Figure 18. transformacion-gato.svg

transformacion-gato.svg
<svg width="200" height="200">
  <defs>
    <g id="base">
      <circle cx="80" cy="80" r="30" style="stroke: black; fill: none;" />
    </g>
  </defs>
  
  <g transform="translate(50, 10)">
    <use xlink:href="#base" transform="rotate(10)" />
    <use xlink:href="#base" transform="rotate(12)" />
    <use xlink:href="#base" transform="rotate(14)" />
    <use xlink:href="#base" transform="rotate(16)" />
    <use xlink:href="#base" transform="rotate(18)" />
    <use xlink:href="#base" transform="rotate(20)" />
    <use xlink:href="#base" transform="rotate(22)" />
    <use xlink:href="#base" transform="rotate(24)" />
    <use xlink:href="#base" transform="rotate(26)" />
    <use xlink:href="#base" transform="rotate(28)" />
  </g>
</svg>

Figure 19. transformacion-circulos.svg

transformacion-circulos.svg

7. SVG: Scripting

Tenemos dos métodos para modificar el contenido de un fichero SVG mediante Scripting:

  • Considerando el documento como un fichero XML estándar y utilizando DOM para su manipulación.

  • Considerando el documento como un fichero específico SVG y utlizando el modelo de objetos de SVG para su manipulación.

7.1. Funciones de ejemplo para el de DOM

<?xml version="1.0"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN" 
          "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd">
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" 
     width="300" height="300" onload="pinta()">
  
  <script type="text/ecmascript">
    <![CDATA[
       function pinta() {
          var circleNode = svgDocument.createElement("circle");
          circleNode.setAttribute("cx", 300*Math.random());
          circleNode.setAttribute("cy", 300*Math.random());
          circleNode.setAttribute("r", 30);
          circleNode.setAttribute("style", "stroke: none; " + 
                                           "opacity: 0.3; " + 
                                           "fill: rgb(" + 255*Math.random() + "," + 
                                                          255*Math.random() + "," + 
                                                          255*Math.random() +  ");");          
          setTimeout("window.pinta()", 300);
          
          document.getElementById("dr").appendChild(circleNode);
       } 
    ]]>
  </script>
  
  <g id="dr" />
</svg>

Figure 20. scripting-dom.svg

scripting-dom.svg
<?xml version="1.0"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN" 
          "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd">
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" 
     width="236" height="295">
  
  <script type="text/ecmascript"><![CDATA[
       var drag = false;
       var dx = 0;
       var dy = 0;
       var x = 0;
       var y = 0;
       
       var frame = document.documentElement.getElementById("frame");
       var filtered = document.documentElement.getElementById("filtered");
       var clip = document.documentElement.getElementById("clipRecorte");

       frame.addEventListener("mousedown", mousedown_listener, false);
       frame.addEventListener("mouseup",   mouseup_listener,   false);
       frame.addEventListener("mousemove", mousemove_listener, false);

       function mousedown_listener(evt) {
          drag = true;
          dx = filtered.getAttribute("x") - evt.clientX;
          dy = filtered.getAttribute("y") - evt.clientY;
       }

       function mouseup_listener(evt) {
          drag = false;
          alert('x: ' + filtered.getAttribute("x") + ', ' +
                'y: ' + filtered.getAttribute("y"));
       }

       function mousemove_listener(evt) {
          if (drag) {
              x = evt.clientX + dx;
              y = evt.clientY + dy;

              filtered.setAttribute("x", x);
              filtered.setAttribute("y", y);

              clip.getChildNodes().item(1).setAttribute("d", 
                    "M" +      x  + "," +      y  + " " +
                    "L" + (100+x) + "," +      y  + " " + 
                    "L" + (100+x) + "," + (100+y) + " " +
                    "L" +      x  + "," + (100+y) + " Z");
          }
       } 
     ]]>
  </script>

  <defs>
    <clipPath id="clipRecorte">
      <path d="M0,0 L100,0 L100,100 L0,100 Z" />
    </clipPath>
  </defs>

  <g id="target">
    <image width="236" height="295" xlink:href="wilber-wizard.png" opacity="0.3" />
    <image width="236" height="295" xlink:href="wilber-wizard.png" 
           clip-path="url(#clipRecorte)" />

    <g id="frame">
      <rect id="filtered" width="100" height="100"  
            style="fill: red; fill-opacity: 0; stroke: red; stroke-width: 1; 
                   shape-rendering: optimizeSpeed;" />
    </g>
  </g>
</svg>

Figure 21. scripting-recorte.svg

scripting-recorte.svg

7.2. Funciones de ejemplo para el uso del modelo de objetos de SVG

function init() {
   transform_list = document.getElementById('all').transform.baseVal;
   svg_element = document.getElementById('all').ownerSVGElement;
}

function Rotate() {
   var xform = document.getElementById('foo').createSVGTransform();
   xform.setRotate(30,50,300);
   var id = svg_element.suspendRedraw(1000);
   transform_list.appendItem(xform);
   svg_element.unsuspendRedraw(id);
}

function Translate() {
   var xform = document.getElementById('foo').createSVGTransform();
   xform.setTranslate(10,-10);
   var id = svg_element.suspendRedraw(1000);
   transform_list.appendItem(xform);
   svg_element.unsuspendRedraw(id);  
   }

function Scalein() {
   var xform = document.getElementById('foo').createSVGTransform();
   xform.setScale(1.5,1.5);
   transform_list.appendItem(xform);
}

function Scaleout() {
   var xform = document.getElementById('foo').createSVGTransform();
   xform.setScale(0.5,0.5);
   var id = svg_element.suspendRedraw(1000);
   transform_list.appendItem(xform);
   svg_element.unsuspendRedraw(id);
}

function DOMTest() {
   var p = document.getElementById('barx').points.getItem(0);
   for (var i=50;i<250;++i) {
        p.x = i;
   }
}

function DOMTest2() {
   var p = document.getElementById('bary').points.getItem(0);
   for (var i=50;i<250;++i) {
        p.y = i;
   }
}

8. SMIL

SMIL permite la incorporacion de animaciones basadas en tiempo dentro de un documento SVG. Realmente, dentro del documento SVG contamos con una serie de apoyos para poder animar cualquiera de elementos que hemos definido. Hay que tener en cuenta que cada animación definida variará los valores de uno de los atributos del elemento durante el periodo especificado (ya esté delimitado por la ejecución de un evento o por un tiempo fijo).

Para asociar una animación podemos:

  • Definirla a parte y asociarla a través del ID del elemento:

    <animate xlink:href="#bubblesrect" attributeName="y" 
             begin="aboutbubbles.click" dur="4s" to="10" fill="freeze"/>
    <animate xlink:href="#bubblesrect" attributeName="y" 
             begin="aboutbubbles.click" end="aboutbubbles.click" to="10" fill="freeze"/>
  • Definirla directamente en el elemento que la necesita:

    <rect id="bubbleslabelrectinvis" pointer-events="all" x="272" y="72" width="86" height="24" 
          rx="10" ry="10">
      <set attributeName="opacity" attributeType="CSS" to="0.5" 
           begin="bubbleslabelrectinvis.click" end="bubblescrossrect.click"/>
    </rect>

Ejemplos de animaciones:

<?xml version="1.0"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN" "http://www.w3.org/TR/SVG/DTD/svg10.dtd">
<svg width="500" height="510" xmlns="http://www.w3.org/2000/svg" 
     xmlns:xlink="http://www.w3.org/1999/xlink">
  <style type="text/css">
    #bubbleslabelrectinvis { fill:#f00; stroke: #700; stroke-width: 3; }
    #aboutbubbles { visibility: hidden; }
    .textrect { stroke:#888; stroke-width:2; fill:#eee; }
    .text  { stroke-width:0; font-size:12; font-family:Arial; 
             font-weight:300; fill:#444; }
    .cross { stroke:#888; stroke-width:3; stroke-linejoin:round; 
             stroke-miterlimit:0; stroke-linecap:round; }
  </style>
  
  <g id="base">
    <rect id="bubbleslabelrectinvis" pointer-events="all" x="272" y="72" width="86" height="24" 
          rx="10" ry="10">
      <set attributeName="opacity" attributeType="CSS" to="0.5" 
           begin="bubbleslabelrectinvis.click" 
           end="bubblescrossrect.click; bubblescross01.click; bubblescross02.click"/>
    </rect>  
  </g>

  <defs>
    <g>
      <animate xlink:href="#bubblesrect" attributeName="y" begin="aboutbubbles.click" 
               dur="4s" to="10" fill="freeze"/>    
      <animate xlink:href="#bubblescrossrect" attributeName="y" begin="aboutbubbles.click" 
               dur="4s" to="20" fill="freeze"/>    
      <animate xlink:href="#bubblescross01" attributeName="y1" begin="aboutbubbles.click" 
               dur="4s" to="24" fill="freeze"/>        
      <animate xlink:href="#bubblescross01" attributeName="y2" begin="aboutbubbles.click" 
               dur="4s" to="32" fill="freeze"/>              
      <animate xlink:href="#bubblescross02" attributeName="y1" begin="aboutbubbles.click" 
               dur="4s" to="32" fill="freeze"/>        
      <animate xlink:href="#bubblescross02" attributeName="y2" begin="aboutbubbles.click" 
               dur="4s" to="24" fill="freeze"/>              
      <animate xlink:href="#bubblesminrect" attributeName="y"  begin="aboutbubbles.click" 
               dur="4s" to="20" fill="freeze"/>    
      <animate xlink:href="#bubblesminline" attributeName="y1" begin="aboutbubbles.click" 
               dur="4s" to="28" fill="freeze"/>        
      <animate xlink:href="#bubblesminline" attributeName="y2" begin="aboutbubbles.click" 
               dur="4s" to="28" fill="freeze"/>              
    </g>
  </defs>
    
  <g id="aboutbubbles">
    <set attributeName="visibility" attributeType="CSS" to="visible" 
         begin="bubbleslabelrectinvis.click" fill="freeze"/>
    <set attributeName="visibility" attributeType="CSS" to="hidden"  
         begin="bubblescrossrect.click; bubblescross01.click; bubblescross02.click" fill="freeze"/>
    
    <rect id="bubblesrect" class="textrect" x="160" y="130" width="220" height="75" 
          rx="10" ry="10" />          
    <rect id="bubblescrossrect" class="textrect" x="350" y="140" width="16" height="16" 
          rx="1" ry="1" />   
    <line id="bubblescross01" class="cross" x1="354" y1="152" x2="362" y2="144" />
    <line id="bubblescross02" class="cross" x1="354" y1="144" x2="362" y2="152" />    
    <rect id="bubblesminrect" class="textrect" x="326" y="140" width="16" height="16" 
          rx="1" ry="1" />
    <line id="bubblesminline" class="cross" x1="330" y1="150" x2="338" y2="150" />

    <rect id="bubblesmaxrect" class="textrect" x="326" y="140" width="0" height="0" rx="1" ry="1">
      <animate attributeName="y" begin="aboutbubbles.click" dur="4s" to="10" fill="freeze"/>    
    </rect>

    <rect id="bubblesmaxbox" class="textrect" x="329" y="143" width="0" height="0" rx="1" ry="1">
      <animate attributeName="y" begin="aboutbubbles.click" dur="4s" to="10" fill="freeze"/>    
    </rect>
    
    <text id="bubblestext" class="text">      
      <tspan id="bubblestext00" x="170" y="158">
        <animate attributeName="y" begin="aboutbubbles.click" dur="4s" to="38" fill="freeze"/>
        Ventana contextual
      </tspan>
    </text>
  </g>
</svg>

Figure 22. smil-ventana.svg

smil-ventana.svg
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 100 100">
  <animate attributeName="viewBox" begin="zoomIn.click" to="0 0 50 50" dur="12s" fill="freeze"/>
  <g id="zoomIn">
    <rect x="40" y="40" width="20" height="4"/>
    <rect x="48" y="32" width="4" height="20"/>
  </g>
</svg>

Figure 23. smil-mas.svg

smil-mas.svg
<svg viewBox="-400 -200 1200 600">
  <g>
    <circle cx="100" cy="50" r="1000" style="fill:#000"/>
    <circle cx="100" cy="50" r="0" style="fill:#F75">
      <animate attributeName="r" begin="0s" dur="10.8s" from="0" to="1200"/>
    </circle>
    <circle cx="200" cy="100" r="0" style="fill:#FA8">
      <animate attributeName="r" begin="2s" dur="10.8" from="0" to="1200"/>
    </circle>
    <circle cx="300" cy="150" r="0" style="fill:#FCB">
      <animate attributeName="r" begin="3.5s" dur="10.8" from="0" to="1200"/>
    </circle>
    <circle cx="400" cy="200" r="0" style="fill:#FDC">
      <animate attributeName="r" fill="freeze" begin="4.5s" dur="10.8s" from="0" to="1200"/>
    </circle>
    <circle cx="500" cy="250" r="0" style="fill:#FED">
      <animate attributeName="r" fill="freeze" begin="5.25s" dur="10.8s" from="0" to="1200"/>
    </circle>
    <circle cx="600" cy="300" r="0" style="fill:#FEF">
      <animate attributeName="r" fill="freeze" begin="5.75" dur="10.8s" from="0" to="1200"/>
    </circle>
  </g>
</svg>

Figure 24. smil-splash.svg

smil-splash.svg
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" 
     id="svg-root" width="100%" height="100%" viewBox="0 0 480 360">
    
  <g id="test-body-content" font-family="Arial" font-size="30">
    <g transform="translate(0, 0)">
      <rect x="60" y="20" width="60" height="210" fill="#dfdfdf" 
            stroke="#dfdfdf" stroke-width="1">
        <animate id="largo1" attributeName="width" 
                 begin="0s" dur="4s" from="60" to="210" fill="freeze"/>
        <animate id="ancho1" attributeName="height" 
                 begin="0s" dur="4s" from="210" to="310" fill="freeze"/>
        <animate id="largo2" attributeName="width"
                 begin="largo1.end" dur="4s" from="210" to="60" fill="freeze"/>
        <animate id="ancho2" attributeName="height" 
                 begin="ancho1.end" dur="4s" from="310" to="210" fill="freeze"/>

        <animateMotion id="abajo1" from="0,0" to="80,80" 
                       begin="largo2.end" dur="3s" fill="freeze"/>
        <animateMotion id="zigzag1" values="80,80;10,0;0,10" 
                       begin="abajo1.end" dur="3s" fill="freeze"/>
        <animateMotion id="arco1" path="M0,10 C0,10 40,40 80,0" 
                       begin="zigzag1.end" dur="3s" fill="freeze"/>
      </rect>
      <rect x="60" y="20" width="50" height="20"  fill="#00ff55" 
        stroke="#008855" stroke-width="1">
        <animate attributeName="width"  
                 begin="0s" dur="4s" from="50" to="200" fill="freeze"/>
        <animate attributeName="height" 
                 begin="0s" dur="4s" from="200" to="300" fill="freeze"/>            
        <animate attributeName="width"  
                 begin="4s" dur="4s" from="200" to="50" fill="freeze"/>
        <animate attributeName="height" 
                 begin="4s" dur="4s" from="300" to="200" fill="freeze"/>            
        
        <animateMotion from="0,0" to="80,80" begin="8s" dur="3s" fill="freeze"/>
        <animateMotion values="80,80;10,0;0,10" begin="11s" dur="3s" fill="freeze"/>
        <animateMotion path="M0,10 C0,10 40,40 80,0" begin="14s" dur="3s" fill="freeze"/>
      </rect>
    </g>
        
    <g>
      <rect x="320" y="100" width="40" height="40" fill="#ffffff">
        <animate id="fadein" attributeName="fill" attributeType="auto" 
                 from="#ffffff" to="#ff0000" begin="indefinite" dur="3s" fill="freeze"/>
        <animate id="fadeout" attributeName="fill" attributeType="auto" 
                 from="#ff0000" to="#ffffff" begin="indefinite" dur="3s" fill="freeze"/>
      </rect>

      <g id="buttons">
        <a xlink:href="#fadein">
          <rect x="320" y="10" width="60" height="40" fill="green"/>
          <text fill="white" font-size="10" font-weight="bold" x="330" y="20">Oscuro</text>
        </a>
        <a xlink:href="#fadeout">
          <rect x="320" y="50" width="60" height="40" fill="maroon"/>
          <text fill="white" font-size="10" font-weight="bold" x="330" y="60">Claro</text>
        </a>
      </g>
    </g>        
  </g>
</svg>

Figure 25. smil-movimiento.jpg

smil-movimiento.jpg

9. HTML/XHTML

SVG, al ser un formato XML, donde mejor se integra es en otros documentos XML. Si partimos de la versión XML de HTML, es decir, XHTML, nos encontraremos con que podemos embeber el codigo SVG dentro del propio documento XHTML. Esto es gracias a que XHTML soporta distintos espacios de nombres.

Con este tipo de documento integramos tecnologías como CSS, Scripting, XML y ahora SVG. Todos estos recursos disponibles en un único tipo de documento XHTML.

Sobre esta base nace el proyecto SVG Mozilla que intenta hacer de este navegador un motor nativo de renderizado de SVG (sin la utilización de ningun plugin externo). Esto quiere decir que podremos añadir código SVG "inline" en el documento XHTML y que el navegador lo interpretará al igual que hace con el código HTML.

En teoría consigueremos el mismo comportamiento que con el plugin de Adobe, aunque ahora no sea del todo cierto debido al estado del desarrollo del proyecto. A día de hoy la versión que de Mozilla SVG que más funciones soporta es la basada en el GDI+ de Windows

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
          "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:svg="http://www.w3.org/2000/svg" >
  <head>
    <title>Test SVG dentro de XHTML</title>
    <style type="text/css">
      polygon[class="base"]  { fill:blue; }
    </style>
  </head>
  <body>
    <h1 class="top">Poligonos renderizados por Mozilla</h1>
  
    <svg:svg  width="200px" height="200px">
      <svg:polygon points="20,20 30,60 60,30" class="base" />
      <svg:foreignObject x="5" y="60" width="40" height="10">
        <span class="forobjpts" style="color:blue;">Poligono</span>
      </svg:foreignObject>
    </svg:svg>
  </body>
</html>

Figure 26. mozilla-inline.xhtml

mozilla-inline.xhtml

10. Implementación, herramientas y enlaces de interés