基于时间的动画 - 在设定的时间内增加一个数字(纯JavaScript)

时间:2016-09-21 10:46:12

标签: javascript timer numbers

我想为0中的数字设置动画并以所选值结束。

它必须在设定的时间内增加,例如1秒(基于时间)。

我需要一个纯JavaScript解决方案(而不是jQuery)。

我有这样的事情:

var animator = {};

animator.animate = null;

animator.settings = {
    elapsedTime: 0, //The elapsed time (used for animation)
    lastTime: 0, //The last time
    startTime: 0, //The current time
    speed: 1000 //How long it should animate
};

animator.increment = function (el, currVal, endVal) {
    var settings = this.settings,
        lastTime,
        self = this,
        startTime;

    settings.startTime = Date.now(); //Get the current time

    startTime = settings.startTime; //Cache the startTime
    lastTime = settings.lastTime; //Cache the lastTime

    //If the lastTime is not equal to 0
    if (lastTime !== 0) {
        settings.elapsedTime = startTime - lastTime; //Update the elapsed time
    }

    settings.lastTime = settings.startTime; //Update the last time

    //If the elapsed time has not passed the speed e.g. 1 second
    if (settings.elapsedTime >= settings.speed) {
        //Add the final value and clear the animation

        clearInterval(this.animate); //Stop animating
    } else {
        //Update the number
        if (currVal < endVal) {
            currVal += settings.speed * settings.elapsedTime;
        } else {
            currVal = endVal;
        }

        el.innerHTML = '&pound;' + currVal; //Update the HTML
    }

    this.animate = setInterval(function () {
        self.increment(el, currVal, endVal)
    }, 1000 / 60); //60 FPS
};

animator.increment(document.getElementById('num'), 0, 1234);

我觉得我错过了一些明显的东西。

增量太快,转换不顺畅,有时不会停止动画。

全部谢谢!

1 个答案:

答案 0 :(得分:0)

问题是由以下行创建的:

settings.lastTime = settings.startTime;

您只能将其用于连续动画,例如游戏循环

我已经整理了我的代码并根据别人给我的另一个解决方案回答了它。

var animator = {};

animator.animateNum = function (el, currVal, endVal) {
    var elapsedTime = 0, //The elapsed time (used for animation)
        fps = 1000 / 60, //60 fps (can be 16)
        lastTime = Date.now(), //The last time
        duration = 1000, //How fast it should animate
        increment = (endVal / duration) * fps, //Work out the increment amount
        update = null; //Where we attach the interval

    //Setup the interval
    update = setInterval(function () {
        elapsedTime = Date.now() - lastTime; //Work out the elapsed time

        //Check the elapsed time has not passed the duration
        if (elapsedTime < duration) {
            //Do the animation
            currVal += increment; //Increase the value
            el.innerHTML = '&pound' + parseFloat(currVal, 10).toFixed(2);
        } else {
            //Else, don't do the animation
            el.innerHTML = '&pound' + parseFloat(endVal, 10).toFixed(2); //Update it to the last value
            clearInterval(update); //Clear the interval
        }
    }, fps);
};

animator.animateNum(document.getElementById('num'), 0, 1005.99);

https://jsfiddle.net/Levyg475/1/

干杯!