I am trying to create a data visualization webpage to display bounding boxes(polygons) by taking the coordinates from an annotation file.
The code is working perfectly fine in terms of displaying the polygons but when I added a hide/unhide d3.select(button) and when I click on the toggle button it displays all the polygons but when I click on it again to hide all the polygons, only one polygon gets hidden and I understood why that is happening
because in the for loop it keeps looping through the coordinates of each polygon one by one and displays it,so during the last iteration of for loop the value of bb is saved and given to 'if(bb)',so it takes only the last bounding box coordinates and hides only that polygon and not all.
I tried pushing all the bb values into an array and providing that as a parameter to the if() but it still is not working.
...
<button>toggle polygon </button>
...
...
var bb;
d3.select('button').on('click', function() {
if ( bb ) {
bb.remove();
// Remove bounding box
bb = null;}
else{
for (var line = 2; line < lines.length; line++) { //array to loop through each lines of the annotation file
console.log(line + " --> " + lines[line]);
var annotationline = lines[line].split(' '),
x1 = annotationline[0],
y1 = annotationline[1],
x2 = annotationline[2],
y2 = annotationline[3],
x3 = annotationline[4],
y3 = annotationline[5],
x4 = annotationline[6],
y4 = annotationline[7],
bb= d3.select(template).append("svg")
.attr("width", width)
.attr("height", height),
poly = [{
"x": x1,
"y": y1
},
{
"x": x2,
"y": y2
},
{
"x": x3,
"y": y3
},
{
"x": x4,
"y": y4
}
];
bb.selectAll("polygon")
.data([poly])
.enter().append("polygon")
.attr("points", function(d) {
return d.map(function(d) {
return [d.x, d.y].join(",");
}).join(" ");
})
.attr("stroke","red")
.attr("fill", "none"); }
}
}
...
1条答案
按热度按时间f0ofjuux1#
您的程式码中有两个问题。
1.您将为每一行附加一个svg。
1.如果追加单个svg,则将使用data。输入以使用覆盖所有其他面的最后一个面数据追加svg
我已经更新了你的代码来解决这两个问题
1.在for循环之前追加一次svg。对于每个多边形追加一个group元素(这是比svg更好的方法)
1.我们只更新组,不更新完整的SVG。
最好的方法是写data[poly].update方法,在这里你可以用新的多边形数据更新svg。请在网上阅读如何输入数据并更新它。https://www.d3indepth.com/enterexit/
以下是目前正在工作的代码,切换将删除所有多边形。您的代码可以与
bb.移除();().d3.select();//移除最新引用后移除所有svg
更好的代码版本(这不会移动你的坐标)。学习检查和阅读由d3生成的html。你应该看到下面的输出在整个页面,并阅读生成的html。
第一个