【问题标题】:Pausing and resuming a transition暂停和恢复过渡
【发布时间】:2014-05-27 17:09:09
【问题描述】:

我正在使用setInterval,所以转换发生在一定的时间间隔之后。是否可以暂停和恢复使用 setInterval?

任何正确方向的建议/指示都会非常有帮助。

【问题讨论】:

  • 你见过this article吗?
  • 是的,我确实看过这篇文章,但我不确定它如何与指定了特定时间间隔的 setInterval 函数一起使用。我在某个时间间隔后开始转换,一旦可视化完成,我就使用了 clearInterval。甚至可以让暂停和恢复功能与 setInterval 一起使用吗?还是需要我更改实施?
  • 原则上你应该可以毫无问题地使用setInterval
  • 你能告诉你为什么需要使用间隔吗? .delay 和 'on start' 处理程序是否会使用 d3.active 创建重复函数? example

标签: javascript d3.js transition


【解决方案1】:

这个问题是在 D3 v3 是可用的最新版本时发布的。 5 年后,D3 v5 有了一些新的方法,比如selection.interrupt()transition.on("interrupt"...)local variables,它们可以让任务更简单,更不痛苦。

所以,让我们假设一个简单的cx 在一个圆上转换:

const svg = d3.select("svg");
const circle = svg.append("circle")
  .attr("r", 15)
  .attr("cx", 20)
  .attr("cy", 50)
  .style("fill", "teal")
  .style("stroke", "black");
circle.transition()
  .duration(10000)
  .ease(d3.easeLinear)
  .attr("cx", 580);
svg {
  background-color: wheat;
  display: block;
};
<script src="https://d3js.org/d3.v5.min.js"></script>
<svg width="600" height="100"></svg>

这个想法是在按下按钮时中断转换:

selection.interrupt();

然后,通过一个局部变量,使用interrupt 的监听器来获取当前位置:

.on("interrupt", function() {
    local.set(this, +d3.select(this).attr("cx"))
}); 

最后,当再次按下按钮时,我们使用local.get(this) 和一个简单的数学运算得到剩余的duration

还值得一提的是,这适用于线性缓动;如果你有另一个缓动,比如默认的d3.easeCubic,你需要更复杂的代码。

这里是演示:

const svg = d3.select("svg");
const local = d3.local();
const button = d3.select("button");
const circle = svg.append("circle")
  .attr("r", 15)
  .attr("cx", 20)
  .attr("cy", 50)
  .style("fill", "teal")
  .style("stroke", "black");
circle.transition()
  .duration(10000)
  .ease(d3.easeLinear)
  .attr("cx", 580)
  .on("interrupt", function() {
    local.set(this, +d3.select(this).attr("cx"))
  });
button.on("click", function() {
  if (d3.active(circle.node())) {
    circle.interrupt();
    this.textContent = "Resume";
  } else {
    circle.transition()
      .ease(d3.easeLinear)
      .duration(function() {
        return 10000 * (560 - local.get(this)) / 560;
      })
      .attr("cx", 580)
    this.textContent = "Stop";
  }
})
svg {
  background-color: wheat;
  display: block;
};
<script src="https://d3js.org/d3.v5.min.js"></script>
<button>Stop</button>
<svg width="600" height="100"></svg>

【讨论】:

  • 你很好,你能告诉我为什么cx是560而不是580吗?
  • @yavg 这可能是一个错字。
猜你喜欢
  • 2013-03-28
  • 2019-06-28
  • 2013-07-19
  • 2015-07-28
  • 2014-12-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多