[英]D3 How can i replace a SVG element
我有一個像
<svg>
<g>
<rect x='0' y='0' height='20' width='20' class='shape rect'/>
<text x='10' y='10' text-anchor='middle' alignment-baseline='middle'>A</text>
</g>
</svg>
在用戶輸入時,我試圖將形狀<rect>
替換為其他形狀(例如圓形)
在我的JS中,我有:
// New User Data
var myData = [{
text:A,
shape:'circle',
x:10,
y:10
}];
// Remove existing shape and replace with a new shape
var svg = d3.select('svg');
var g = svg.select('g');
var sh = g.select('.shape);
sh.remove();
var newsh = g.selectAll('.shape').data(myData);
newsh.enter().append('circle').attr({
cx: function(d){ return d.x;},
cy: funciton(d){ return d.y;},
r:10
})
.classed('shape circle',true);
這將在覆蓋了文本的<text>
元素之后向該組添加一個新項目。 構建新數據時如何指定元素的位置。
編輯: FIDDLE
使用selection.append()
將圓附加為其父<g>
元素的最后一個子元素。 由於SVG元素是按文檔順序渲染的,因此它將覆蓋位於新添加的圓之前的文本。 您可以使用selection.insert("circle", ":first-child")
將圓插入組中第一個元素之前,因此在text元素之前。
// New User Data var myData = [{ text:'A', shape:'circle', x:10, y:10 }]; // Remove existing shape and replace with a new shape var svg = d3.select('svg'); var g = svg.select('g'); var sh = g.select('.shape'); sh.remove(); var newsh = g.selectAll('.shape').data(myData); newsh.enter().insert('circle', ':first-child').attr({ "cx": function(d){ return dx;}, "cy": function(d){ return dy;}, "r":10 }) .classed('shape circle',true);
text { fill: white; }
<script src="https://d3js.org/d3.v3.js"></script> <svg> <g> <rect x='0' y='0' height='20' width='20' class='shape rect'/> <text x='10' y='10' text-anchor='middle' alignment-baseline='middle'>A</text> </g> </svg>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.