D3:缩放不会重置比例

时间:2018-12-17 14:12:29

标签: javascript reactjs typescript d3.js

我有一个简单的图表,其中包含一些模拟的实时数据。您可以打开和关闭图形。关闭绘图后,您可以放大和缩小。

https://codesandbox.io/s/wqyz1q3o45

问题出在这里

  1. 等待一段时间在屏幕上显示一些数据
  2. 单击“切换”以停止绘制新数据
  3. 放大(鼠标滚轮或双击)并缩小
  4. 单击“切换”以再次开始绘制

您可以看到该行从左侧被占用。那是因为秤没有重置。

这是"dd MMM yyyy HH:mm"方法

render

还有public render(data: ISample[]) { this.xScale.domain(extent(data, d => d.timestamp) as [number, number]); this.yScale.domain(extent(data, d => d.value) as [number, number]); this.xAxisGroup.call(this.xAxis as any); this.yAxisGroup.call(this.yAxis as any); this.xGridGroup.call(this.xGrid as any); this.yGridGroup.call(this.yGrid as any); this.lineGroup.datum(data).attr("d", this.line); } 方法

zoom

如果您在public zoom = () => { const newXScale = event.transform.rescaleX(this.xScale); const newYScale = event.transform.rescaleY(this.yScale); this.xAxisGroup.call(this.xAxis.scale(newXScale)); this.yAxisGroup.call(this.yAxis.scale(newYScale)); this.xGridGroup.call(this.xGrid.scale(newXScale)); this.yGridGroup.call(this.yGrid.scale(newYScale)); this.line.x(d => newXScale(d.timestamp)).y(d => newYScale(d.value)); this.lineGroup.attr("d", this.line as any); }; 方法中使用以下代码,或者对相应的行进行注释/取消注释,则它会起作用。

render

您可以单击“切换”并根据需要进行放大/缩小。

为什么必须使用this.xAxisGroup.call(this.xAxis.scale(this.xScale)); this.yAxisGroup.call(this.yAxis.scale(this.yScale)); this.xGridGroup.call(this.xGrid.scale(this.xScale)); this.yGridGroup.call(this.yGrid.scale(this.yScale)); this.line.x(d => this.xScale(d.timestamp)).y(d => this.yScale(d.value)); 方法重设比例?尤其像

render

那永远不会改变。它应该始终是相同的。我以为再次缩小会将该比例重置为初始值。

谢谢您的帮助!

1 个答案:

答案 0 :(得分:0)

更改chart.ts渲染功能

  public render(data: ISample[]) {
    this.xScale.domain(extent(data, d => d.timestamp) as [number, number]);
    this.yScale.domain(extent(data, d => d.value) as [number, number]);

    // this.xAxisGroup.call(this.xAxis as any);
    this.xAxisGroup.call(this.xAxis.scale(this.xScale));

    // this.yAxisGroup.call(this.yAxis as any);
    this.yAxisGroup.call(this.yAxis.scale(this.yScale));

    // this.xGridGroup.call(this.xGrid as any);
    // this.yGridGroup.call(this.yGrid as any);
    this.xGridGroup.call(this.xGrid.scale(this.xScale));
    this.yGridGroup.call(this.yGrid.scale(this.yScale));

    this.line.x(d => this.xScale(d.timestamp)).y(d => this.yScale(d.value));

    this.lineGroup.datum(data).attr("d", this.line);
  }