请求将D3.js多节点多链接旧版本代码适配至7.8.5版本
D3.js v3.5.17 转 v7.8.5 多节点多链接代码适配方案
核心差异修改点
- 力导向布局:
d3.layout.force()替换为d3.forceSimulation(),所有力配置通过.force()方法添加 - 链接力:v3的
force.links(links)改为 v7的d3.forceLink(links),需通过.id()指定节点唯一标识(若数据用索引关联则可省略) - 拖拽功能:
force.drag()替换为d3.drag(),并绑定拖拽生命周期事件 - 事件绑定:
force.on("tick", callback)写法保留,但绑定对象变为simulation
适配后的完整代码示例
// 示例多节点多链接数据 const nodes = [ { id: "节点1" }, { id: "节点2" }, { id: "节点3" }, { id: "节点4" }, { id: "节点5" } ]; const links = [ { source: "节点1", target: "节点2" }, { source: "节点1", target: "节点3" }, { source: "节点2", target: "节点4" }, { source: "节点3", target: "节点4" }, { source: "节点4", target: "节点5" } ]; // SVG容器初始化 const width = 800; const height = 600; const svg = d3.select("body") .append("svg") .attr("width", width) .attr("height", height); // 创建力模拟实例 const simulation = d3.forceSimulation(nodes) // 链接力:设置链接距离、指定节点id关联字段 .force("link", d3.forceLink(links).id(d => d.id).distance(120)) // 电荷斥力:控制节点间排斥强度 .force("charge", d3.forceManyBody().strength(-400)) // 中心力:将整体布局居中 .force("center", d3.forceCenter(width / 2, height / 2)); // 渲染链接线条 const linkGroup = svg.append("g") .selectAll("line") .data(links) .enter() .append("line") .attr("stroke", "#ccc") .attr("stroke-width", 2); // 渲染节点 const nodeGroup = svg.append("g") .selectAll("circle") .data(nodes) .enter() .append("circle") .attr("r", 15) .attr("fill", "#4285F4") // 绑定拖拽交互 .call(d3.drag() .on("start", dragStart) .on("drag", dragMove) .on("end", dragEnd)); // 渲染节点标签 const labelGroup = svg.append("g") .selectAll("text") .data(nodes) .enter() .append("text") .text(d => d.id) .attr("font-size", 14) .attr("fill", "#333") .attr("dx", 20) .attr("dy", 5); // Tick事件:实时更新元素位置 simulation.on("tick", () => { linkGroup .attr("x1", d => d.source.x) .attr("y1", d => d.source.y) .attr("x2", d => d.target.x) .attr("y2", d => d.target.y); nodeGroup .attr("cx", d => d.x) .attr("cy", d => d.y); labelGroup .attr("x", d => d.x) .attr("y", d => d.y); }); // 拖拽事件处理函数 function dragStart(event, d) { if (!event.active) simulation.alphaTarget(0.3).restart(); // 固定拖拽起始位置 d.fx = d.x; d.fy = d.y; } function dragMove(event, d) { // 更新拖拽位置 d.fx = event.x; d.fy = event.y; } function dragEnd(event, d) { if (!event.active) simulation.alphaTarget(0); // 取消固定,让节点回归力模拟 d.fx = null; d.fy = null; }
额外适配说明
- 如果原v3代码中链接数据的
source/target是节点数组索引而非id,需移除.id(d => d.id)配置 - 若需自定义力行为(如碰撞检测),可添加
.force("collision", d3.forceCollide().radius(20)) - 样式、尺寸等可根据原示例需求调整
内容的提问来源于stack exchange,提问作者Cédric
相关产品推荐
相关产品推荐

