Velocityのイージングを拡張する
Velocityっていうアニメーション用のライブラリがある。
最初からいろんなイージングが使えて、jQuery UIのイージングの一部が入ってるんだけど、Back系、Elastic系、Bounce系のやつは入ってない。
Velocityは独自にイージングを拡張することもできるので、jQuery UIで使えるイージングは全部使えるようにしてみた。
'use strict'; import Velocity from 'velocity-animate'; let baseEasings = {}; baseEasings.Elastic = p => { return p === 0 || p === 1 ? p : -Math.pow(2, 8 * (p - 1)) * Math.sin (((p - 1) * 80 - 7.5) * Math.PI / 15); }; baseEasings.Back = p => p * p * (3 * p - 2); baseEasings.Bounce = p => { let pow2; let bounce = 4; while (p < ((pow2 = Math.pow(2, --bounce)) - 1) / 11) {} return 1 / Math.pow(4, 3 - bounce) - 7.5625 * Math.pow((pow2 * 3 - 2) / 22 - p, 2); }; Object.keys(baseEasings).forEach(name => { Velocity.Easings[`easeIn${name}`] = baseEasings[name]; Velocity.Easings[`easeOut${name}`] = p => 1 - baseEasings[name](1 - p); Velocity.Easings[`easeInOut${name}`] = p => { return p < 0.5 ? baseEasings[name](p * 2) / 2 : 1 - baseEasings[name](p * -2 + 2) / 2; } }); export default Velocity;
以上のコードで、
- easeInElastic
- easeOutElastic
- easeInOutElastic
- easeInBack
- easeOutBack
- easeInOutBack
- easeInBounce
- easeOutBounce
- easeInOutBounce
を拡張できた。
これをimportしたらイージングを拡張したVelocityが使える。
2016/8/15 追記
ソースはこの辺参考
あと、イージングは一度拡張すれば、ファイルを分けてrequire
する必要はない。
つまり以下のようにして利用できる。
main.js
const Velocity = require('velocity-animate'); // イージングを拡張 Velocity.Easings.anyEasing = () => {}; require('./animation');
animation.js
const Velocity = require('velocity-animate'); Velocity(document.getElementById('el'), {opacity: 0}, 'anyEasing');