js 怎么输出一张有向图?
时间: 2024-01-22 19:02:01 浏览: 19
要输出一张有向图,你可以使用一些第三方库,如 D3.js 或 vis.js。这些库提供了许多有用的函数和工具,可以让你很容易地创建和可视化有向图。
下面是一个使用 D3.js 输出有向图的示例代码:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>D3 Directed Graph Example</title>
<script src="https://d3js.org/d3.v6.min.js"></script>
</head>
<body>
<svg width="500" height="500"></svg>
<script>
const nodes = [
{ id: "A" },
{ id: "B" },
{ id: "C" },
{ id: "D" },
];
const links = [
{ source: "A", target: "B" },
{ source: "B", target: "C" },
{ source: "C", target: "D" },
{ source: "D", target: "A" },
];
const svg = d3.select("svg");
const simulation = d3.forceSimulation(nodes)
.force("link", d3.forceLink(links).id(d => d.id).distance(100))
.force("charge", d3.forceManyBody().strength(-100))
.force("center", d3.forceCenter(250, 250));
const link = svg.append("g")
.attr("stroke", "#999")
.attr("stroke-opacity", 0.6)
.selectAll("line")
.data(links)
.join("line")
.attr("marker-end", "url(#arrow)");
const node = svg.append("g")
.attr("stroke", "#fff")
.attr("stroke-width", 1.5)
.selectAll("circle")
.data(nodes)
.join("circle")
.attr("r", 15)
.attr("fill", "#ccc")
.call(drag(simulation));
node.append("title")
.text(d => d.id);
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);
});
const defs = svg.append("defs");
defs.append("marker")
.attr("id", "arrow")
.attr("viewBox", "0 -5 10 10")
.attr("refX", 25)
.attr("refY", 0)
.attr("markerWidth", 6)
.attr("markerHeight", 6)
.attr("orient", "auto")
.append("path")
.attr("d", "M0,-5L10,0L0,5");
function drag(simulation) {
function dragstarted(event) {
if (!event.active) simulation.alphaTarget(0.3).restart();
event.subject.fx = event.subject.x;
event.subject.fy = event.subject.y;
}
function dragged(event) {
event.subject.fx = event.x;
event.subject.fy = event.y;
}
function dragended(event) {
if (!event.active) simulation.alphaTarget(0);
event.subject.fx = null;
event.subject.fy = null;
}
return d3.drag()
.on("start", dragstarted)
.on("drag", dragged)
.on("end", dragended);
}
</script>
</body>
</html>
```
这个例子中,我们定义了一个包含 4 个节点和 4 条边的有向图。然后,我们使用 D3.js 的力学模拟功能来进行布局,并在 SVG 元素中创建节点和边。最后,我们使用箭头标记来表示有向边的方向。