gpt4 book ai didi

javascript - D3 力导向布局 : bounding box

转载 作者:行者123 更新时间:2023-11-29 22:01:01 25 4
gpt4 key购买 nike

这里提出了一个非常相似的问题:D3 force directed layout with bounding box ...我尝试实现建议的解决方案但没有成功,所以我会再问一次:(

这是我的代码

// initialization stuff happening up here...
// create graph:

this.onStateChange = function() {

svg.selectAll("g").remove();
nodes = {};
links = [];

links = eval(this.getState().string);
links.forEach(function(link) {
link.source = nodes[link.source] || (nodes[link.source] = {name : link.source});
link.target = nodes[link.target] || (nodes[link.target] = {name : link.target});
});

force.nodes(d3.values(nodes)).links(links).start();

path = svg.append("g").selectAll("path")
.data(force.links()).enter()
.append("path")
.attr("class", function(d) {return "link " + d.type;})
.attr("marker-end", function(d) {return "url(#" + d.type + ")";});

circle = svg.append("g").selectAll("circle")
.data(force.nodes())
.enter()
.append("circle")
.attr("r", 8)
.call(force.drag);

text = svg.append("g").selectAll("text")
.data(force.nodes())
.enter()
.append("text")
.style("font-size","15px")
.attr("x", 10)
.attr("y", ".42em").text(function(d) {return d.name;});
};

//add gravity
function tick() {

path.attr("d", linkArc);
circle.attr("transform", transform);
text.attr("transform", transform);


circle.attr("cx", function(d) { return d.x = Math.max(r, Math.min(w - r, d.x)); })
.attr("cy", function(d) { return d.y = Math.max(r, Math.min(h - r, d.y)); });

path.attr("x1", function(d) { return d.source.x; })
.attr("y1", function(d) { return d.source.y; })
.attr("x2", function(d) { return d.target.x; })
.attr("y2", function(d) { return d.target.y; });


}

function linkArc(d) {
var dx = d.target.x - d.source.x,
dy = d.target.y - d.source.y,
dr = Math.sqrt(dx * dx + dy * dy);

return "M" + d.source.x + ","
+ d.source.y + "A" + dr + "," + dr
+ " 0 0,1 " + d.target.x + "," + d.target.y;
}

function transform(d) {
return "translate(" + d.x + "," + d.y + ")";
}
};

但这不起作用 - 我无法再移动节点,它们卡在右上角。

最佳答案

我发现了它是怎么回事。如果有人想向这个移动专利诉讼示例 ( http://bl.ocks.org/mbostock/1153292 ) 添加边界框,这可能会有所帮助:

function tick() {   
//circle.attr("transform", transform); //no need for this anymore

circle.attr("cx", function(d) { return d.x = Math.max(8, Math.min(300 - 8, d.x)); })
.attr("cy", function(d) { return d.y = Math.max(8, Math.min(280 - 8, d.y)); });
text.attr("transform", transform);
path.attr("d", linkArc);

}
function linkArc(d) {
var dx = d.target.x - d.source.x,
dy = d.target.y - d.source.y,
dr = Math.sqrt(dx * dx + dy * dy);

return "M" + d.source.x
+ "," + d.source.y
+ "A" + dr
+ "," + dr
+ " 0 0,1 " + d.target.x
+ "," + d.target.y;
}
//function transform(d) { //don't need this anymore either
//return "translate(" + d.x + "," + d.y + ")";
//}
};

关于javascript - D3 力导向布局 : bounding box,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23770194/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com