核心代码结构:
const linkGenerator = d3.linkVertical() .x(d => d.x) .y(d => d.y); d3.selectAll('.link') .data(root.links()) .join('path') .attr('d', linkGenerator) .attr('fill', 'none') .attr('stroke', '#7b8ca9') .attr('stroke-width', 1.5) .attr('stroke-opacity', 0.6);
线型选择:
d3.linkVertical()
:垂直方向曲线(默认贝塞尔曲线)d3.linkHorizontal()
:水平方向曲线d3.linkRadial()
:径向树布局视觉优化技巧:
.attr('stroke-dasharray', '3 2') // 虚线样式 .attr('marker-end', 'url(#arrow)') // 添加箭头
// 路径插值动画 .transition() .duration(800) .attrTween('d', function(d) { const interpolate = d3.interpolate(this._current, d); return t => { this._current = interpolate(t); return linkGenerator(this._current); }; });
// 根据层级设置不同颜色 .attr('stroke', d => { const depth = d.source.depth; return depth === 0 ? '#4a90e2' : depth === 1 ? '#50e3c2' : '#b8e986'; });
// 鼠标悬停效果 .on('mouseover', function(event, d) { d3.select(this) .attr('stroke-width', 3) .raise(); }) .on('mouseout', function() { d3.select(this) .attr('stroke-width', 1.5); });
渲染优化:
path
替代line
元素(减少DOM节点)shape-rendering: geometricPrecision;
大数据处理:
// 使用简化算法 .attr('d', d3.linkVertical().curve(d3.curveStepAfter))
stroke-width
至2px以上pointer-events: stroke;
提升小尺寸连线点击精度