我有使用 d3.js 制作的旋转轮。
我希望轮子无限旋转或达到给定的计时器值。
在
spin()
下调用 setTimeout
函数时,轮子确实会无限旋转,但会以降低的速度停止并缓慢重新启动。不过我想保持上一轮旋转的速度。
function spin(d){
$('#spin').on("click", null);
if(oldpick.length == data.length){
console.log("done");
$('#spin').on("click", null);
return;
}
var ps = 360/data.length,
pieslice = Math.round(1440/data.length),
rng = Math.floor((Math.random() * 1440) + 360);
rotation = (Math.round(rng / ps) * ps);
const offsetToTop = Math.ceil(360/ps/4) - 1;
picked = Math.round(data.length - (rotation % 360)/ps) - offsetToTop;
if(picked >= data.length){
picked = picked % data.length;
}else if(picked < 0){
picked = 0;
}
if(oldpick.indexOf(picked) !== -1){
d3.select(this).call(spin);
return;
} else {
oldpick.push(picked);
}
rotation += 90 - Math.round(ps/1);
vis.transition()
.duration(1000)
.attrTween("transform", rotTween)
.each("end", function(){
console.log(picked);
oldrotation = rotation;
alert(data[picked].xp);
});
}
function rotTween(to) {
var i = d3.interpolate(oldrotation % 360, rotation);
return function(t) {
return "rotate(" + i(t) + ")";
};
}
请参考codepen
d3 过渡的默认 ease 是“慢进慢出”,它会产生您所描述的“以降低的速度停止并缓慢重新启动”的效果。听起来您想要一个“线性”过渡,始终使用相同的速度。要做到这一点,请使用:
vis.transition()
.ease("linear")
.duration(1000)
.attrTween("transform", rotTween)
.each("end", function(){
console.log(picked);
oldrotation = rotation;
alert(data[picked].xp);
});
注意,您使用的是非常旧的版本
d3
。对于更现代的版本,对 .ease
的调用会有所不同。我的答案是针对您正在使用的版本(v3)。