D3.js d3强制布局节点始终从屏幕左上角开始
我有一个强制布局,节点定义如下D3.js d3强制布局节点始终从屏幕左上角开始,d3.js,D3.js,我有一个强制布局,节点定义如下 nodes = someData.map(function (d) { return { image_location: d.image_location, image_width: d.image_width, image_height: d.image_height, aspect_ratio: d.aspect_ratio,
nodes = someData.map(function (d) {
return {
image_location: d.image_location,
image_width: d.image_width,
image_height: d.image_height,
aspect_ratio: d.aspect_ratio,
radius: circleRadiusScale(d.someCount),
x: width/2,
y: height / 2,
px: width/2,
py: height/2,
cx: width/2,
cy: height / 2
};
});
然后在代码后面创建的强制布局中使用
force = d3.layout.force()
.gravity(.05)
.alpha(0.1)
.size([width, height])
.on("tick", tick);
force.nodes(nodes)
.start();
我之所以强制使用x/y、px/py、cx/cy值,是因为我只是想确保节点不会总是从浏览器的左上角开始投影(在强制模拟生效之前,这只是一瞬间,但在firefox或移动设备上尤其明显)
对我来说奇怪的是,我在编写连接圆、图像等浏览器应该显示的代码之前,用我的x/y、cx/cy、px/py值启动强制布局-换句话说,此代码在定义/启动强制布局之后出现
node = svg.selectAll(".node")
.data(force.nodes(), function(d) { return d.id; })
.enter()
.append("g")
.attr("class", "node") etc to append circles, images...
所以我想知道如何通过浏览器保留节点的投影,直到我知道force布局的初始位置不是0,0。谢谢你的任何想法 我会检查
勾选处理函数内的位置,并在满足条件后初始化:
var initialized = false;
force.on("tick", function() {
if(!initialized) {
// can also check multiple nodes here...
if(nodes[0].x != width/2 && nodes[0].y != height/2) initialize();
} else {
// update node positions
}
});
function initialize() {
node = svg.selectAll(".node")
.data(force.nodes(), function(d) { return d.id; })
.enter()
.append("g")
.attr("class", "node") // etc
initialized = true;
}
在我的例子中,节点在调用tick()之前初始化并显示。所以它们将首先显示在屏幕的左上角,然后调用tick()将其转换为图形中的实际位置。
添加图形时仅隐藏节点:
nodeEnter.style("visibility", "hidden")
并且,在tick()函数中可见:
nodeEnter.style("visibility", "visible")
谢谢Lars-这完全解决了问题-只需确保在我在页面上绘制任何圆圈、图像等之前发生了1次勾号。在这种情况下,您甚至可以在启动后和添加处理程序之前调用force.tick()
。