我有這樣的svg:
<svg id="mySvg">
<path></path>
<path></path>
<path></path>
</svg>
但我想將這個 svg 中的所有路徑分組到g標簽內,所以它看起來像這樣:
<svg id="mySvg">
<g>
<path></path>
<path></path>
<path></path>
</g>
</svg>
我該怎么做?
d3.select("#mySvg").append("g") // -> and move all paths inside g
uj5u.com熱心網友回復:
您可以使用 洗掉元素selection.remove()。此方法將回傳已洗掉元素的選擇。
您還可以使用selection.append()附加這些元素。但是, selection.append 只接受一個函式或一個字串。如果您提供一個函式,它應該回傳一個(單個)元素/節點。我們可以訪問一個元素選擇的元素/節點selection.node()
這給了我們模式:
let svg = d3.select('svg')
let path = svg.selectAll('path').remove();
svg.append('g').append(()=>path.node());
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/7.0.0/d3.min.js"></script>
<svg>
<path d="M 30 30 C 60 30 50 50 80 50" stroke="black" stroke-width="1" fill="none"></path>
</svg>
但是, append() 是為單個元素設計的。如果您有很多元素,則可以使用selection.each()將每個選定元素添加到 parent g:
let svg = d3.select('svg')
let path = svg.selectAll('path').remove();
let g = svg.append('g');
path.each(function() {
g.append(()=>this);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/7.0.0/d3.min.js"></script>
<svg>
<path d="M 30 30 C 60 30 50 50 80 50" stroke="black" stroke-width="1" fill="none"></path>
<path d="M 30 130 C 60 130 50 150 80 150" stroke="black" stroke-width="1" fill="none"></path>
</svg>
使用 function() 和粗箭頭表示法旨在確保正確的this,這是我們要添加到父 g 的元素
無論選擇一個或多個節點,第二個片段都將起作用。
uj5u.com熱心網友回復:
在過去的幾年里,我提出了一些類似于Andrew Reid 在他的回答中提出的方法:“我可以在 d3.js 中的 SVG 組之間移動 SVG 元素”和“D3.js 如何將選擇嵌入到新元素中” ”。然而,深入研究這個問題,我發現了一個使用 VanillaJS DOM 方法并在單個方法呼叫中完成整個 shebang 的解決方案。
an 的 APIElement知道一些同時向 DOM 添加多個元素的方法。該element.append()方法可用于path在一次運行中優雅且輕松地將元素附加到新組中。
const path = d3.selectAll("path");
d3.select("svg")
.insert("g") // insert the new g at the first position
.node() // get the DOM node
.append( // use the DOM's append, not the D3 one
...path.nodes() // add the nodes from the path selection
);
<script src="https://d3js.org/d3.v7.js"></script>
<svg id="mySvg">
<path></path>
<path></path>
<path></path>
</svg>
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/511498.html
標籤:d3.js
上一篇:React/Javascript-將本地csv中的值保存到useState/useEffect
下一篇:D3出現錯誤
