d3在rect内部,访问和绘制嵌套元素

时间:2016-02-06 17:19:46

标签: javascript d3.js svg

我想创建一个包含多个rects的rect。所以输出对于一行看起来像这样(除了类之外没有属性):

<g class="rects">
  <rect class="rect"></rect>
  <g class="rectChildren">
    <rect class="rectChild1"></rect>
    <rect class="rectChild2"></rect>
    <rect class="rectChild3"></rect>
  </g>
</g>

但是,我不知道如何使用d3中的嵌套foreach循环访问和绘制它(参见代码注释)。

JSON:

[
  {"name":"A", "rect":{"x":0, "width":600}, "rectChildren":[{"x":0, "width":200}, {"x":200, "width":200}, {"x":400, "width":200}]},
  {"name":"B", "rect":{"x":0, "width":1200}, "rectChildren":[{"x":0, "width":400}, {"x":400, "width":400}, {"x":800, "width":400}]}
]

代码:

var data;
d3.json("flare.json", function(error, flare) {
    if (error) throw error;
    data = flare;
});
var nodes = tree.nodes(data);
var barHeight = 40;

// Update the nodes…
var rects = svg.selectAll("g.rects")
    .data(nodes, function(d) { return d.id || (d.id = ++i); });

//first group
var rectsEnter = rects.enter().append("g")
    .attr("class", "rects");

rectsEnter
    .append("rect")
    .attr("class", "rect")
    .attr("y", function(d, i) { return i * (10 + barHeight); })
    .attr("height", barHeight)
    .attr("width", function(d) { return d.width; })
    .style("fill", "blue");

var rectChildren = rectsEnter
    //here I need something like:
    //foreach(r in d.rectChildren)
    //do
    .append("rect")
    .attr("class", "rectChild")
    .attr("y", function(d, i) { return i * barHeight + 10; })
    .attr("height", barHeight)
    .attr("width", function(d) { return d.width; })
    .style("fill", "green");   

0 个答案:

没有答案