[英]JS smooth transition between two value change
I have this variables changing constantly, from 0 to 100 this coming from an exernal SDK like this for example:我有这个变量不断变化,从 0 到 100 这来自这样的外部 SDK,例如:
window.addEventListener({
variable = 0;
})
Now when this variable change and goes to another value it's too sharp for me and I want to make this exponential, for example, not 0 => 100 directly, but I want to sample the value of variable every x millisecond e make a smooth transition between the two value with the intermediate value现在,当这个变量改变并变为另一个值时,它对我来说太尖锐了,我想使这个指数,例如,不是 0 => 100 直接,但我想每 x 毫秒采样一次变量的值 e 平滑过渡两个值与中间值之间
example: 0 => 20 => 40 => 60 => 80 => 100例如:0 => 20 => 40 => 60 => 80 => 100
how can I do?我能怎么做?
This should do the trick:这应该可以解决问题:
var animationDuration = 500; //in miliseconds
var startValue = 0;
var endValue = 100;
function animateNextFrame(currentTime) {
if (!startTime) startTime = currentTime;
var elapsedTime = currentTime - startTime;
if (elapsedTime < animationDuration) {
currentValue = Math.floor((elapsedTime / animationDuration) * (endValue - startValue));
//set your field value to currentValue here with something like document.getElemenById...
//call the next animation frame
window.requestAnimationFrame(animateNextFrame);
} else {
//set your field value to endValue here with something like document.getElemenById...
}
}
//trigger the number animation
window.requestAnimationFrame(animateNextFrame);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.