我正在嘗試創建一個資料可視化網頁,通過從注釋檔案中獲取坐標來顯示邊界框(多邊形)。
該代碼在顯示多邊形方面作業得非常好,但是當我添加一個隱藏/取消隱藏 d3.select(button) 并且當我單擊切換按鈕時它顯示所有多邊形但是當我再次單擊它以隱藏所有多邊形,只有一個多邊形被隱藏,我明白為什么會這樣
因為在for回圈中它會不斷回圈遍歷每個多邊形的坐標并顯示它,所以在for回圈的最后一次迭代中,bb的值被保存并賦予'if(bb)',所以它只需要最后一個邊界框坐標并僅隱藏該多邊形而不是全部。
我嘗試將所有 bb 值推入一個陣列并將其作為引數提供給 if() 但它仍然無法正常作業。
...
<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"); }
}
}
...
uj5u.com熱心網友回復:
您的代碼中有兩個問題。
- 您正在為每一行附加一個 svg。
- 如果附加單個 svg,則使用 data.enter 附加最后一個多邊形資料,這會覆寫所有其他多邊形
我已更新您的代碼以解決這兩個問題
- 在 for 回圈之前附加一個 svg。為每個多邊形附加一個組元素(這比 svg 更好)
- 我們只更新組而不是完整的 svg。
最好的方法是撰寫 data[poly].update 方法,您可以在其中使用新的多邊形資料更新 svg。在網上閱讀有關如何輸入資料和更新資料的資訊。 https://www.d3indepth.com/enterexit/
現在下面是正在運行的代碼,并且切換將洗掉所有多邊形。您的代碼可以使用
bb.remove(); d3.select('svg').remove(); // 洗掉最新參考后洗掉所有 svg
更好的代碼版本(這也不會移動您的坐標)。學習檢查和閱讀 d3 生成的 html。您應該在整頁中看到下面的輸出并閱讀生成的 html。
var bb;
d3.select('button').on('click', function() {
if (bb) {
bb.remove();
// Remove bounding box
bb = null;
} else {
bb = d3.select(".template").append("svg")
.attr("width", '300')
.attr("height", '400');
for (var line = 2; line < 4; line ) { //array to loop through each lines of the annotation file
var annotationline = 9,
x1 = 23 * line / 2,
y1 = 34 line,
x2 = 27 * line / 2,
y2 = 34 line,
x3 = 145 * line / 2,
y3 = 65 * line / 2,
x4 = 145 * line / 2,
y4 = 59 * line / 2,
poly = [{
"x": x1,
"y": y1
},
{
"x": x2,
"y": y2
},
{
"x": x3,
"y": y3
},
{
"x": x4,
"y": y4
}
];
let g = bb.append('g');
g.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");
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/7.4.4/d3.min.js" integrity="sha512-hnFpvCiJ8Fr1lYLqcw6wLgFUOEZ89kWCkO cEekwcWPIPKyknKV1eZmSSG3UxXfsSuf z/SgmiYB1zFOg3l2UQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<button>toggle polygon </button>
<div class="template">
</div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/494552.html
標籤:javascript html d3.js
下一篇:如何理解isNaN
