【发布时间】:2015-07-16 00:28:33
【问题描述】:
我有想要添加到 SVG 的数据对象。考虑以下伪 sn-p:
var data = [], counter = 0;
for (var col=1; col<=5; col++)
for (var row=1; row<=3; row++)
data.push({
id: "obj-" + ++counter
,x: col * 120
,y: row * 120
,width: 40
,height: 40
,shape: counter % 2 ? "circle" : "rect"
});
d3.select(".container").selectAll(".obj")
.data(data)
.enter()
.append("g")
.attr("id", function(d){ return d.id; }
/***
now I want to draw here a circle or rect based on the shape key
so if (d.shape == "rect") -- we will use width and height
if (d.shape == "rect" && d.width == d.height) we will set "r" to "width", etc.
***/
理想情况下,我会创建一个 Shape 类型的对象,例如
function Shape(id, shape, x, y, w, h) {
this.id = id;
this.shape = shape;
this.x = x;
this.y = y;
this.width = w;
this.height = h;
this.render = function(parent) {
var g = parent.append("g")
.attr("id", this.id);
switch (this.shape) {
case "circle":
g.append("circle")
.attr( /* more code here */ )
break;
case "rect":
g.append("rect")
.attr( /* more code here */ )
break;
case "triangle":
g.append("polygon")
.attr( /* more code here */ )
break;
}
}
}
然后我可以做类似的事情:
var data = [], counter = 0;
for (var col=1; col<=5; col++)
for (var row=1; row<=3; row++)
data.push(new Shape({
id: "obj-" + ++counter
,x: col * 120
,y: row * 120
,width: 40
,height: 40
,shape: counter % 2 ? "circle" : "rect"
)});
但是我怎样才能从 d3 调用 Shape 的 render() 方法呢?即
d3.select(".container").selectAll(".obj")
.data(data)
.enter()
/* given a datum named d, call d.render(parent) ? */
我对 d3 比较陌生,所以也许数据连接是错误的方法?是否有其他方法可以更好地呈现这种情况下的数据项?
【问题讨论】:
-
这实际上不适用于 D3。我想你可以附加一个
g元素,然后调用.each(function(d) { d.render(this); }),但这有点不合时宜。 -
是否有任何 d3 内部库可以做到这一点。 5 年过去了,他们更新了很多东西。
标签: javascript oop d3.js svg