删除d3 svg元素以重新绘制

时间:2022-11-20 17:41:04

I hope you can help me, because this is driving me nuts!

我希望你能帮助我,因为这让我发疯!

So i was trying to redraw a svg using d3. In my code i add the svg using:

因此,我尝试使用d3重新绘制svg。在我的代码中,我使用以下方法添加svg:

d3.xml("Images/vertical_line.svg", "image/svg+xml", function(xml) {

  var importedNode = document.importNode(xml.documentElement, true);
  var svg = d3.select('#'+id+'_verticallinecontainer').node().appendChild(importedNode);

  });

When my update function is called i then proceed to remove the element:

当我的更新函数被调用时,我继续删除元素:

d3.select("#"+id+'_verticallinecontainer').remove();

This removes the container and the element. I then proceed with redrawing the svg again using the above code.

这将删除容器和元素。然后使用上面的代码重新绘制svg。

My problem is that when it appends the svg again it does it twice and i do not understand why! It seems that d3 somehow caches the svg, adding it again.

我的问题是,当它再次添加svg时,它会添加两次,我不明白为什么!看起来d3以某种方式缓存了svg,并再次添加它。

Hope you can help to clear out what is wrong, any help would be appreciated!

希望您能帮忙解决问题,任何帮助都将不胜感激!

2 个解决方案

#1


4  

FIDDLE with a quick example of adding, removing and the adding again an SVG and a contained circle. Hope this helps.

修改添加、删除和再次添加SVG和包含圆的快速示例。希望这个有帮助。

function update() {
    svg.remove();
    svg = d3.selectAll("body").append("svg");
    svg.append("circle")
        .attr("cx",40)
        .attr("cy",40)
        .attr("r",20)
        .style("fill","blue");
}

#2


3  

I had a similar problem to this. removing the SVG element did not allow me to fully update the data like I wanted.

我也有类似的问题。删除SVG元素不允许像我希望的那样完全更新数据。

Instead, I removed the g elements created inside the SVG with this line:

相反,我用这一行删除了SVG内部创建的g元素:

d3.selectAll("g > *").remove()

in my updateGraph() function

在我updateGraph()函数

Full explanation and situation shown here: Repainting/Refreshing Graph in D3

完整的解释和情况显示在这里:重画/刷新图在D3中

#1


4  

FIDDLE with a quick example of adding, removing and the adding again an SVG and a contained circle. Hope this helps.

修改添加、删除和再次添加SVG和包含圆的快速示例。希望这个有帮助。

function update() {
    svg.remove();
    svg = d3.selectAll("body").append("svg");
    svg.append("circle")
        .attr("cx",40)
        .attr("cy",40)
        .attr("r",20)
        .style("fill","blue");
}

#2


3  

I had a similar problem to this. removing the SVG element did not allow me to fully update the data like I wanted.

我也有类似的问题。删除SVG元素不允许像我希望的那样完全更新数据。

Instead, I removed the g elements created inside the SVG with this line:

相反,我用这一行删除了SVG内部创建的g元素:

d3.selectAll("g > *").remove()

in my updateGraph() function

在我updateGraph()函数

Full explanation and situation shown here: Repainting/Refreshing Graph in D3

完整的解释和情况显示在这里:重画/刷新图在D3中