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

不使用viewBox实现D3.js响应式图表时双线无法渲染问题求助

问题根因

  • 选择器无区分度:两次创建轴线都用selectAll('line')匹配所有line元素,单条数据绑定下D3只会复用已存在的line元素,不会生成第二条线
  • 语法不兼容:你用的是D3 v5版本,.join()方法是D3 v6才新增的API,低版本下执行无效
  • 冗余操作&变量重名:第一根轴线的代码里join('line').append('line')会生成嵌套的无效line元素,同时同一作用域重复声明axis变量也属于不规范写法

修正后代码

JavaScript

function myResponsiveChart(container, props) {
  const { width, height } = props;

  let svg = container.selectAll('svg').data([null]);
  svg = svg.enter().append('svg').merge(svg)
    .attr('width', width)
    .attr('height', height);

  const rect = svg.selectAll('rect').data([null]);
  rect.enter().append('rect').merge(rect)
    .attr('width', width)
    .attr('height', height)
    .attr('rx', 100);

  const fontSize = 16,
    hPix = height/6,
    margin = { top: hPix/2, bottom: hPix/2, left: hPix/10, right: hPix/2 };

  // DELTA轴线:通过类名区分选择器,避免和其他line冲突
  const deltaAxis = svg.selectAll('line.diff_axis.delta').data([null]);
  deltaAxis.enter().append('line')
    .attr('class', 'diff_axis delta')
    .merge(deltaAxis)
    .attr("x1", margin.left)
    .attr("x2", width)
    .attr("y1", margin.top)
    .attr("y2", margin.top);

  // ABSOLUTE轴线:单独的选择器匹配
  const absAxis = svg.selectAll('line.diff_axis.abs').data([null]);
  absAxis.enter().append('line')
    .attr("class", "diff_axis abs")
    .attr("id", "abs")
    .merge(absAxis)
    .attr("x1", margin.left)
    .attr("x2", width)
    .attr("y1", margin.top + hPix)
    .attr("y2", margin.top + hPix);
}

function render() {
  myResponsiveChart(d3.select('body'), {
    width: document.body.clientWidth,
    height: document.body.clientHeight
  });
}

render();
window.addEventListener('resize', render);

CSS

body {
  position: fixed;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  margin: 0;
  padding: 0;
}

.diff_axis {
  stroke: red;
  stroke-width: 6;
}

HTML

<script src="https://d3js.org/d3.v5.min.js"></script>

内容的提问来源于stack exchange,提问作者Barnabás Várszegi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 20:06:04