封装一个简单好用的Tween.js

原文地址:封装一个轻便好用的Tween.js
在开发过程中觉得Tween.js用起来太累赘了,要写很多不必要的代码,比如:

render();
        function render() {
            if (isOver) {
                that._complete && that._complete()
                return
            }
            requestAnimationFrame(render);
            TWEEN.update();
        }

所以我就对它进行了简单的封装,用起来非常的简单!

用的时候就是下面这样子,是不是显得非常简单?而且方法没有先后顺序。怎么写顺序都无所谓~

Animate.start({ y: scrollTop })
          .to({ y: height })
          .time(300)
          .update(({ y }) => {
            console.log("更新");
            dom.scrollTo(0, y);
          })
          .complete(() => {
            console.log("播放完成");
          });

封装的代码如下:

import TWEEN from "tween";
const Animate = {
    _tween: null,
    _to: null,
    _complete: null,
    start(obj) {
        obj.__number__ = 0;
        this._tween = new TWEEN.Tween(obj)
        return this;
    },
    to(obj) {
        obj.__number__ = 100;
        this._to = obj;
        return this;
    },
    time(time) {
        this._tween.to(this._to, time)
        return this;
    },
    update(callback) {
        var that = this;
        var _number = 100;
        var isOver = false;
        this._tween.onUpdate(function () {
            callback && callback(this)
            if (this.__number__ >= _number) {
                isOver = true;
            }
        })
        this._tween.start();
        render();
        function render() {
            if (isOver) {
                that._complete && that._complete()
                return
            }
            requestAnimationFrame(render);
            TWEEN.update();
        }
        return this;
    },
    complete(callback) {
        this._complete = callback
        return this;
    }
}

export default Animate;
再也不用写requestAnimationFrame了!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值