所以我在 d3 中有一个点保留在转换方法下。当按下模拟时,它会转到某个位置并从该位置返回到原始位置。它处于连续循环状态,因此它所做的就是在相同位置进出。
我想做的是让它像现在一样连续工作,但是当它从 A 移动到 B 时,它不应该从 B 回到 A,它应该再次从 A 开始到 B。基本上是 A 到 B ,A到B连续。这是我正在使用的代码。
dot.transition()
.duration(3000)
.attr("cx", 500)
.attr("cy", 80).on("start", function repeat() {
d3.active(this)
.attr("cx", 70)
.attr("cy", 350)
.transition()
.attr("cx", 500)
.attr("cy", 80)
.transition()
.on("start", repeat);
});
你能帮我解决这个问题吗?提前致谢。
最佳答案
一个简单的重构,使用 on.("end")
而不是 .on("start")
:
const dot = d3.select("circle");
dot.transition()
.duration(3000)
.attr("cx", 250)
.attr("cy", 100).on("end", function repeat() {
d3.select(this)
.attr("cx", 50)
.attr("cy", 50)
.transition()
.duration(3000)
.attr("cx", 250)
.attr("cy", 100)
.on("end", repeat)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<svg>
<circle r="10" cx="50" cy="50"></circle>
</svg>
但我认为,如果您使用 selection.call
(您可以将其与不同的 和 参数一起使用),这会更加优雅和清晰:
const dot = d3.select("circle");
dot.call(transition)
function transition(element) {
element.attr("cx", 50)
.attr("cy", 50)
.transition()
.duration(3000)
.attr("cx", 250)
.attr("cy", 100)
.on("end", function() {
transition(element)
})
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<svg>
<circle r="10" cx="50" cy="50"></circle>
</svg>
顺便说一句,由于 D3 过渡使用 d3.easeCubic 作为默认缓动,因此如果使用线性缓动,可以获得更好的效果(取决于您想要的):
const dot = d3.select("circle");
dot.call(transition)
function transition(element) {
element.attr("cx", 50)
.attr("cy", 50)
.transition()
.duration(3000)
.ease(d3.easeLinear)
.attr("cx", 250)
.attr("cy", 100)
.on("end", function() {
transition(element)
})
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<svg>
<circle r="10" cx="50" cy="50"></circle>
</svg>
关于javascript - 如何在循环中从起始位置进行转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54896416/