0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Javascriptでtweenerを自作する

Posted at

##たまに作るような内容ですがコピペで使えるように、メモ的に書いています。

setIntervalで回数制限
https://ndruger.hatenadiary.org/entry/20100928/1285679176
イージングの使い方の確認
https://gist.github.com/gre/1650294
経過時間の参照
https://webbibouroku.com/Blog/Article/js-time

上記リンクを参考

EasingFunctionsはそのまま利用する(jsに直書きでもOK)

qiita.js
function tweener(_time,_func,_ease){
   var start = new Date().getTime();
    var _si = setInterval(function(){
        var _progress = new Date().getTime() - start;
        if ( _progress > _time) {
          //1
          _func(1);
          clearInterval(_si);
        }else{
          //
          _func(_ease(_progress/_time));
        }
    }, 33);
}

これで使い方は

qiita.js
tweener(3000,function(progress){
  console.log(progress)
},EasingFunctions.easeOutQuint);

こんな感じでprogressに0-1までの値で3秒間でeaseOutQuintで値が出てくるので変数に当てはめればいい。

でこれで終わりでもいいのですが、途中で止めるっていうのも欲しい。やめ方も
skipで終了値にする、cancelで初期値にする、killで止めるっていうのができたらいいので追加すると

qiita.js
var TWEENER = {
  tween:function(_time,_func,_ease){
    var start = new Date().getTime();
    var _this = this;
    _this.functionHolder = _func;
    _this.setIntervalObj = setInterval(function(){
        var _progress = new Date().getTime() - start;
        if ( _progress > _time) {
          //1
          _func(1);
          _this.functionHolder = null;
          clearInterval(_this.setIntervalObj);
        }else{
          //
          _func(_ease(_progress/_time));
        }
    }, 33);
  },
  cancel:function(){
    if(this.functionHolder != null){
      this.functionHolder(1)
      clearInterval(this.setIntervalObj);
    }
  },
  skip:function(){
    if(this.functionHolder != null){
      this.functionHolder(1)
      clearInterval(this.setIntervalObj);
    }
  },
  kill:function(){
    clearInterval(this.setIntervalObj);
  },
  functionHolder:null,
  setIntervalObj:null
}

で使い方は

qiita.js
TWEENER.tween(3000,function(progress){
  console.log(progress)
},EasingFunctions.easeOutQuint);

setTimeout(function(){
  TWEENER.cancel();
},1000);

※無理やり1秒後にcancelをしています
な感じで自前でtweenerが完成。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?