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

D3 v6仅对Y轴实现缩放平移时图层矩形高度计算异常求助

问题根因分析

核心错误出在updateLayers函数的矩形高度计算逻辑:经过缩放平移变换后的Y轴比例尺,domain和range均发生偏移,不再是从0开始的线性映射,你直接将数值差d.to - d.from传入Y比例尺计算高度,会引入额外偏移误差,该误差正好等于Y轴0m刻度的偏移距离,和你描述的异常特征完全匹配。

修复方案
  • 修改updateLayers中的高度计算逻辑,不要直接传入数值差给比例尺,而是分别计算上下边界的像素坐标后取差值,得到正确高度
  • 可同步简化Y坐标的计算逻辑,无需判断索引,直接取d.from的映射值即可,避免索引依赖的潜在错误

修改后的updateLayers核心代码如下:

const updateLayers = (data: LAYER_COMPONENT_TYPE[], yScale) => {
  const layerFill = getLayerFill(data);

  const rects = layerGroup.selectAll('rect').data(data);

  rects.exit().remove();

  const newLayers = rects
    .enter()
    .append('rect')
    .attr('x', 10)
    .style('opacity', 0.5)
    .attr('width', 300)
    .style('stroke', '#101010')
    .style('stroke-width', '1px');

  newLayers
    .merge(rects)
    .style('fill', (d: LAYER_COMPONENT_TYPE) => {
      if (!layerFill[`${d.fgdc_texture}.${d.from}`].url) {
        return layerFill[`${d.fgdc_texture}.${d.from}`];
      }
      svg.call(layerFill[`${d.fgdc_texture}.${d.from}`]);
      return layerFill[`${d.fgdc_texture}.${d.from}`].url();
    })
    // 简化Y坐标计算,无需判断索引
    .attr('y', (d: LAYER_COMPONENT_TYPE) => yScale(d.from))
    // 修正高度计算逻辑
    .attr('height', (d: LAYER_COMPONENT_TYPE) => yScale(d.to) - yScale(d.from));
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 16:18:00