requestAnimationFrame动画封装

function Animator(duration, progress) {
    this.duration = duration;
    this.progress = progress;
    this.next = true;
}
Animator.prototype = {
    constructor: Animator,
    start: function (finished) {
        var startTime = new Date().getTime();
        var duration = this.duration,
            self = this,
            timeOut = 0;
        var vendors = ['webkit', 'moz'];
        for (var i = 0; i < vendors.length && !window.requestAnimationFrame; ++i) {
            window.requestAnimationFrame = window[vendors[i] + 'RequestAnimationFrame'];
        }
        if (!window.requestAnimationFrame) {
            window.requestAnimationFrame = function (callback, element) {
                var start = 0,
                    finish = 0;
                window.setTimeout(function () {
                    start = +new Date();
                    callback(start);
                    finish = +new Date();
                    timeOut = 1000 / 300 - (finish - start);
                }, timeOut);
            };
        }

        window.requestAnimationFrame(function step() {
            var p = (new Date().getTime() - startTime) / duration;
            self.progress(p, p);
            if (p >= 1.0) {
                self.progress(1.0, 1.0);
                self.next = false;
                finished();
            }

            if (self.next) {
                window.requestAnimationFrame(step);
            }

        });
    },
    stop: function () {
        this.next = false;
    }
};


原文地址:https://www.cnblogs.com/jerrypig/p/10150329.html