数小时以来,我一直在尝试找到纯JavaScript轻松实现,但找不到任何实现。那些接近的没有任何意义。我所能找到的只是一堆没有实现的缓动函数。
例如,如下功能:
function linear(time, begin, change, duration) {
return change * time / duration + begin;
}
function easeInQuad(t) {
return t*t
},
function easeOutQuad(t) {
return t*(2-t)
},
困扰我的一件事是fps在哪里播放?它与持续时间直接相关。我还没有提到它。
如何在以下动画中实现上述缓动功能?
var box = document.getElementById("box");
var fps = 60;
var duration = 2; // seconds
var start = 0; // pixel
var finish = window.innerWidth - box.clientWidth;
var distance = finish - start;
var increment = distance / (duration * fps);
var position = start;
function move() {
position += increment;
if (position >= finish) {
clearInterval(handler);
box.style.left = finish + "px";
return;
}
box.style.left = position + "px";
}
var handler = setInterval(move, 1000 / fps);
body {
background: gainsboro;
}
#box {
width: 100px;
height: 100px;
background: white;
box-shadow: 1px 1px 1px rgba(0, 0, 0, .2);
position: absolute;
left: 0;
}
<div id="box"></div>
You could use a
time
variable and increment it for every frame and use the easing functions for the right position with the values you already have.