我在用setInterval
,因此转换会在一定时间间隔后发生。是否可以使用 setInterval 暂停和恢复工作?
任何正确方向的建议/指示都会非常有帮助。
这个问题是在 D3 v3 是最新版本时发布的。 5年后D3 v5有了一些新方法,比如selection.interrupt() https://github.com/d3/d3-transition/blob/master/README.md#selection_interrupt, transition.on("interrupt"...) https://github.com/d3/d3-transition/blob/master/README.md#transition_on and local variables https://github.com/d3/d3-selection/blob/master/README.md#local,这可以使任务变得更简单、更少痛苦。
那么,我们假设一个简单的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>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)