(Embed and) Refer to an external SVG via D3 and/or javascript

后端 未结 2 1932
轻奢々
轻奢々 2020-11-29 07:29

I have an .svg file and want to embed it in the svg strucure of my d3-graphic.

I also need to reference all paths/polygons attached to g-elements via an id of certai

2条回答
  •  日久生厌
    2020-11-29 07:55

    There's a better solution.

    I hadn't realized that the d3.xml() function returns a read-in xml file as a document fragment (as opposed to converting it to JSON). In other words, it returns a ready-made DOM tree that can be inserted within you main document's DOM wherever you need it.

    Knowing that (and knowing that stand-alone SVG files are also XML files), this is likely the most reliable approach for adding external SVG content to your webpage:

    d3.xml("http://upload.wikimedia.org/wikipedia/commons/a/a0/Circle_-_black_simple.svg", 
            function(error, documentFragment) {
    
        if (error) {console.log(error); return;}
    
        var svgNode = documentFragment
                    .getElementsByTagName("svg")[0];
        //use plain Javascript to extract the node
    
        main_chart_svg.node().appendChild(svgNode);
        //d3's selection.node() returns the DOM node, so we
        //can use plain Javascript to append content
    
        var innerSVG = main_chart_svg.select("svg");
    
        innerSVG.transition().duration(1000).delay(1000)
              .select("circle")
              .attr("r", 100);
    
    });
    

    Fiddle here: http://jsfiddle.net/J8sp3/4/

    Notice in particular that (a) I am adding the content to an existing SVG, and (b) I am not deleting any of that SVG's current content.

    Of course, you can also add the SVG to a

    or any other element that can contain it: http://jsfiddle.net/J8sp3/3/

    This method should work in any browser that supports SVG. I even tried it in IE8, and the DOM structure is correct even if IE8 doesn't know how to draw circles and rectangles!

    @Seb, please unselect the previous answer at pick this one as the accepted answer.

提交回复
热议问题