Creating an SVG DOM element from a String

前端 未结 4 1888
天命终不由人
天命终不由人 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:26

    You can use DOMParser to parse an XML string.

    var parser = new DOMParser();
    var doc = parser.parseFromString(stringContainingXMLSource, "image/svg+xml");
    

    The root element for the parsed string will be doc.documentElement

    For this to work properly cross-browser you'll need to set the html namespace i.e. your string will need to look like this...

    var svg2='<svg xmlns="http://www.w3.org/2000/svg" width="500" height="500" ...
    
    0 讨论(0)
  • 2021-02-05 06:29

    Assuming you are using JavaScript, you can simply pass that string as the innerHTML of an existing element obtained via the DOM API:

    var svg2 = "<svg ...> ... </svg>";
    var container = document.getElementById("container");
    container.innerHTML = svg2;
    

    See: JSFiddle

    0 讨论(0)
  • 2021-02-05 06:37

    Reading and writing the innerHTML of an SVG within HTML seems to work well except in Internet Explorer (9-11): http://cs.sru.edu/~ddailey/svg/IframeSVG.htm . If one needs IE compatibility (as in for a real web app) then use DOM methods to create a suitable container (object, iframe or embed) and build the SVG, one childNode at a time, through DOM methods within that container. ) It's a bit of a chore, but the basics are covered at http://www.w3.org/Graphics/SVG/IG/resources/svgprimer.html#SVG_HTML.

    0 讨论(0)
  • 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

    <svg id="chart_SVG" width="900" height="600" role="img" xmlns="http://www.w3.org/2000/svg"></svg>
    

    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,
      '<svg><g><rect x="0" y="0" width="100%" height="100%" stroke="red" stroke-width="10" fill="orange"/><text x="50%" y="50%" dominant-baseline="middle" text-anchor="middle" font-family="Verdana" font-size="24" fill="blue">TEXT</text></g></svg>',
      "myNewNode"
    )
    
    0 讨论(0)
提交回复
热议问题