当update
承诺解决时,我试图通过调用transition.end()
函数来链接转换。以下代码段位于此update
函数中。可以在https://jsfiddle.net/fmgreenberg/1npLeguh/10/上找到完整的示例(该摘要是其中的一部分)。
let t = d3
.transition()
.duration(3000)
.end()
.then(() => update(newData));
问题在于过渡几乎是瞬时发生的,然后可视化文件在那里呆了约3秒钟,直到再次调用更新。为什么是这样?如果我注释掉代码段的最后两行,则过渡过程将花费预期的3秒钟。 (当然,自从我删除了循环之后,在这种情况下只有一个过渡。)
答案 0 :(得分:4)
与其命名过渡实例,不如在过渡选择本身中使用promise:
d3.select("#figure")
.selectAll("circle")
.data(newData, d => d)
.transition()
.duration(3000)
.attr("cx", (_, i) =>
i < N ? (i + 1) * (2 * r + s) : 300 - (i - N + 1) * (2 * r + s)
)
.end()
.then(() => update(newData));
这是更新的JSFiddle:https://jsfiddle.net/k9gf8ybL/
以及相应的S.O.片段:
let N = 5;
let r = 5;
let s = 2;
let data = d3.range(2 * N);
d3.select("#figure")
.selectAll("circle")
.data(data)
.enter()
.append("circle")
.attr("cx", (_, i) =>
i < N ? (i + 1) * (2 * r + s) : 300 - (i - N + 1) * (2 * r + s)
)
.attr("cy", 26)
.attr("r", r)
.attr("stroke", "blue")
.attr("fill", d => (d < N ? "white" : "black"));
update(data);
function update(data) {
let I = data.slice(0, N);
let J = data.slice(N, 2 * N);
let i = randInt(N);
let x = I[i];
let j = randInt(N);
let y = J[j];
let newData = [
...I.slice(0, i),
...I.slice(i + 1),
y,
...J.slice(0, j),
...J.slice(j + 1),
x
];
d3.select("#figure")
.selectAll("circle")
.data(newData, d => d)
.transition()
.duration(3000)
.attr("cx", (_, i) =>
i < N ? (i + 1) * (2 * r + s) : 300 - (i - N + 1) * (2 * r + s)
)
.end()
.then(() => update(newData));
}
function randInt(n) {
return Math.floor(Math.random() * n);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.9.0/d3.min.js"></script>
<svg id="figure" viewBox="0 0 300 50" style="background-color: papayawhip; border-radius: 1rem" xmlns="http://www.w3.org/2000/svg"></svg>
但是,如果出于任何原因仍要使用命名转换实例,则只需使用更常见的on("end"...)
方法而不是end()
Promise:
let t = d3
.transition()
.duration(3000)
.on("end", () => {
update(newData)
});
然后:
selection.transition(t)
//etc...
这是采用这种方法的JSFiddle:https://jsfiddle.net/8od3vkc1/