2015-06-29 3 views
2

У меня есть функция таймера, с индикатором выполнения. Он работает хорошо, но я хочу сделать гладкую анимацию хода выполнения, с 60 FPSИндикатор работы таймера Javascript

function started(duration) { 
    var TotalSeconds = 40; 
    var documentWidth = $(document).width(); 
    var start = Date.now(); 
    var intervalSetted = null; 

    function timer() { 
     var diff = duration - (((Date.now() - start)/1000) | 0); 
     var seconds = (diff % 60) | 0; 
     seconds = seconds < 10 ? "0" + seconds : seconds; 
     $('#timer').html("00:" + seconds); 
     var progresBarWidth = (seconds * documentWidth/TotalSeconds); 

     $('#progress').css({ 
      width: progresBarWidth + 'px' 
     }); 

     if (diff <= 0) { 
      clearInterval(intervalSetted); 
     } 
    } 

    timer(); 
    intervalSetted = setInterval(timer, 1000); 
} 

started(40); 

Как достичь 60FPS-анимации?

Демоверсия моего кода: JSFiddle!

ответ

5

Вы можете использовать CSS3 анимации. Я написал несколько примеров кода, который показывает индикатор прогресса, который подсчитывается с использованием продолжительности, которую вы можете выбрать. Вы также можете получить обратный вызов, когда анимация будет завершена.

Утилиты CSS3 с аппаратным ускорением, поэтому у вас будет самый приятный опыт, когда вы его используете.

/* 
 
* Creates a progressbar. 
 
* @param id the id of the div we want to transform in a progressbar 
 
* @param duration the duration of the timer example: '10s' 
 
* @param callback, optional function which is called when the progressbar reaches 0. 
 
*/ 
 
function createProgressbar(id, duration, callback) { 
 
    // We select the div that we want to turn into a progressbar 
 
    var progressbar = document.getElementById(id); 
 
    progressbar.className = 'progressbar'; 
 

 
    // We create the div that changes width to show progress 
 
    var progressbarinner = document.createElement('div'); 
 
    progressbarinner.className = 'inner'; 
 

 
    // Now we set the animation parameters 
 
    progressbarinner.style.animationDuration = duration; 
 

 
    // Eventually couple a callback 
 
    if (typeof(callback) === 'function') { 
 
    progressbarinner.addEventListener('animationend', callback); 
 
    } 
 

 
    // Append the progressbar to the main progressbardiv 
 
    progressbar.appendChild(progressbarinner); 
 

 
    // When everything is set up we start the animation 
 
    progressbarinner.style.animationPlayState = 'running'; 
 
} 
 

 
addEventListener('load', function() { 
 
    createProgressbar('progressbar1', '40s'); 
 
    createProgressbar('progressbar2', '30s'); 
 
    createProgressbar('progressbar3', '20s', function() { 
 
    alert('20s progressbar is finished!'); 
 
    }); 
 
    createProgressbar('progressbar4', '10s', function() { 
 
    alert('10s progressbar is finished!'); 
 
    }); 
 
});
.progressbar { 
 
    width: 80%; 
 
    margin: 25px auto; 
 
    border: solid 1px #000; 
 
} 
 
.progressbar .inner { 
 
    height: 15px; 
 
    animation: progressbar-countdown; 
 
    /* Placeholder, this will be updated using javascript */ 
 
    animation-duration: 40s; 
 
    /* We stop in the end */ 
 
    animation-iteration-count: 1; 
 
    /* Stay on pause when the animation is finished finished */ 
 
    animation-fill-mode: forwards; 
 
    /* We start paused, we start the animation using javascript */ 
 
    animation-play-state: paused; 
 
    /* We want a linear animation, ease-out is standard */ 
 
    animation-timing-function: linear; 
 
} 
 
@keyframes progressbar-countdown { 
 
    0% { 
 
    width: 100%; 
 
    background: #0F0; 
 
    } 
 
    100% { 
 
    width: 0%; 
 
    background: #F00; 
 
    } 
 
}
<div id='progressbar1'></div> 
 
<div id='progressbar2'></div> 
 
<div id='progressbar3'></div> 
 
<div id='progressbar4'></div>

1

Используйте метод .animate() в jQuery вместо .css().

Метод .animate() позволяет нам создавать анимационные эффекты для любого численного свойства CSS . Единственным обязательным параметром является простой объект свойств CSS. Этот объект аналогичен тому, который может быть отправлен в .css(), за исключением того, что диапазон свойств больше ограничительный.

$('#progress').animate({ 
     width: progresBarWidth + 'px' 
}, 1000); 

Fiddle

Смежные вопросы