Pause and resume transition

I use setInterval , so transitions occur at a specific interval. Is it possible to make pause work and resume work with setInterval?

Any suggestions / pointers in the right direction would be really helpful.

+8
source share
1 answer

This question was posted when D3 v3 was the last available version. After 5 years, several new methods appeared in D3 v5, such as selection.interrupt() , transition.on("interrupt"...) and local variables , which can make the task simpler and less painful.

So, let's assume a simple cx transition in a circle:

 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> 

The idea is to abort the transition when, for example, a button is pressed:

 selection.interrupt(); 

And then, with a local variable, use the listener for interrupt to get the current position:

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

Finally, when the button is pressed again, we use local.get(this) and simple math to get the remaining duration .

It is also worth noting that this works for linear attenuation; if you have another slowdown such as d3.easeCubic by default, you will need more complex code.

And here is the demo:

 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> 
0
source

All Articles