javascript - requestAnimationFrame动画如何像transition一样控制完成时间?
阿神
阿神 2017-04-10 14:48:57
0
1
892

比如一个简单的改变width的动画,使用requestAnimationFrame的FPS是由浏览器控制,因此我无法确定width0100px用了多久,我希望他用1s的时间,难道只能通过动画函数中调整控制步长和通过打时间戳跳帧的方式来完成,而不是很完美优雅地像transition: width 1s; 这样精确地控制么

阿神
阿神

闭关修行中......

reply all(1)
小葫芦

代碼不優雅,是因爲結構不好。
代碼優雅,是因爲結構好,把不優雅的部分藏起來了。

可以考慮使用一個動畫庫,也可以考慮自己寫一個微型的。

話說,動畫本來就該是用時間來做度量的,對於不可控因素應該除掉~

"use strict";

var p = document.querySelector("p");

var y = 0;

function getStep(totalstep, duration, t, dt, timing) {
    return totalstep / duration * timing(t / duration) * dt;
}

function movement(t, dt) {
    var to = 1000, 
        duration = 707; // milliseconds
    y += getStep(to, duration, t, dt, function(t) { return 2 * t });
    y = Math.min(y, to);
    p.style.transform = "translate3d(0, " + y + "px, 0)";
    console.log(t);
    return (y) < to;
}

requestAnimationFrame(function(t) {
    var t0 = t, t1 = 0;
    requestAnimationFrame(function frame(t) {
        movement(t - t0, -t1 + (t1 = t)) && requestAnimationFrame(frame);
    });
});

https://bumfo.github.io/ani.html

這裏對於 timing 函數的要求很嚴,必須 Integral(0, 1, timing(t)) = 1,否則 結果的 duration 將會不正確。

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template