having problems selecting svg child elements using d3

后端 未结 1 586
没有蜡笔的小新
没有蜡笔的小新 2020-12-22 00:03

I have an svg that I\'m trying to access and modify using d3.js. The svg file name is us-map.svg. I\'ve included a reference to the svg in my htm

相关标签:
1条回答
  • 2020-12-22 01:04

    I was thinking that d3 could be used to traverse and manipulate an existing SVG

    This is pretty much what d3 does best. But when you write:

    d3.select('#imgMap')
    

    You are not selecting the SVG (unless you have an SVG with id = "imgMap", which is not your case). You're using an <object>. Thus, you have to write:

    var mySVG = d3.select(document.getElementById("imgMap").contentDocument);
    

    And then select your groups using mySVG.

    var myGroups = mySVG.selectAll("g");
    

    Have in mind that this selection only works after the object has been loaded.

    Source: https://benfrain.com/selecting-svg-inside-tags-with-javascript/

    EDIT:

    As requested by the OP, this is a basic working demo: https://plnkr.co/edit/RJOznJROiqTpo5dm9M7L?p=preview

    In this plunkr, "mysvg.svg" is an external file (in your code, you'll have to provide the correct path). The code finds the SVG:

    var mySVG = d3.select(document.getElementById("imgMap").contentDocument);
    

    And then selects the blue circle inside the SVG, moving it to the right:

    var myCircle = mySVG.select("#blueCircle"); 
    myCircle.transition().duration(2000).attr("cx", 180);
    

    Pay attention to this: I set a setTimeout of 1000ms, just to make sure that the object is loaded before the code runs.

    0 讨论(0)
提交回复
热议问题