我正在使用setInterval
函数,因此过渡效果会在一定时间间隔后发生。是否可能通过setInterval
来实现暂停和恢复功能?
如果您能给出任何方向性的建议或提示,将非常有帮助。
我正在使用setInterval
函数,因此过渡效果会在一定时间间隔后发生。是否可能通过setInterval
来实现暂停和恢复功能?
如果您能给出任何方向性的建议或提示,将非常有帮助。
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
setInterval
。 - Lars Kotthoff.delay
和'on start'处理程序通过d3.active创建重复函数不可以吗?示例 - mtx