drawing on an externally loaded svg graphic in D3

后端 未结 1 1769
醉话见心
醉话见心 2021-01-29 01:23

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:



        
1条回答
  •  囚心锁ツ
    2021-01-29 01:34

    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");});
     });
    

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