画笔和缩放d3

时间:2018-10-10 16:28:29

标签: javascript d3.js

我正在遵循本指南:https://bl.ocks.org/mbostock/34f08d5e11952a80609169b7917d4172

您能解释一下这一行吗?谢谢

x.domain(s.map(x2.invert, x2));

1 个答案:

答案 0 :(得分:1)

对于上下文,这来自一些实现图表刷图的代码:

function brushed() {
  if (d3.event.sourceEvent && d3.event.sourceEvent.type === "zoom") return; // ignore brush-by-zoom
  var s = d3.event.selection || x2.range();
  x.domain(s.map(x2.invert, x2));
  focus.select(".area").attr("d", area);
  focus.select(".axis--x").call(xAxis);
  svg.select(".zoom").call(zoom.transform, d3.zoomIdentity
      .scale(width / (s[1] - s[0]))
      .translate(-s[0], 0));
}

我们已经将xx2初始化为两个时标:

var x = d3.scaleTime().range([0, width]),
x2 = d3.scaleTime().range([0, width])

s初始化为

var s = d3.event.selection || x2.range();

(其中d3.event是刷牙事件)

x.domain(s.map(x2.invert, x2));

通过在数组x中的每个项目上运行x2.invert,将s作为x2的值来设置this缩放域。实际上,这意味着您正在跑步

x.domain( x2.invert( s[0] ), x2.invert( s[1] ) );

因为s中只有两个值,并且this上下文不会影响invert函数。在可视化方面,这是通过将底部图表中选择框边缘的像素值转换为大图表上的日期来设置大图表所覆盖的时间范围。

简要概述整个功能:

function brushed() {
  if (d3.event.sourceEvent && d3.event.sourceEvent.type === "zoom") return; // ignore brush-by-zoom
  // get the edges of the selection box or use the maximum values (in x2.range)
  var s = d3.event.selection || x2.range();
  // convert those pixel values into dates, and set the x scale domain to those values
  x.domain(s.map(x2.invert, x2));
  // redraw the top graph contents to show only the area within the x domain
  focus.select(".area").attr("d", area);
  // redraw the top graph's x axis with the updated x scale domain
  focus.select(".axis--x").call(xAxis);
  // zoom the overlay of the top graph to reflect the new x domain
  // so that any zoom operations will scale correctly
  svg.select(".zoom").call(zoom.transform, d3.zoomIdentity
      .scale(width / (s[1] - s[0]))
      .translate(-s[0], 0));
}