You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

D3.js地理地图中text元素已添加但不显示的原因咨询

D3.js 文本元素添加后不显示的问题排查

问题代码

import { useEffect, useRef } from "react";
import * as d3 from "d3";

import koreaMap from "../../imgs/map.json";

const Map = props => {
  const mapRef = useRef(null);
  const mapContainer = props.mapContainer;

  console.log(koreaMap);
  useEffect(() => {
    const map = d3.select(mapRef.current);

    if (map && mapContainer) {
      const width = mapContainer.getBoundingClientRect().width;
      const height = mapContainer.getBoundingClientRect().height;
      const projection = d3.geoMercator().fitSize([width, height], koreaMap);
      const path = d3.geoPath().projection(projection);

      const kopreaCapital = map
        .attr("width", width)
        .attr("height", height)
        .selectAll("path")
        .data(koreaMap.features)
        .enter()
        .append("g");

      kopreaCapital.append("path").attr("d", path);

      kopreaCapital.append("text").attr("fill", "black").text("hi");
    }
  }, [mapContainer]);

  return <svg ref={mapRef} />;
};

export default Map;

问题原因

  • 未指定文本位置:SVG的<text>元素必须通过x/y或transform属性定义显示坐标,否则默认渲染在(0,0)位置,大概率处于SVG视口外或被地图元素遮挡,导致视觉上不可见(即使DOM结构存在)。
  • 拼写错误隐患:代码中kopreaCapital是拼写错误(应为koreaCapital),虽不影响当前DOM生成,但后续若基于该变量做数据绑定可能引发问题。

修复方案

给文本元素添加位置属性,利用D3的path.centroid(d)方法获取每个地理区域的中心坐标,确保文本显示在对应区域的中心:

kopreaCapital.append("text")
  .attr("fill", "black")
  // 获取区域中心坐标
  .attr("x", d => path.centroid(d)[0])
  .attr("y", d => path.centroid(d)[1])
  // 文本居中对齐
  .attr("text-anchor", "middle")
  .text("hi");

若需要避免文本被路径遮挡,可额外添加样式提升文本层级:

.style("pointer-events", "none")
.style("font-size", "12px")

内容的提问来源于stack exchange,提问作者kang

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 04:07:21