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

D3.js v4迁移至v7力导向图代码运行异常,寻求修复方案

问题排查

  • 异步请求接口不兼容:D3 v5及以上版本将d3.json等异步请求方法全部改为Promise规范,废弃了原有的回调函数写法,原有代码中的回调逻辑不会执行,是核心故障点。
  • 连线宽度取值错误:代码中设置连线粗细时用了d[2],但helpme.json的links是对象结构,权重字段为value,此处取值为undefined会导致连线宽度异常。
  • 可选优化:当前力导向中心设置为画布的1/3位置,最终渲染的力导向图会整体偏左上,可调整为画布居中位置。

修复后完整代码

<!DOCTYPE html>
<meta charset="utf-8">
<style>

.links line {
  stroke: #999;
  stroke-opacity: 0.6;
}

.nodes circle {
  stroke: #fff;
  stroke-width: 1.5px;
}

text {
  font-family: sans-serif;
  font-size: 10px;
}

</style>
<svg width="500" height="500"></svg>
<script src="https://d3js.org/d3.v7.min.js"></script>

<script>

const svg = d3.select("svg"),
    width = +svg.attr("width"),
    height = +svg.attr("height");

const simulation = d3.forceSimulation()
    .force("link", d3.forceLink().id(function(d) { return d.id; }))
    .force("charge", d3.forceManyBody())
    .force("center", d3.forceCenter(width/2, height / 2)); // 调整为画布中心

// 改为Promise写法适配v7版本
d3.json("helpme.json").then(function(graph) {
  const link = svg.append("g")
      .attr("class", "links")
    .selectAll("line")
    .data(graph.links)
    .enter().append("line")
      // 修正为取value字段值
      .attr("stroke-width", function(d) { return Math.sqrt(d.value)*2; });

  const node = svg.append("g")
      .attr("class", "nodes")
    .selectAll("g")
    .data(graph.nodes)
    .enter().append("g")

  const circles = node.append("circle")
    .attr("r", 6)
    .attr("fill", "olive");

  const drag_handler = d3.drag()
      .on("start", dragstarted)
      .on("drag", dragged)
      .on("end", dragended);

  drag_handler(node);
  
  const lables = node.append("text")
      .text(function(d) {
        return d.id;
      })
      .attr('x', 6)
      .attr('y', 3);

  node.append("title")
      .text(function(d) { return d.id; });

  simulation
      .nodes(graph.nodes)
      .on("tick", ticked);

  simulation.force("link")
      .links(graph.links);

  function ticked() {
    link
        .attr("x1", function(d) { return d.source.x; })
        .attr("y1", function(d) { return d.source.y; })
        .attr("x2", function(d) { return d.target.x; })
        .attr("y2", function(d) { return d.target.y; });

    node
        .attr("transform", function(d) {
          return "translate(" + d.x + "," + d.y + ")";
        })
  }
}).catch(function(error) {
  if (error) throw error;
});

  
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>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 10:45:00