在更新由circle
元素内的g
组成的包布局时,我遇到了一些问题,其中转换由g
控制,并且半径由...控制circle
:
<g transform="translate(1,1)"><circle r="1"></circle></g>
可以通过圈子控制翻译进行更新,但我的错误x
,y
和r
以及g
作为容器,如在demo中那样。
var diameter = 300;
function translate(x, y) {
return "translate(" + x + "," + y + ")";
}
// The layout I'm using now
var pack = d3.layout.pack()
.size([diameter - 4, diameter - 4])
.value(function(d) { return 1; });
// The basic container
var svg = d3.select("body").append("svg")
.attr("width", diameter)
.attr("height", diameter)
.append("g")
.attr("transform", "translate(2,2)");
// My initial data source
var data = {
name: "Languages",
children: [{
name: "Functional",
children: [
{ name: "OCaml" },
{ name: "Haskell" },
{ name: "Erlang" }
]
}, {
name: "Imperative",
children: [
{ name: "BASIC" },
{ name: "Clipper" }
]
}]
};
(window.update = function() {
// Modify the current data object
data.children.push({
name: "NEW ELEMENT " + Math.floor(Math.random() * 100)
});
// Select *ALL* elements
var selection = svg.datum(data).selectAll(".node")
.data(pack.nodes);
// Select *ONLY NEW* nodes and work on them
selection
.enter()
.append("g")
.classed("node", true)
.append("circle")
.style("fill", "black");
// Recompute *ALL* elements
// Here the results aren't consistent, I always get the wrong translation
// and radius, therefore, the elements are badly positioned
selection
.transition()
.duration(500)
.attr("transform", function(d) {
return translate(d.x, d.y);
})
.selectAll("circle")
.attr("r", function(d) {
return d.r;
});
})();
// Set the height
d3.select(self.frameElement).style("height", diameter + "px");
我看到我正在选择正确的元素,但为什么每当我拨打update
时我的结果都会出错?
答案 0 :(得分:0)
嗯,代码大部分是正确的,但是selectAll("circle")
将选择所有圆形元素并为所有圆形元素应用内部元素的半径。我们只需要选择内圈,因此select("circle")
解决了问题(demo)。