René Nyffenegger's collection of things on the web
René Nyffenegger on Oracle - Most wanted - Feedback -
 

SVG examples: Dynamic SVG with Javascript

The following example creates an SVG dynamically with Javascript. It doesn't seem to work with Internet Explorer.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Dynamic SVG</title>

  <script language='javascript'>

    function writeSVG() {

      var div   = document.getElementById('svgContainer');
      var svg   = document.createElement('object');

      svg.setAttribute('type', 'image/svg+xml');

      svg.setAttribute('data', 'data:image/svg+xml,'                   + 
                 '<?xml version="1.0" standalone="no"?>'               +
                 '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN " '    +
                 '"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">' +
                 ''                                                          +
                 '<svg width  ="400px"'                                +
                 '     height ="170px"'                                +
                 '     version="1.1"'                                  +
                 '     xmlns  ="http://www.w3.org/2000/svg" >'         +
                 ''                                                    +
                 '<rect width ="300" '                                 +
                 '      height="100" '                                 +
                 '      x     ="50"'                                   +
                 '      y     ="50"'                                   +
                 '      style ="fill:rgb(0,255,0);'                    +
                 '              stroke-width:20; '                     +
                 '              stroke:rgb(0,0,255)"'                  +
                 '/>' +
                 ''                                                    +
                 '</svg>');

      div.appendChild(svg);

    }

  </script>

</head>
<body onLoad='writeSVG()'>
 
  <div>
    The next div (with id=svgContainer) will
    contain the SVG after writeSVG() is called.
  </div>

  <div id='svgContainer'>
  </div>

</body>
</html>
See also other SVG examples.