// 引入 d3.js 库
<script src="https://d3js.org/d3.v6.min.js"></script>
// 创建一个 SVG 容器
const svg = d3.select("body")
.append("svg")
.attr("width", 800)
.attr("height", 600);
// 树状图的数据结构
const data = {
"name": "root",
"children": [
{ "name": "child1" },
{ "name": "child2" },
{
"name": "child3",
"children": [
{ "name": "grandchild1" },
{ "name": "grandchild2" }
]
}
]
};
// 创建树布局
const treeLayout = d3.tree()
.size([600, 400]);
// 创建分层数据
const root = d3.hierarchy(data);
// 将分层数据应用到树布局中
treeLayout(root);
// 绘制连接线 (父子节点之间的连线)
svg.selectAll(".link")
.data(root.links())
.enter()
.append("line")
.attr("class", "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)
.style("stroke", "#ccc");
// 绘制节点
svg.selectAll(".node")
.data(root.descendants())
.enter()
.append("circle")
.attr("class", "node")
.attr("cx", d => d.x)
.attr("cy", d => d.y)
.attr("r", 5)
.style("fill", "steelblue");
// 添加文本标签
svg.selectAll(".node-label")
.data(root.descendants())
.enter()
.append("text")
.attr("class", "node-label")
.attr("x", d => d.x + 10)
.attr("y", d => d.y)
.text(d => d.data.name)
.style("fill", "black");
<script>
标签引入 d3.js 库,确保可以在页面中使用 d3 的功能。d3.select
方法选择页面中的 body
元素,并在其内部添加一个 svg
元素作为绘图容器。name
属性,子节点存储在 children
数组中。d3.tree()
创建一个树布局,并设置其大小(宽度和高度)。d3.hierarchy()
将 JSON 数据转换为分层数据结构。svg.selectAll(".link")
选择所有连接线元素,并根据树布局生成的链接数据绘制线条。svg.selectAll(".node")
选择所有节点元素,并根据树布局生成的节点位置绘制圆形节点。svg.selectAll(".node-label")
选择所有文本标签元素,并在每个节点旁边添加对应的文本标签。这段代码将生成一个简单的树状图,展示节点之间的层次关系。
上一篇:js base64.encode
下一篇:js 图片压缩
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站