求带国家名称标签层的D3 Globe(含Globe-gl)实现示例
D3 Globe 添加国家名称标签实现指引
搞定国家中心点数据
要么用自带中心坐标的GeoJSON/TopoJSON,要么用d3.geoCentroid计算每个国家的地理中心:countries.features.forEach(country => { country.centroid = d3.geoCentroid(country); });给标签单独建容器
在SVG里新增一个<g>元素放置标签,确保层级在地球图形上方,避免被遮挡:const labelGroup = svg.append("g").attr("class", "country-labels");渲染标签并同步缩放
将中心点数据绑定到文本元素,通过投影转换为屏幕坐标,同时让字体大小随地球缩放比例动态调整:// 初始化标签 const labels = labelGroup.selectAll("text") .data(countries.features) .join("text") .attr("class", "country-label") .text(d => d.properties.name) .attr("text-anchor", "middle") .style("font-size", `${12 / projection.scale() * 150}px`); // 更新标签位置与大小的函数 function updateLabels() { labels .attr("x", d => projection(d.centroid)[0]) .attr("y", d => projection(d.centroid)[1]) .style("font-size", `${12 / projection.scale() * 150}px`) // 隐藏地球背面不可见的标签 .style("opacity", d => projection(d.centroid) ? 1 : 0); }绑定到交互逻辑
在地球拖拽、旋转、缩放的事件回调里调用updateLabels(),保证标签与地球同步变化:// 拖拽交互示例 d3.drag() .on("drag", () => { projection.rotate([d3.event.x, -d3.event.y]); path.attr("d", pathGenerator); updateLabels(); // 同步更新标签 })(svg);
内容的提问来源于stack exchange,提问作者Alexander Huber
相关产品推荐
相关产品推荐

