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

D3.js等高线显示为黑块求助:参照Observable示例实现失败

修正D3.js等高线显示问题的解决方案

你的代码里有几个关键问题导致只显示黑块,我来一步步帮你修正:

1. SVG未设置宽高

你创建了SVG元素但没有指定它的width和height属性,导致SVG默认尺寸极小,看起来就是个黑块。需要把SVG的尺寸设置为和你的高程数据一致:

var svg = d3.select('#container')
  .append('svg')
  .attr('width', width)
  .attr('height', height);

2. 使用错误的地理投影

d3.geoPath()默认使用的是适用于经纬度的球面投影,但你的等高线坐标是像素坐标(对应数据的width和height),必须用d3.geoIdentity()来适配本地坐标,同时因为D3的SVG坐标系y轴向下,而d3.contours生成的GeoJSON y轴向上,需要添加reflectY(true)翻转:

const path = d3.geoPath()
  .projection(d3.geoIdentity().reflectY(true));

3. 路径样式错误

你只设置了描边,但没有把填充设为none,导致整条路径被填充成黑色,完全覆盖了描边。同时stroke-width设为0.03太细,几乎无法看清,建议适当调大:

const g = svg.append("g")
  .attr("stroke", "black")
  .attr("stroke-width", 0.5)
  .attr("fill", "none");

4. 简化等高线阈值参数

contours.contour()的第二个参数接受单个阈值数值,不需要用数组包裹,直接传数值更清晰:

g.append("path")
  .attr("d", path(contours.contour(data.values, 90)));

修正后的完整代码

var data = {"width": ..., "height":..., "values": ...};
var width = data.width;
var height = data.height;

// 创建带尺寸的SVG
var svg = d3.select('#container')
  .append('svg')
  .attr('width', width)
  .attr('height', height);

// 使用适配本地像素的投影
const path = d3.geoPath()
  .projection(d3.geoIdentity().reflectY(true));

// 创建等高线容器并设置样式
const contours = d3.contours().size([width, height]);
const g = svg.append("g")
  .attr("stroke", "black")
  .attr("stroke-width", 0.5)
  .attr("fill", "none");

// 添加单个等高线路径
g.append("path")
  .attr("d", path(contours.contour(data.values, 90)));

额外提醒:确保你的data.values是长度为width * height的一维数组,顺序为行优先(先遍历x轴从0到width-1,再遍历y轴从0到height-1),这是d3.contours要求的标准数据格式。

内容的提问来源于stack exchange,提问作者D. Cohen

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 18:03:11