requestAnimationFrame动画封装

本文介绍了一个自定义动画实现的方法,通过创建Animator类及其原型方法,实现了动画的开始和停止功能。利用requestAnimationFrame进行平滑动画更新,适用于浏览器环境。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值