gpt4 book ai didi

javascript - d3.js 更改不同图像的节点并设置不同距离的链接

转载 作者:行者123 更新时间:2023-11-28 08:42:51 28 4
gpt4 key购买 nike

我之前的问题是这个How to display images based on their distance to the center image? ?有人建议我使用 d3.js。这是我的文档中的代码。我想知道如何用不同的图像更改这些节点,是否可以使链接具有不同的距离?

<!DOCTYPE html>
<meta charset="utf-8">
<style>

.link {
stroke: #000;
stroke-width: 1.5px;
}

.node {
fill: #000;
stroke: #fff;
stroke-width: 1.5px;
}

.node.a { fill: #ff7f0e; }
.node.b { fill: #2ca02c; }
.node.c { fill: #2ca02c; }
.node.d { fill: #2ca02c; }


</style>
<body>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>

var width = 960,
height = 500;

var color = d3.scale.category10();

var nodes = [],
links = [];

var force = d3.layout.force()
.nodes(nodes)
.links(links)
.charge(-400)
.linkDistance(120)
.size([width, height])
.on("tick", tick);

var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);

var node = svg.selectAll(".node"),
link = svg.selectAll(".link");


setTimeout(function() {
var a = {id: "a"}, b = {id: "b"}, c = {id: "c"},d = {id: "d"};

nodes.push(a, b, c, d);
links.push({source: a, target: b}, {source: a, target: c},{source: a, target: d});
start();
}, 0);



function start() {
link = link.data(force.links(), function(d) { return d.source.id + "-" + d.target.id; });
link.enter().insert("line", ".node").attr("class", "link");
link.exit().remove();

node = node.data(force.nodes(), function(d) { return d.id;});
node.enter().append("circle").attr("class", function(d) { return "node " + d.id; }).attr("r", 8);
node.exit().remove();

force.start();
}

function tick() {
node.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; })

link.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; });
}

</script>

我的最终预期输出应如下所示:enter image description here

最佳答案

您可以使用 linkDistance() function 调整节点之间的距离。代码看起来像这样。

force.linkDistance(function(d) {
return d.distance; // each link data element has a member "distance"
});

请注意,这些只是弱几何约束。这意味着,如果您指定两个节点之间的距离为 10,那么最终的距离可能不是 10,而是 12。如果您需要特定距离,则使用力布局是错误的。

关于javascript - d3.js 更改不同图像的节点并设置不同距离的链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20296447/

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