You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用D3.js从本地外部JSON加载圆形并添加居中数字标签

解决方案

1. 从本地外部JSON文件获取数据

步骤:

  • 创建本地JSON文件(命名为circles.json),将原内置数据存入:
[{
    "x": 68,
    "y": 61,
    "radius": 20,
    "color": "green",
    "label": "0"
}, {
    "x": 361,
    "y": 60,
    "radius": 20,
    "color": "green",
    "label": "1"
}, {
    "x": 360,
    "y": 311,
    "radius": 20,
    "color": "green",
    "label": "2"
}, {
    "x": 65,
    "y": 310,
    "radius": 20,
    "color": "green",
    "label": "3"
}, {
    "x": 112,
    "y": 28,
    "radius": 20,
    "color": "green",
    "label": "4"
}]
  • 使用D3的d3.json()方法异步加载文件,所有绘图逻辑需放在回调函数内(避免异步加载导致的数据未就绪问题):
    注意:本地直接打开HTML文件会触发浏览器跨域限制,需通过本地服务器运行,比如执行python -m http.server(Python 3)后访问http://localhost:8000

2. 添加圆形中心的白色数字标签

在绘制完圆形后,绑定相同数据创建text元素,通过文本对齐属性实现标签居中显示。


完整代码

script.js

d3.json("circles.json", function(error, jsonCircles) {
  if (error) throw error;

  var svgContainer = d3.select("body")
    .append("svg")
    .attr("width", 1000)
    .attr("height", 1000);

  // 绘制圆形
  var circles = svgContainer.selectAll("circle")
    .data(jsonCircles)
    .enter()
    .append("circle");

  circles.attr("cx", function(d) { return d.x; })
    .attr("cy", function(d) { return d.y; })
    .attr("r", function(d) { return d.radius; })
    .style("fill", function(d) { return d.color; });

  // 添加中心白色标签
  svgContainer.selectAll("text")
    .data(jsonCircles)
    .enter()
    .append("text")
    .text(function(d) { return d.label; })
    .attr("x", function(d) { return d.x; })
    .attr("y", function(d) { return d.y; })
    .style("fill", "white")
    .style("text-anchor", "middle") // 水平居中
    .style("dominant-baseline", "middle") // 垂直居中
    .style("font-size", "14px"); // 可根据圆形半径调整字体大小
});

HTML(无需修改)

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title> Three Little Circles (Using JSON)</title>
</head>

<body>
  <script src="https://d3js.org/d3.v3.min.js" charset="utf-8"></script>
  <script src="./script.js"></script>
</body>

</html>

内容的提问来源于stack exchange,提问作者Paul

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 17:42:48