简体   繁体   English

JavaScript动画轻松

[英]JavaScript animation with easing

I'm trying to build a slider module with JavaScript. 我正在尝试使用JavaScript构建滑块模块。 Everything works, but the animation is linear, and doesn't feel smooth or natural. 一切正常,但动画是线性的,并且感觉不流畅或自然。 I had thought of hooking up an easing equation, but I'm not sure where it goes. 我原本想挂钩一个宽松的方程式,但我不确定它的去向。

Here's the animation function I borrowed from here : 这是我从这里借来的动画功能:

function animate(elem, style, unit, from, to, time) {
    if (!elem) return;
    var start = new Date().getTime(),
        timer = setInterval(function() {
            var step = Math.min(1,(new Date().getTime()-start)/time);

            elem.style[style] = (from+step*(to-from))+unit;

            if (step == 1) clearInterval(timer);
        },25);
    elem.style[style] = from+unit;
}

And an easing function from here : 还有一个从这里开始的缓动功能:

/**
 * @param {Number} t The current time
 * @param {Number} b The start value
 * @param {Number} c The change in value
 * @param {Number} d The duration time
 */ 
function easeInCubic(t, b, c, d) {
    t /= d;
    return c*t*t*t + b;
}

I tried just passing in the values I already have like this: 我尝试只传递已经具有的值:

elem.style[style] = easeInCubic(start, from, to, time) + unit;

But clearly, that's wrong (I'm not amazing at maths, and I'm admittedly just guessing). 但是很显然,这是错误的(我在数学上并不令人惊讶,并且我只能猜测)。

How do I join the two together? 如何将两者结合在一起?

your approach is ok, you just used wrong parameters. 您的方法还可以,只是使用了错误的参数。 as it says, t is current time and d is overall animation time 就像它说的那样,t是当前时间,d是整体动画时间

function animate(elem, style, unit, from, to, time) {
    if (!elem) return;
    var start = new Date().getTime(),
        timer = setInterval(function() {
            var step = Math.min(1,(new Date().getTime()-start)/time);
            elem.style[style] =  easeInCubic(step*time, from,step*(to-from), time)+unit;

            if (step == 1) clearInterval(timer);
        },25);
    elem.style[style] = from+unit;
}

t is the current time, or more accurately the elapsed time. t是当前时间,或更准确地说是经过的时间。 In your case new Date().getTime() - start 在您的情况下, new Date().getTime() - start

c is the difference between start and end, in your case from - to . c是开始和结束之间的差,在您的情况下from - to

        var elapsedTime = new Date().getTime() - start;
        elem.style[style] = easeInCubic(elapsedTime, from, to - from, time) + unit;
        if (elapsedTime >= time) clearInterval(timer);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM