I have a slider that has possible values between 0 to 1 with steps of 0.1
For example if I move the slider at the starting point, the animation will start from (0%), if I move the slider to 0.5 (50%) it means that it will start at 50% of the animation to the end.
My problem is if, for example I select the slider at 50%, the animation starts from 50% but if I want to return it to another percentage of animation, the animation will not be returned to that percentaje selected.
How can I solve that?
This is my code:
d3.select("#visualization").append('svg');
var vis = d3.select("svg").attr("width", 800).attr("height", 150).style("border", "1px solid red");
var rectangle = vis.append("rect").attr("width", 100).attr("height", 70).attr("x", 0).attr("y", 50);
var duration=5000;
function setPercentValue(percentage) {
//rectangle.interrupt();
rectangle.transition()
.duration(duration * (1 - percentage))
.ease(t => d3.easeCubic(percentage + t * (1 - percentage)))
.attr("x", 250)
.attr("width", 100)
.attr("height", 100)
.style("opacity", 0.5)
.attr("fill", "red");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<div id="visualization"></div>
<input type="range" min="0" max="1" step="0.1" oninput="setPercentValue(+event.target.value)">
The animation is still working, that's not the issue. The issue is that once the first animation ends, you're animating the element from its final values to those same final values, and nothing will happen.
The simplest solution is just setting the initial positions/sizes again inside the setPercentValue function:
d3.select("#visualization").append('svg');
var vis = d3.select("svg").attr("width", 800).attr("height", 150).style("border", "1px solid red");
var rectangle = vis.append("rect").attr("width", 100).attr("height", 70).attr("x", 0).attr("y", 50);
var duration = 5000;
function setPercentValue(percentage) {
rectangle.interrupt();
rectangle.attr("width", 100)
.attr("height", 70)
.attr("x", 0)
.attr("y", 50)
.transition()
.duration(duration * (1 - percentage))
.ease(t => d3.easeCubic(percentage + t * (1 - percentage)))
.attr("x", 250)
.attr("width", 100)
.attr("height", 100)
.style("opacity", 0.5)
.attr("fill", "red");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<div id="visualization"></div>
<input type="range" min="0" max="1" step="0.1" oninput="setPercentValue(+event.target.value)">
Of course, one can say if that solution is adequate only knowing what's your goal here, but that's not exactly clear.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With