[英]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.