[英]d3 remove text from svg
我有修改路徑的S命令的滑塊。 我希望源名稱顯示在它所做的路徑上; 但是,如何刪除以前創建的文本元素? 我試圖將其刪除(請參見下面的代碼),但是它不起作用。 dom僅填充了多余的文本元素,路徑上的文本隨着彼此開始堆積而變得越來越暗。 我什至試圖通過顯示的id檢查文本元素,但沒有成功。 希望您能對如何刪除文本元素有所了解,以便在修改每個S命令時只有一個。
我在這里添加了一個小提琴(在代碼窗口的最底部添加了文本): 小提琴...
graph.links.forEach(function (d, i) {
//console.log(obj[0].text, graph.links[i].source.name, graph.links[i].linkid);
if (graph.links[i].source.name == obj[0].text) {
var linkid = graph.links[i].linkid;
var the_path = $("#" + linkid).attr("d");
var arr = $("#" + linkid).attr("d").split("S");
//update S command
$("#" + linkid).attr("d", arr[0] + " S" + scommand_x2 + "," + scommand_y2 + " " + scommand_x + "," + scommand_y);
svg.select("#txt_" + linkid).remove();
svg.selectAll("#" + linkid).data(graph.links).enter()
.append("text")
.attr("id", "txt_" + linkid)
.append("textPath")
.attr("xlink:href", function (d) {
return "#" + linkid;
})
.style("font-size", fontSize + "px")
.attr("startOffset", "50%")
.text("")
.text(graph.links[i].source.name);
}
});
這是一個解決方案:
https://jsfiddle.net/kx3u23oe/
我做了兩件事。 首先,您不需要像以前那樣將文本綁定到數據。 其次,我將變量與所有append
一起移到update
函數之外:
var someText = svg.append("text").append("textPath");
然后,我只保留了此內部update
功能:
someText.attr("xlink:href", "#L0")
.style("font-size", "12px")
.attr("startOffset", "50%")
.text("some text");
您可以使用“刪除”功能刪除文本元素。 這是相同的工作代碼段。
var text = d3.select("body") .append("text") .text("Hello..."); setTimeout(function() { text.remove(); }, 800);
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
順便說一句,代碼中的問題是,您正在遍歷每個鏈接( graph.links.forEach(function (d, i) {
)並為所有鏈接創建一個文本元素( .data(graph.links).enter()
),每次創建n * n個文本標簽;其中n是鏈接數,因此我假設您的代碼應如下所示。
svg.select("#txt_" + linkid).remove();
svg.selectAll("#" + linkid)
.append("text")
.attr("id", "txt_" + linkid)
.append("textPath")
.attr("xlink:href", function (d) {
return "#" + linkid;
})
.style("font-size", fontSize + "px")
.attr("startOffset", "50%")
.text(graph.links[i].source.name);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.