缩放时的 D3js 画笔区域未居中

D3js brush area on zoom not centered

我正在使用 D3js 对条形图进行缩放和刷亮。我正在关注这个例子:https://bl.ocks.org/mbostock/34f08d5e11952a80609169b7917d4172

我在缩放画笔区域时遇到问题。它没有正确居中(大多数时候)。当它不正确居中时,它居中太靠左(见屏幕截图)。

这是刷图缩放的代码

// Zoom
  var zoom = d3.zoom()
    .scaleExtent([.9, 20])
    .translateExtent([[0, 0], [graph.width(), graph.height()]])
    .on('zoom', zoomUpdateChart);

  svg.call(zoom);

  function zoomUpdateChart() {
    if (d3.event.sourceEvent && d3.event.sourceEvent.type == "brush") return;

    // recover the new scale
    var transform = d3.event.transform;
    var zoomLevel = d3.event.transform.k;
    graph._xScale.domain(transform.rescaleX(graph._xScaleZoom).domain());

    resetZoomBtn.attr("opacity", 1)
      .on("click", resetZoom);
    graph.TooltipRemove(tooltip);

    // regenerating the box axis
    axis.remove();
    axis = graph.RenderBoxAxis(g, graph._xScale);
    bars.attr("x", function(d) { return graph._xScale(d.x); })
        .attr("width", barWidth * zoomLevel );

    zoomSection.select(".brush").call(brush.move, graph._xScale.range().map(transform.invertX, transform));
  }

  function resetZoom() {
    svg.transition()
      .duration(750)
      .call(zoom.transform, d3.zoomIdentity)
      .on("end", () => { 
        resetZoomBtn.attr("opacity", 0.2)
          .on("click", null); 
      });
    graph.TooltipRemove(tooltip);
  }

  // Brush
  var brush = d3.brushX()
    .extent([[0, 0], [graph._width, graph._heightZoom]])
    .on("brush", brushed);

  zoomSection.append("g")
    .attr("class", "brush")
    .call(brush)
    .call(brush.move, graph._xScale.range());

  function brushed() {
    if (d3.event.sourceEvent && d3.event.sourceEvent.type == "zoom") return;

    const selection = d3.event.selection || graph._xScaleZoom.range();
    graph._xScale.domain(selection.map(graph._xScaleZoom.invert, graph._xScaleZoom));
    const selectionWidth = selection[1] - selection[0];
    const scale = (selectionWidth / graph._width);
    const zoomLevel = 1 / scale;

    resetZoomBtn.attr("opacity", 1)
      .on("click", resetZoom);
    graph.TooltipRemove(tooltip);

    // regenerating the box axis
    axis.remove();
    axis = graph.RenderBoxAxis(g, graph._xScale);
    bars.attr("x", function(d) { return graph._xScale(d.x) })
        .attr("width", barWidth * zoomLevel)

    svg.call(zoom.transform, d3.zoomIdentity
        .scale(graph._width / selectionWidth)
        .translate(-selection[0], 0));
  }

我自己做了一些研究。问题出在新笔刷位置的设置范围内。

zoomSection.select(".brush").call(brush.move, graph._xScale.range().map(transform.invertX, transform));

设置为[-166.07655066619142, 298.5037864592652]。第一个索引应该是正数,但计算不正确。我已经查看了几个小时,但没有找到解决方案。

更多详细信息:该页面加载了更多不同类型的图表,例如面积图和折线图。

经过大量搜索,我找到了答案。我没有在缩放时设置 .extent()。正确的代码是:

var zoom = d3.zoom()
    .scaleExtent([0.9, 20])
    .extent([[0, 0], [graph._width, graph._height]])
    .translateExtent([[0, 0], [graph._width, graph._height]])
    .on('zoom', zoomUpdateChart);