An example of creating an SVG tag and elements with JavaScript

This is an example of using two JavaScript functions to create an SVG tag and a few SVG child elements (a <rect>, <g> and <circle> tags).

You can get the code by viewing the source and taking the functions from there.

<script>
    // This function can be used to create an SVG tag
    //
    // @param object opt Various options that you can pass to the function.
    //                   This is an object that can consist of the following
    //                   properties (there's just one currently):
    //
    //                              container - The DIV tag (or its ID) that is
    //                                          the container of the SVG tag.
    function createSVG (opt)
    {
        var container = opt.container;

        if (typeof container === 'string') {
            container = document.getElementById(container);
        }

        var svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
            svg.setAttribute('style', 'top: 0; left: 0; position: absolute');
            svg.setAttribute('width', container.offsetWidth);
            svg.setAttribute('height', container.offsetHeight);
            svg.setAttribute('version', '1.1');
            svg.setAttributeNS("http://www.w3.org/2000/xmlns/", 'xmlns', 'http://www.w3.org/2000/svg');
            svg.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xlink", "http://www.w3.org/1999/xlink");
            svg.__container__ = container;
        container.appendChild(svg);

        container.__svg__    = svg;
    
        var style = getComputedStyle(container);
        if (style.position !== 'absolute' && style.position !== 'fixed' && style.position !== 'sticky') {
            container.style.position = 'relative';
        }

        return svg;
    }

    //
    // Creates an SVG tag depending on the arguments that you give
    //
    //@param opt object The options for the function. This is a regular
    //                  JavaScript object that can consist of the following
    //                  properties:
    //                             svg - The SVG object - the same as what you
    //                                   get back from the above createSVG()
    //                                   function
    //                             type - The name of the type of tag that you
    //                                    want - eg rect or circle etc
    //                             parent - By default new elements are added to
    //                                      the root of the SVG document but by
    //                                      specifying a parent you can start
    //                                      nesting elements (eg inside g tags)
    //                             attr - An object of attributes that should
    //                                    be added to the tag. See the example
    //                                    to see how this is specified.
    //                             css - An object map of any CSS that you want
    //                                   to add to the tag. SVG 2.0 allows for
    //                                   property specification using CSS but
    //                                   it's not widle supported at this time by
    //                                   browsers. One thing that you may need
    //                                   though is the cursor property for when
    //                                   you mouseover the element.
    //
    function create (opt)
    {
        var ns  = "http://www.w3.org/2000/svg",
            tag = document.createElementNS(ns, opt.type);

        // Add the attributes
        for (var o in opt.attr) {
            if (typeof o === 'string') {
            
                var name = o;

                if (o === 'className') {
                    name = 'class';
                }
                if ( (opt.type === 'a' || opt.type === 'image') && o === 'xlink:href') {
                    tag.setAttributeNS('http://www.w3.org/1999/xlink', o, String(opt.attr[o]));
                } else {
                    tag.setAttribute(name, String(opt.attr[o]));
                }
            }
        }
        
        // Add the style
        for (var o in opt.style) {
            if (typeof o === 'string') {
                tag.style[o] = String(opt.style[o]);
            }
        }

        if (opt.parent) {
            opt.parent.appendChild(tag);
        } else {
            opt.svg.appendChild(tag);
        }

        return tag;
    }

    /**********************************************************************
    * Using the two functions (the above two functions would go well in a *
    * library file)                                                       *
    ***********************************************************************/

    // Create the SVG tag
    svg = createSVG({
        container: 'cc'
    });

    // Create a rect element and add to the SVG tag
    rect = create({
        svg: svg,
        type: 'rect',
        attr: {
            x: 5,            // The X coordinate of the rectangle
            y: 5,            // The Y coordinate of the rectangle
            width: 100,      // The width of the rectangle
            height: 100,     // The height of the rectangle
            fill: 'red',     // The fill colour of the rectangle
            stroke: 'black'  // The stroke colour of the rectangle
        }
    });

    // Create a g element (a group)
    g = create({
        svg: svg,
        type: 'g',
        attr: {
            // No attributes to give the group just yet
        }
    });

    // Create a circle element
    circle = create({
        svg: svg,
        type: 'circle',

        parent: g, // The circle is added as a child of the group that
                   // was just added
        attr: {
            cx: 200,        // The center X coordinate
            cy: 200,        // The center Y coordinate
            r: 50,          // The radius of the circle
            stroke: 'black' // The stroke of the circle. Because no fill has been
                            // specified it defaults to black (but is changed a
                            // few lines down)
        }
    });

    // Set the groups fill to red which means all of the sub-elements
    // of the group inherit the color too - ie the circle that was just
    // added
    g.setAttribute('fill','blue');
</script>

« Back to the article