要在JavaScript中实现人物关系图,可以使用一些图表库,如D3.js、ECharts或jsPlumb等。以下是使用D3.js实现一个简单的人物关系图的示例:
以下是一个使用D3.js实现简单人物关系图的示例代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>人物关系图</title>
<script src="https://d3js.org/d3.v7.min.js"></script>
<style>
.node {
stroke: #fff;
stroke-width: 1.5px;
}
.link {
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: "Alice", group: 1},
{id: "Bob", group: 1},
{id: "Charlie", group: 1},
{id: "David", group: 2},
{id: "Eve", group: 2}
];
const links = [
{source: "Alice", target: "Bob"},
{source: "Alice", target: "Charlie"},
{source: "Bob", target: "David"},
{source: "Charlie", target: "Eve"}
];
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)
.call(d3.drag()
.on("start", dragstarted)
.on("drag", dragged)
.on("end", dragended));
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);
});
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;
}
</script>
</body>
</html>
通过以上步骤,你可以实现一个简单的人物关系图,并根据需要进行扩展和定制。
没有搜到相关的文章