Technologies: HTML, CSS, JavaScript, SVG, jQuery

You probably already know the technical aspects of SVG. So I won't go into any of the background.

My task here today is to take a JavaScript Object:

svgData = {
    defs: { },
    svg: {
        height: 500,
        width: 500
    },
    polygon: {
        points: {
             0: [200,10],
             1: [250,190],
             2: [160,210],
             3: [100,80]
        },
        style : {
            fill: "lime",
            stroke: "purple",
            strokeWidth: "4"
        }
    }
}

And render this to the screen:

So to begin with, let's get a basic template setup. index.html:


<!DOCTYPE html>
<head>
    <title>SVG from Object</title>
</head>
<body>
    <div id="svgParent">
        <!--SVG GOES HERE-->
    </div>

<script src="add jquery here"></script>
</body>

Now we need to load the JavaScript Object. I am using the above object as a test to determine what I will eventually need in a loadable/savable JSON object. So it is sort of rough right now, but it will get us started.

The first thing we need to do is setup our JavaScript file.

"use strict";
window.onload = function(){
   //Do something
};

Just a quick FYI, I've recently read some articles that point out Document.Ready() will soon not be the recommended way to check your DOM. So I always use window.onload

So now we need to divide concerns. So let's add a function:

"use strict";
window.onload = function(){

    //Load our SVG Object when the DOM has loaded.
    loadSVGObject(svgData);

}; //End Window Onload

// Description: Parse the loaded object and append to our DOM work area
// params: svgData - the object containing our SVG information;
// return: none;
function loadSVGObject(svgData){

    //Do our parsing and appending here

}; //End loadSVGObject

Now we will learn how to parse the object in JavaScript.
So in our loadSVGObject function we need to do a couple of things:

1. Determine where we are going to attach our SVG element to our DOM - aka our Parent
Note: I use jQuery because the application I am using already has it loaded. But feel free to use pure javascript: var parent = document.getElementById('svgParent');
2. Build our DOM structure, SVG -> Polygon
3. Put together our Polygon attributes based on our svgData
4. Combine 1,2 and 3
5. Add the resulting structure to our DOM
6. And finally, we will need to refresh our DOM's html so the SVG will be accounted for and rendered properly.


function loadSVGObject(svgData){

    //1. Where are we going to attach our svg?
    var parent = $('#svgParent');

    //2. Build our DOM structure
    curObjSVG = document.createElement("svg"); //create a new svg element
    curObjSVG.setAttribute("width", svgData.svg.width); //set the svg element's width and height attributes
    curObjSVG.setAttribute("height", svgData.svg.height);

    //3. Put together our polygon attributes
    curObjSVGPolygon = document.createElement("polygon");
    var pointStr = ""; //create a temp empty string to hold our points
    for(point in svgData.polygon.points){
        aX = svgData.polygon.points[point][0];
	aY = svgData.polygon.points[point][1];
	aPoint = aX + "," + aY;
	pointStr += aPoint + " ";
    }
    curObjSVGPolygon.setAttribute("points", pointStr); //The points are in a string, let's apply them as the attribute
    
    //We are adding the styles inline. I did this because I need each svg object to keep it's individual styles
    var tempStyleStr = "fill:" + svgData.polygon.style.fill + ";" + " stroke:" + svgData.polygon.style.stroke + ";" + " stroke-width:" + svgData.polygon.style.strokeWidth + ";";
    curObjSVGPolygon.setAttribute("style", tempStyleStr ); //The styles are in a string, apply them as the attribute

    //4. Now append the elements together
    curObjSVG.append( curObjSVGPolygon );

    //5. Add them to the parent which is already on the DOM
    parent.append( curObjSVG );
    
    //6. Now refresh the DOM (or parent), so our SVG will be rendered properly
    parent.html(parent.html());

}; //End loadSVGObject

The code in #6 is important because of the way the DOM loads the SVG. The code is processed when it loads the initial html. So we need a little hack to force the DOM to recognize the new SVG and update the rendered element.

Resources:
n/a

Codepen

See the Pen SVG from a JavaScript Object by Jeremy (@J-Roel) on CodePen.

Conclusion:
SVGs are fun to work with. You can utilize these components to achieve some really nice effects and make them responsive. This tutorial can help you get started with dynamically accessing DOM related elements for use on your web applications.