Object oriented SVG scripting

Lissajou is a rather simple SVG example. But it has some interesting features:

lissajou.html

<!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">
  <head>
    <meta name="generator" content="HTML Tidy, see www.w3.org" />
    <title>SVG Lissajou</title>
  </head>

  <body>
    <h1>SVG Lissajou example</h1>

    <p><embed width="400" height="300" src="lissajou.svg" /></p>

    <form id="formular" align="center">
      p(t) = sin(<input id="om1" type="text" value="1" size="2" />*t) + 
             cos(<input id="om2" type="text" value="2" size="2" />*t  + 
             <span style="font-family:symbol">f</span>) 
      <input type="button" value="change" onclick="window.lissajou.ChangeOmega(om1.value, om2.value);" />
    </form>
  </body>
</html>
  

lissajou.svg

<?xml version="1.0"?>
<svg width="400" height="300" onload="OnLoadEvent(evt)">
   <g id="frame">
      <rect x="0" y="0" width="400" height="300" style="fill:#C0C0C0"/>
   </g>

<script><![CDATA[
// == Lissajou object definition (start) =======================
function Lissajou(parent)  // .. constructor ..
{
   // -- properties ---------------------
   this.curve  = null;
   this.omega1 = 1;
   this.omega2 = 2;
   this.phi    = 0;
   this.dphi   = Math.PI/30.
   // -- methods ------------------------
   this.ChangeOmega = Lissajou_ChangeOmega;  // .. property change by user ..
   this.Animate     = Lissajou_Animate;      // .. animate curve ..
   // -- create new curve as path -------
   var doc = parent != null ? parent.getOwnerDocument() : null;
   if (doc != null)
   {
      this.curve = doc.createElement("path");
      this.curve.setAttribute("style", "stroke-width:1; stroke:blue; fill:none");
      parent.appendChild(this.curve);
   }
}

// --------------------------------------------------------------
function Lissajou_ChangeOmega(om1, om2)
{
   this.omega1 = om1;
   this.omega2 = om2;
}

// --------------------------------------------------------------
function Lissajou_Animate()
{
   var str = "M", dt = Math.PI/100, pi2 = 2.*Math.PI;

   for (var t=0.0; t <= pi2; t += dt)
      str += (200. + 100.*Math.sin(this.omega1*t)) + " " + 
             (150. + 100.*Math.cos(this.omega2*t + this.phi)) + " ";

   this.curve.setAttribute("d", str);
   this.phi += this.dphi;
   setTimeout("window.lissajou.Animate()", 1);
   return true;
}
// == Lissajou object definition (end) =======================

// == event handler ============================================
function OnLoadEvent(event)
{
   var doc = event.getTarget() != null ? event.getTarget().getOwnerDocument() : null;
   if (doc != null)
   {
      window.lissajou = new Lissajou(doc.getElementById("frame"));
      window.lissajou.Animate();
   }
}

]]></script> 

</svg>
  

© 2000 MecXpert