我使用html
创建了一个d3.js
页面来创建和控制相当复杂的svg
。页面的一部分响应鼠标移动,并且根据鼠标的位置,页面的另一部分显示散点图。每次鼠标移动时,都会擦除并重绘该散点图。此功能很有效。但是,我必须通过clipPath
添加defs
,当path
更新时,clipPath
也需要在鼠标移动时清除。这导致页面中有数百个空标记,如下所示:<defs></defs>
,当鼠标移动时。
问题:有没有办法清除这些空标签?我不喜欢他们,我认为他们可能会对表现产生影响。
以下是产生这些空标记的代码:
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");
}
ORIGINAL:
//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