How would I go about creating an SVG DOM element from a String
?
Example:
var svgStr = \'
I was building SVG chart and needed to enable user to pass any SVG to make it into a chart annotation. The solution was:
index.html - the root SVG element I am attaching child SVGs to
api.ts - API to add annotation (written in TypeScript). x, y - coordinates where to place the annotation
function drawAnnotation(x: number, y: number, svgContent: string, svgId: string): SVGElement {
const svgRoot = document.getElementById("chart_SVG");
const svgNode = document.createRange().createContextualFragment(svgString);
svgRoot.appendChild(svgNode);
const newNode = this.svgRoot.lastChild as SVGElement;
newNode.id = svgId;
newNode.setAttribute("x", x.toString());
newNode.setAttribute("y", y.toString());
return newNode;
}
example.ts
drawAnnotation(
100,
100,
'',
"myNewNode"
)