Dynamically generated SVG path
Demo of dynamically adding a line to an SVG element
by doug65536
HTML
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" id="cont">
</svg>
CSS
#cont {
width: 500px;
height: 500px;
}
JavaScript
function makeline(parent, coords, style, xprop, yprop) {
var attribs = { d: '', style: style };
attribs.d = 'M' + coords[0][xprop] + ',' + coords[0][yprop];
for (var i = 1; i < coords.length; ++i) {
if (i !== coords.length - 1 ||
coords[0][xprop] !== coords[i][xprop] ||
coords[0][yprop] !== coords[i][yprop])
attribs.d += 'L' + coords[i][xprop] + ',' + coords[i][yprop];
else
attribs.d += 'Z';
}
if (style !== undefined)
attribs.style = style;
el = $(document.createElementNS('http://www.w3.org/2000/svg', 'path'));
el.attr(attribs).appendTo(parent);
}
makeline($('#cont'), [[4,5], [20,5], [30,40], [20, 60], [4,5]],
"stroke:black;stroke-width:2;fill:lightblue", '0', '1');