Adding Elements

A bit more advanced example is shown below. The javascript is payload in the (green) CDATA section. The top element registers a number of listeners: onmousemove, onmousedown and onmouseup. The corresponding handlers can be found in the CDATA section. On startup the SVG will be an empty rectangle. First of all there is a state engine: state being kept in the variable 'up'. The value will be toggled by the functions registered by 'onmousedown' and 'onmouseup'. On mousemove the 'move' fuction will create a new circle, if the mouse is down. It is great to watch the DOM grow: this works well in in most browsers by right clicking and choosing 'Inspect element'.

<svg xmlns="http://www.w3.org/2000/svg" 
  xmlns:xlink="http://www.w3.org/1999/xlink" 
  onload="startup(evt)" onmousemove="move(evt)" onmousedown="msdn(evt)" 
  onmouseup="msup(evt)" >
<script><![CDATA[
  var SVGDocument = null;
  var SVGRoot = null;
  var count=0;
  var up=1;
  var svgns = 'http://www.w3.org/2000/svg';

  function startup(evt){
    O=evt.target;
    SVGDoc = O.ownerDocument;
    SVGRoot = SVGDoc.documentElement;
  }

  function msdn(evt) {
    up=0;
  }

  function msup(evt) {
    up=1;
  }
  
  function move(evt){
    if (up==0) {
      N = SVGDoc.createElementNS(svgns,"circle");
      N.setAttributeNS(svgns,"id", "P"+count);
      N.setAttribute("cx", evt.clientX);
      N.setAttribute("cy", evt.clientY);
      N.setAttribute("r", 100);
      N.setAttribute("opacity",.2);
      N.setAttribute("fill", "rgb(255,"+(count++*3)%255+",0)");
      SVGRoot.appendChild(N);
    }
  }
]]></script>

  <rect id="P" x="0" y="0" width="100%" height="100%" fill="#333"/>
</svg>
        
It will show up like (click and move mouse):

alt : It seems your browser does not support SVG. Consider using Google Chrome or another SVG enabled browser

© Jan van der Meiden 2015