Creating an SVG DOM element from a String

前端 未结 4 1946
天命终不由人
天命终不由人 2021-02-05 05:40

How would I go about creating an SVG DOM element from a String?

Example:

var svgStr = \'

        
4条回答
  •  不要未来只要你来
    2021-02-05 06:40

    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,
      'TEXT',
      "myNewNode"
    )
    

提交回复
热议问题