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; });
补充说明
- 节点尺寸绑定:若你的节点数据对象没有
width和height属性,需要在创建矩形节点时添加:node.append('rect') .attr('width', 48) .attr('height', 24) .each(function(d) { d.width = 48; d.height = 24; }); - 统一尺寸优化:如果所有矩形节点尺寸一致,可直接将
halfWidth和halfHeight替换为固定值(比如24和12),减少计算开销。
内容的提问来源于stack exchange,提问作者Sri
相关产品推荐
相关产品推荐

