我有以下数据集,只包含文字和颜色信息
var inputs = [{"text": "inleaf1", "col": "red"}, {"text": "inleaf2", "col": "blue"}, {"text": "inleaf3", "col": "green"}];
以下用于绘制带有文本元素的矩形
var inputleaf = container.selectAll("rect")
.data(data)
.enter().append("rect")
.attr("class", "input-leaf")
.attr("width", elementwidth)
.attr("height", elementheight)
.attr("x", startX)
.attr("y", function (d, i) {
return startY + ((elementheight + verticalmargin) * i);
})
.attr("stroke-width", "2")
.attr("fill", "none")
.attr("stroke", function (d) {
return d.col;
})
.call(function (d) {
//--------------------add position details to the data set
});
var inputtext = container.selectAll("text")
.data(data)
.enter().append("text")
.attr("x", startX + elementwidth / 10)
.attr("y", function (d, i) {
return startY + (elementheight / 2) + ((elementheight + verticalmargin) * i);
})
.text(function (d) {
return d.text;
});
在迭代期间,如何向数据集添加更多属性,例如位置详细信息。基本上我想更新数据集。
答案 0 :(得分:2)
This is one solution, maybe not the best one : update you data when you set the attr
. For example :
.attr("y", function (d, i) {
var y = i * 10;
inputs[i].y = y // or d.y = y
return y;
})
See this fiddle
答案 1 :(得分:1)
您可以使用selection.each:
var inputleaf = container.selectAll("rect")
.data(data)
.enter().append("rect")
.attr("class", "input-leaf")
.attr("width", elementwidth)
.attr("height", elementheight)
.attr("x", startX)
.attr("y", function (d, i) {
return startY + ((elementheight + verticalmargin) * i);
})
.attr("stroke-width", "2")
.attr("fill", "none")
.attr("stroke", function (d) {
return d.col;
})
.each(function (d) {
//add position details to the data set
d.x = d3.select(this).attr('x');
d.y = d3.select(this).attr('y');
});