在 JavaScript 中绘制有向图可以通过多种方式实现,常见的有以下几种:
基础概念: 有向图是由顶点(节点)和有方向的边组成的图结构。
优势:
类型:
应用场景:
常见的实现方式之一是使用 D3.js
库:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>有向图示例</title>
<script src="https://d3js.org/d3.v7.min.js"></script>
<style>
.node {
fill: #69b3a2;
stroke: #fff;
stroke-width: 1.5px;
}
.link {
fill: none;
stroke: #999;
stroke-opacity: 0.6;
}
</style>
</head>
<body>
<svg width="600" height="400"></svg>
<script>
const svg = d3.select("svg");
const width = +svg.attr("width");
const height = +svg.attr("height");
const nodes = [
{ id: "A" },
{ id: "B" },
{ id: "C" },
{ id: "D" }
];
const links = [
{ source: "A", target: "B" },
{ source: "A", target: "C" },
{ source: "B", target: "D" },
{ source: "C", target: "D" }
];
const simulation = d3.forceSimulation(nodes)
.force("link", d3.forceLink(links).id(d => d.id))
.force("charge", d3.forceManyBody())
.force("center", d3.forceCenter(width / 2, height / 2));
const link = svg.append("g")
.attr("class", "links")
.selectAll("line")
.data(links)
.enter().append("line")
.attr("class", "link");
const node = svg.append("g")
.attr("class", "nodes")
.selectAll("circle")
.data(nodes)
.enter().append("circle")
.attr("class", "node")
.attr("r", 10);
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);
});
</script>
</body>
</html>
可能出现的问题及原因:
d3.forceSimulation
中力的参数,如电荷力、中心力等。领取专属 10元无门槛券
手把手带您无忧上云