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

D3.js力导向图:如何让链接指向矩形节点边框而非中心

解决D3.js力导向图矩形节点的链接端点问题

你当前的代码用固定偏移量(24)来计算链接端点,这种方式只适用于圆形节点。矩形节点的边框位置随连线角度变化——水平方向需偏移半宽,垂直方向需偏移半高,斜向则要取两者的最小比例对应位置。以下是修改后的tick函数:

link.attr('x1', function(d) {
  const dx = d.target.x - d.source.x;
  const dy = d.target.y - d.source.y;
  // 避免除以0,用极小值替代
  const absDx = Math.max(Math.abs(dx), 1e-9);
  const absDy = Math.max(Math.abs(dy), 1e-9);
  // 矩形节点的半宽/半高,若节点尺寸统一可直接写固定值(比如24和12)
  const halfWidth = d.source.width / 2;
  const halfHeight = d.source.height / 2;
  // 计算到达边框的最小比例,确保端点落在矩形边上
  const t = Math.min(halfWidth / absDx, halfHeight / absDy);
  return d.source.x + dx * t;
})
.attr('y1', function(d) {
  const dx = d.target.x - d.source.x;
  const dy = d.target.y - d.source.y;
  const absDx = Math.max(Math.abs(dx), 1e-9);
  const absDy = Math.max(Math.abs(dy), 1e-9);
  const halfWidth = d.source.width / 2;
  const halfHeight = d.source.height / 2;
  const t = Math.min(halfWidth / absDx, halfHeight / absDy);
  return d.source.y + dy * t;
})
.attr('x2', function(d) {
  const dx = d.source.x - d.target.x;
  const dy = d.source.y - d.target.y;
  const absDx = Math.max(Math.abs(dx), 1e-9);
  const absDy = Math.max(Math.abs(dy), 1e-9);
  const halfWidth = d.target.width / 2;
  const halfHeight = d.target.height / 2;
  const t = Math.min(halfWidth / absDx, halfHeight / absDy);
  return d.target.x + dx * t;
})
.attr('y2', function(d) {
  const dx = d.source.x - d.target.x;
  const dy = d.source.y - d.target.y;
  const absDx = Math.max(Math.abs(dx), 1e-9);
  const absDy = Math.max(Math.abs(dy), 1e-9);
  const halfWidth = d.target.width / 2;
  const halfHeight = d.target.height / 2;
  const t = Math.min(halfWidth / absDx, halfHeight / absDy);
  return d.target.y + dy * t;
});

补充说明

  1. 节点尺寸绑定:若你的节点数据对象没有width和height属性,需要在创建矩形节点时添加:
    node.append('rect')
      .attr('width', 48)
      .attr('height', 24)
      .each(function(d) {
        d.width = 48;
        d.height = 24;
      });
    
  2. 统一尺寸优化:如果所有矩形节点尺寸一致,可直接将halfWidth和halfHeight替换为固定值(比如24和12),减少计算开销。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 20:30:49