drawing on an externally loaded svg graphic in D3

2020-04-30 16:48发布

问题:

I have loaded an external graphic from an svg file and I want to experiment drawing on it but cannot figure out how. my simple d3 code is here:

<!DOCTYPE html>
  <html>
  <head>
   <script type="text/javascript" src="http://mbostock.github.com/d3/d3.js"></script>
</head>
<body>
  <script type="text/javascript">

     d3.xml("brussels.svg", "image/svg+xml", function(xml) {
     document.body.appendChild(xml.documentElement);
       });

     svg.append("circle")
     .style("stroke", "gray")
     .style("fill", "white")
     .attr("r", 40)
     .attr("cx", 50)
     .attr("cy", 50)
     .on("mouseover", function(){d3.select(this).style("fill", "aliceblue");})
     .on("mouseout", function(){d3.select(this).style("fill", "white");});

      </script>
   </body>
</html>

I am sure it is something simple but I am not sure how to create the actual circle.

Thanks!

回答1:

The function:

 d3.xml("brussels.svg", "image/svg+xml", function(xml) {
   document.body.appendChild(xml.documentElement);
 });

executes asynchronously. Hence, the code following it is executed before the callback is executed. The second problem is that you need to define the svg variable before you can operate on it.

Something like the following should work:

 d3.xml("brussels.svg", "image/svg+xml", function(xml) {
   document.body.appendChild(xml.documentElement);

   var svg = d3.select('svg');

   svg.append("circle")
    .style("stroke", "gray")
    .style("fill", "white")
    .attr("r", 40)
    .attr("cx", 50)
    .attr("cy", 50)
    .on("mouseover", function(){d3.select(this).style("fill", "aliceblue");})
    .on("mouseout", function(){d3.select(this).style("fill", "white");});
 });