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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…