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