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

D3.js使用geoProjection放大地图出现黑色块无法正常显示问题

问题根因

  • 你自定义的d3.geoProjection未做坐标适配:地理经纬度的数值范围和#mapsvg的像素尺寸完全不匹配,生成的路径要么超出可视区域,要么计算异常直接填充整个svg画布,形成黑色遮挡块。
  • 未配置投影的中心、缩放、平移参数,中国区域默认不在标准投影的初始可视范围内。
  • 未调用投影的适配方法将GeoJSON数据自动匹配到你的svg画布尺寸。

修正代码

方案1:使用标准墨卡托投影适配中国地图

fetch("./data/chinaMapDataAll.json")
  .then(d1 => d1.json())
  .then(d1 => {
    const mapsvg = d3.select("#mapsvg")
    const mapwidth = Number(mapsvg.attr("width"))
    const mapheight = Number(mapsvg.attr("height"))
    // 初始化墨卡托投影,自动适配画布尺寸
    const mapProjection = d3.geoMercator()
      .fitSize([mapwidth, mapheight], d1) // 自动把geojson适配到svg尺寸
      // 如果需要额外放大,可以再加scale调整,例如.scale(1.2)就是放大1.2倍
    const mapPath = d3.geoPath(mapProjection);                           
    mapsvg.selectAll("path")
      .data(d1.features)
      .join("path")
      .attr("d", d => mapPath(d))      
      .attr("fill", (d,i) => scacolor[i])
      .attr("stroke", "#fff") // 可选加省份边框,避免区块粘连
  })

方案2:自定义投影调整

如果需要自定义投影逻辑,也要加上缩放平移适配,参考代码:

const mapProjection = d3.geoProjection(function(x,y){
  // 这里可以写你的自定义转换逻辑,最终返回适配画布的像素坐标
  // 示例基础转换:调整坐标原点+适配缩放
  const scale = 800 // 根据你的画布尺寸调整
  return [(x - 104) * scale + mapwidth/2, (36 - y) * scale + mapheight/2];
}).fitSize([mapwidth, mapheight], d1)

额外验证点

  • 确认scacolor数组的长度和GeoJSON的features长度一致,避免fill取到undefined值,导致路径被填充为默认黑色。
  • 确认#mapsvg元素没有设置额外的黑色背景样式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 20:24:02