简体   繁体   English

D3如何更换SVG元素

[英]D3 How can i replace a SVG element

I have an svg like 我有一个像

<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>

On user input I am trying to replace the shape <rect> to a different shape (say a circle) 在用户输入时,我试图将形状<rect>替换为其他形状(例如圆形)

In my JS I have: 在我的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);

This appends a new item to the group after the <text> element covering up the text. 这将在覆盖了文本的<text>元素之后向该组添加一个新项目。 How can I specify the position of the elements when building new data. 构建新数据时如何指定元素的位置。

EDIT: FIDDLE 编辑: FIDDLE

Using selection.append() will append the circle as the last child of its parent <g> element. 使用selection.append()将圆附加为其父<g>元素的最后一个子元素。 Because SVGs elements are rendered in document order, this will cover the text which is located before the newly appended circle. 由于SVG元素是按文档顺序渲染的,因此它将覆盖位于新添加的圆之前的文本。 You can use selection.insert("circle", ":first-child") to insert the circle before the first element in the group, and, hence, before the text element. 您可以使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM