d3 限制时间轴的缩放级别

Gov*_*tri 5 javascript visualization d3.js

我的代码如下用于缩放时间 X 轴。我想在时间之间设置一个限制应该放大或缩小,即时间的上限和下限。我试图将边界值放在缩放函数中,这是在此d3 图中建议的缩放线程有限的函数。但它不起作用。

var x = d3.time
  .scale()
  .domain([start_date, end_date])
  .range([0, width]);

var zoom = d3.behavior
  .zoom()
  .x(x)
  .on("zoom", zoomed);

svg = d3
  .select("#chart" + k)
  .append("svg:svg")
  .attr("width", width + margin.left + margin.right)
  .attr("height", height + margin.top + margin.bottom)
  .append("svg:g")
  .attr("transform", "translate(" + margin.left + "," + margin.top + ")")
  .call(zoom);

function zoomed() {
  svg.selectAll(".line").remove();

  makeBackground();

  svg.select(".x.axis").call(xAxis);
  d3.select(".x.axis.top").call(xAxisTop);

  svg.select(".x.grid").call(
    make_x_axis()
      .tickSize(-height, 0, 0)
      .tickFormat("")
  );
  svg.selectAll(".circle-path").remove();
  d3.selectAll(".trainTag").remove();
  drawPaths();
  drawCircle(x, y, chartBody, trainData[0]);
}
Run Code Online (Sandbox Code Playgroud)
任何人都有任何其他解决方案来设置下一个和前两个小时的缩放级别。谢谢

spa*_*awn 2

在 d3 v4 中,d3.zoom().scaleExtent 允许限制用户缩放超出给定边界(但可以通过编程方式设置超出)。这些是作为因素给出的,而不是作为时间范围给出的。但您肯定可以使用已知的量表开始时间和结束时间自行计算这些因素:

const minTimeMilli = 20000; // do not allow zooming beyond displaying 20 seconds
const maxTimeMilli = 6.3072e+11; // approx 20 years

const widthMilli = endTime - startTime;

const minScaleFactor = widthMilli / maxTimeMilli;
const maxScaleFactor = widthMilli / minTimeMilli;

const zoom = d3.zoom()
  .scaleExtent([minScaleFactor, maxScaleFactor])
Run Code Online (Sandbox Code Playgroud)