Javascript 删除svg文档中的空标记
我已经使用d3.js创建了一个html页面来创建和控制一个相当复杂的svg。页面的一部分响应鼠标移动,根据鼠标的位置,页面的另一部分显示散点图。每次鼠标移动时,此散点图都会被删除并重新绘制。此功能运行良好。但是,我必须通过defs添加clipPath,当路径更新时,clipPathalso需要随着鼠标移动而清除。这会导致页面中出现数百个空标记,如下所示:随着鼠标移动 问题:有没有办法清除这些空标签?我不喜欢他们在那里,我想在某个时候,他们可能会对性能产生影响 以下是导致这些空标记的代码位:Javascript 删除svg文档中的空标记,javascript,svg,d3.js,Javascript,Svg,D3.js,我已经使用d3.js创建了一个html页面来创建和控制一个相当复杂的svg。页面的一部分响应鼠标移动,根据鼠标的位置,页面的另一部分显示散点图。每次鼠标移动时,此散点图都会被删除并重新绘制。此功能运行良好。但是,我必须通过defs添加clipPath,当路径更新时,clipPathalso需要随着鼠标移动而清除。这会导致页面中出现数百个空标记,如下所示:随着鼠标移动 问题:有没有办法清除这些空标签?我不喜欢他们在那里,我想在某个时候,他们可能会对性能产生影响 以下是导致这些空标记的代码位: sv
svg.append('rect') // outline x slice region (done once)
// this is both an aesthetic feature and is used as the clipPath
.attr({x: lPad,
y: tPad + conHeight + gap,
width: xslWidth,
height: xslHeight,
id: "xViewport",
stroke: 'black',
'stroke-width': 1.5,
fill:'white'});
// everything below here responds to the mouse and constantly changes
// prepare to draw: remove existing path and clipPath
d3.selectAll(".xslice") // these 'removes' work but leave the empty tags
.remove();
d3.selectAll(".xViewport")
.remove();
d3.selectAll("#xClipBox")
.remove();
// snip: lots of data preparation skipped
// the data used depends on mouse position which changes constantly
// now ready to draw
编辑:添加了这个逻辑。它可以防止文档被空标记污染,但不再剪辑
if (d3.select("#xClipBox").length) {
// already exists, no need to do anything
console.log("xClipBox exists")
} else { // create it if missing
var clip = svg.append("defs").append("clipPath")
.attr("id", "xClipBox")
clip.append("use").attr("xlink:href", "#xViewport");
}
原件:
//var clip = svg.append("defs").append("clipPath") // EDIT: never changes
// .attr("id", "xClipBox")
// clip.append("use").attr("xlink:href", "#xViewport"); // EDIT: never changes
//var xSlice = svg.append("g") // EDIT: never changes
// .attr("clip-path", "url(#xClipBox)")
//.attr("class", "xViewport")
继续:
xSlice.append("path") // EDIT: this part responds to the mouse position
.attr("transform", "translate(" + lPad + ","
+ (tPad + conHeight + gap) + ")")
.attr({width: xslWidth,
height: xslHeight,
"class": "line",
"class": "xslice",
"d": slice(xy)})
// All of this repeats each time the mouse moves
您不能在添加之前检查中是否存在defs子元素吗?在这种情况下,您只需添加一次def,如果它已经存在,只需附加到它。您的建议与我想要的差不多,但我不确定如何检查现有的def。clipPath从不改变,我只想反复使用它。我以为删除会删除def,但它会删除标签之间的内容,留下空标签。你可以检查defs是否有未定义的内容。如果存在,则重用它;如果不存在,则创建它。请看本例中的一个类比:我们将尝试这样做。谢谢另外,刚刚访问了你们的网站,上面有鱼帽和翼手龙模型,非常好。请看原始问题中的编辑。