【问题标题】:Prevent line path from overflowing graph in svg using D3使用 D3 防止线条路径在 svg 中溢出图形
【发布时间】:2017-07-26 21:22:52
【问题描述】:

我正在关注这个例子:https://bl.ocks.org/mbostock/34f08d5e11952a80609169b7917d4172

但是当我将focus 中的area 替换为line 时,它就无法正常工作了。缩放、平移和使用画笔使line 路径溢出图形的左右边界,如下所示:

这只是主图表的屏幕截图,即focus。它不包括context 图表

area 元素不会像示例代码中那样出现此问题。我想我没有在brushed()zoomed() 中进行适当的更新。我应该怎么做才能防止溢出?

以下是我为使用line所做的更改:

原码:

var area = d3.area()
  .curve(d3.curveMonotoneX)
  .x(function(d) { return x(d.date); })
  .y0(height)
  .y1(function(d) { return y(d.price); });

[...]

focus.append("path")
  .datum(data)
  .attr("class", "area")
  .attr("d", area);

[...]

function brushed() {
  [...]
  focus.select(".area").attr("d", area);
  [...]
}

function zoomed() {
  [...]
  focus.select(".area").attr("d", area);
  [...]
}

我的代码:

var line = d3.line()
    .x(function(d) { return x(d.date); })
    .y(function(d) { return y(d.price); });

[...]

focus.append("path")
      .datum(data)
      .attr("fill", "none")
      .attr("stroke", "steelblue")
      .attr("stroke-linejoin", "round")
      .attr("stroke-linecap", "round")
      .attr("stroke-width", 1.5)
      .attr("class", "line")
      .attr("d", line);

[...]

function brushed() {
  [...]
  focus.select(".line").attr("d", line);
  [...]
}

function zoomed() {
  [...]
  focus.select(".line").attr("d", line);
  [...]
}

谢谢。

【问题讨论】:

标签: javascript css d3.js svg


【解决方案1】:

看起来您缺少剪辑路径,即在图表域之外隐藏数据。这一切都在您使用的示例中。

CSS:

.area {
    fill: steelblue;
    clip-path: url(#clip);
}

JS:

svg.append("defs").append("clipPath")
    .attr("id", "clip")
    .append("rect")
    .attr("width", width)
    .attr("height", height);

【讨论】:

    猜你喜欢
    • 2012-10-06
    • 1970-01-01
    • 1970-01-01
    • 2014-01-20
    • 1970-01-01
    • 2018-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多