D3.js 基础模块
d3-selection
操作DOM元素d3-scale
实现数据坐标映射d3-path
生成 SVG 路径d3-zoom
添加缩放交互数据结构设计
线路图数据通常采用嵌套格式:
const routes = [ { id: "routeA", points: [ {x: 0, y: 50}, {x: 100, y: 150}, // 更多坐标点 ] } ];
const svg = d3.select("#chart") .append("svg") .attr("width", 800) .attr("height", 600);
const lineGenerator = d3.line() .x(d => d.x) .y(d => d.y) .curve(d3.curveCatmullRom); // 平滑曲线
svg.selectAll(".route") .data(routes) .enter() .append("path") .attr("d", d => lineGenerator(d.points)) .attr("stroke", "#2c7be5") .attr("fill", "none") .attr("stroke-width", 2);
动态渐变效果
为路径添加流动动画:
paths.style("stroke-dasharray", function() { const length = this.getTotalLength(); return `${length} ${length}`; }) .style("stroke-dashoffset", function() { return this.getTotalLength(); }) .transition() .duration(2000) .style("stroke-dashoffset", 0);
交互提示框
通过鼠标事件显示节点信息:
paths.on("mouseover", function(event, d) { d3.select("#tooltip") .html(`线路ID: ${d.id}<br>节点数: ${d.points.length}`) .style("left", event.pageX + "px") .style("top", event.pageY + "px") .classed("visible", true); });
大数据量处理
d3.quadtree
实现空间索引加速渲染渲染优化
// 使用 requestAnimationFrame 分批渲染 function animatePaths() { let start = 0; const batchSize = 100; function update() { const batch = routes.slice(start, start + batchSize); renderBatch(batch); start += batchSize; if (start < routes.length) requestAnimationFrame(update); } requestAnimationFrame(update); }
实时交通监控系统
通过 WebSocket 动态更新线路拥堵状态,颜色编码采用 d3.interpolateReds
网络攻击溯源分析
使用力导向图(Force-Directed Graph)展示攻击路径:
const simulation = d3.forceSimulation() .force("link", d3.forceLink().id(d => d.id)) .force("charge", d3.forceManyBody()) .force("center", d3.forceCenter(width/2, height/2));