1
1

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.

Array.reduce()を使ってGSAP3 timeline.to()のチェーンを作る

Posted at

JavaScriptのPromiseの使い方を解説したMDNのドキュメントに、Array.reduce()を使って複数の処理を直列的に繋げるコードが載っていて、数学のような不思議な記述形式にちょっぴり感動しました。

MDN: Promiseを使う合成 (Composition)

なるほど。Something.fn().fn().fn() ...というふうにメソッドチェーンを作れるオブジェクトならこの方式が適用できるのですね。GSAP3のTimelineto()メソッドなどでチェーンを作れます。

早速やってみました。たとえば、4個の要素を順番にアニメーションするこのTimelineの場合、

javascript
gsap.timeline({ defaults: {duration: 2, x: 300} })
.to('.a', {})
.to('.b', {})
.to('.c', {})
.to('.d', {});

これをArray.reduce()を使って次のように書き換えます。

javascript
['.a', '.b', '.c', '.d'].reduce((tl, e) => tl.to(e, {}),
       gsap.timeline({ defaults: {duration: 2, x: 300} }));

サンプルはこれです。

See the Pen Array.reduce, gsap.timeline by Kazuhiro Hashimoto (@kaz_hashimoto) on CodePen.

1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?