首先引入D3库并定义包含nodes和links的数据结构,接着创建SVG容器并初始化力模拟,设置边、电荷和中心力;然后绘制连线、节点及标签,最后通过监听tick事件更新元素位置,并添加拖拽交互以实现动态调整。

力导向图(Force-directed Graph)是数据可视化中常见的一种形式,特别适合展示节点之间的关系网络。D3.js 作为强大的 JavaScript 可视化库,提供了完整的物理引擎支持,可以轻松实现力导向图。下面介绍如何使用 D3.js 创建一个基础但功能完整的力导向图。
要使用 D3.js 实现力导向图,首先引入 D3 库。可以通过 CDN 引入最新版本:
<script src="https://d3js.org/d3.v7.min.js"></script>力导向图的数据通常包含两个数组:nodes(节点)和 links(边)。例如:
const graph = {
nodes: [
{ id: "A" },
{ id: "B" },
{ id: "C" }
],
links: [
{ source: "A", target: "B" },
{ source: "B", target: "C" }
]
};
每个节点有唯一 id,每条边指定 source 和 target 节点。
立即学习“Java免费学习笔记(深入)”;
使用 SVG 绘制图形,并初始化 D3 的力模拟(force simulation):
const width = 800;
const height = 600;
const svg = d3.select("body")
.append("svg")
.attr("width", width)
.attr("height", height);
const simulation = d3.forceSimulation(graph.nodes)
.force("link", d3.forceLink(graph.links).id(d => d.id).distance(100))
.force("charge", d3.forceManyBody().strength(-300))
.force("center", d3.forceCenter(width / 2, height / 2));
说明:
在 SVG 中添加线段表示边,圆形表示节点:
const link = svg.append("g")
.selectAll("line")
.data(graph.links)
.enter()
.append("line")
.attr("stroke", "#999")
.attr("stroke-width", 1);
const node = svg.append("g")
.selectAll("circle")
.data(graph.nodes)
.enter()
.append("circle")
.attr("r", 8)
.attr("fill", "#4285f4")
.call(d3.drag()
.on("start", dragstarted)
.on("drag", dragged)
.on("end", dragended)
);
同时为节点添加标签(可选):
const label = svg.append("g")
.selectAll("text")
.data(graph.nodes)
.enter()
.append("text")
.text(d => d.id)
.attr("font-size", 12)
.attr("dx", 12)
.attr("dy", 4);
监听模拟的 tick 事件,在每次迭代后更新节点、边和标签的位置:
simulation.on("tick", () => {
link
.attr("x1", d => d.source.x)
.attr("y1", d => d.source.y)
.attr("x2", d => d.target.x)
.attr("y2", d => d.target.y);
node
.attr("cx", d => d.x)
.attr("cy", d => d.y);
label
.attr("x", d => d.x)
.attr("y", d => d.y);
});
拖拽函数用于交互式调整节点位置:
function dragstarted(event, d) {
if (!event.active) simulation.alphaTarget(0.3).restart();
d.fx = d.x;
d.fy = d.y;
}
function dragged(event, d) {
d.fx = event.x;
d.fy = event.y;
}
function dragended(event, d) {
if (!event.active) simulation.alphaTarget(0);
d.fx = null;
d.fy = null;
}
通过设置 d.fx 和 d.fy,可以在拖动时固定节点位置,提升交互体验。
基本上就这些。只要数据结构清晰,D3 力导向图就能自动布局并支持交互。可根据需要添加颜色映射、提示框、缩放等功能进一步增强可视化效果。
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号