我在 html 页面上有一些 svg。我想在它们上面绑定一些数据,并根据该数据添加装饰元素。我认为我必须做的是:
// pseudo-code
selection = select all existing svg piece i want to decorate
var datas = selection.each( function(d,i) { // each is right? maybe selection.datum() is better?
var data = this.(do something with the svg piece)
return data;
});
// add elements with the "default" chain selection.data(datas).enter().append()
我注意到的是 selection.each 没有返回我可以找到返回数据的东西。我认为这是方法,但我无法弄清楚我必须做什么才能看到绑定的数据。
所以我必须做一些肮脏的解决方法,比如:
var datas = [];
selection.each( function(d,i) { // each is right? maybe selection.datum() is better?
var data = this.(do something with the svg piece)
datas.push(data);
});
为什么?如何在不手动将数据推送到数组中并在一些现有的 svg 元素中绑定数据的情况下做类似的事情?
这是一个jsFiddle 示例。
或者,如果您愿意,可以使用以下代码:
html:
<div id="container">
<svg>
<rect id="0" x="0" y="50" width="30" height="30"/>
<rect id="1" x="50" y="50" width="30" height="30"/>
<rect id="2" x="100" y="50" width="30" height="30"/>
<rect id="3" x="150" y="50" width="30" height="30"/>
<rect id="4" x="200" y="50" width="30" height="30"/>
<rect id="5" x="250" y="50" width="30" height="30"/>
</svg>
</div>
js:
var svg = d3.select("#container svg");
var districts = svg.selectAll("rect");
var district_data = [];
var _c = districts.each(function(d, i) {
var bbox = this.getBBox();
var centroid = [
bbox.x + bbox.width/2,
bbox.y + bbox.height/2
];
var ret = {centroid:centroid, position:bbox.x};
district_data.push( ret );
return ret;
});
// now, i'm expecting that _c should be something
// similar to district_data
console.log(_c);
svg
.selectAll("circle")
.data(district_data) // i think i should use `_c` instead of manually created `district_data` but does not work
.enter()
.append("circle")
.attr("class", "district_circle")
.attr("cx", function(d){ return d.centroid[0]})
.attr("cy", function(d){ return d.centroid[1]})
.attr("r", 10)
.attr("fill", function(d){ return "rgb("+d.position+",0,0)"});