UNPKG

timing-function

Version:

Simple API for easing functions and Bezier curves

135 lines (127 loc) 3.37 kB
// Generated by CoffeeScript 1.8.0 var UnitBezier, isFinite, timingFunction; UnitBezier = require('./UnitBezier'); module.exports = timingFunction = { UnitBezier: UnitBezier, linear: function(p) { return p; }, define: function(name, func) { var _func, _name; if (typeof name === 'object') { for (_name in name) { _func = name[_name]; timingFunction.define(_name, _func); } return; } return timingFunction[name] = { easeIn: func, easeOut: function(p, x) { return 1 - func(1 - p, x); }, easeInOut: function(p, x) { if (p <= 0.5) { return 0.5 * func(p * 2, x); } else { return 0.5 * (2 - func(2 * (1 - p), x)); } } }; }, get: function(func, x) { var b, comp, f, i, part, parts, _i, _j, _len, _len1; if (func instanceof Function) { return func; } else if ((arguments[1] != null) && (arguments[2] != null) && (arguments[3] != null)) { b = new UnitBezier(arguments[0], arguments[1], arguments[2], arguments[3]); return function(p) { return b.solveSimple(p); }; } if (Array.isArray(func)) { return timingFunction.get.apply(null, func); } if (typeof func !== 'string') { throw Error("func should either be a function or a string, like 'cubic.easeOut'"); } if (func.match(/\,/)) { parts = func.split(/\,/); if (parts.length !== 4) { throw Error("Invalid func '" + func + "'"); } for (i = _i = 0, _len = parts.length; _i < _len; i = ++_i) { part = parts[i]; comp = parseFloat(part.replace(/\s+/g, '')); if (!isFinite(comp)) { throw Error("Invalid number '" + part + "' in '" + func + "'"); } parts[i] = comp; } b = new UnitBezier(parts[0], parts[1], parts[2], parts[3]); return function(p) { return b.solveSimple(p); }; } parts = func.split('.'); f = timingFunction; for (_j = 0, _len1 = parts.length; _j < _len1; _j++) { part = parts[_j]; f = f[part]; } if (typeof f === 'undefined') { throw Error("Cannot find easing function '" + func + "'"); } if (x != null) { return function(p) { return f(p, x); }; } return f; } }; timingFunction.define({ quad: function(p) { return Math.pow(p, 2); }, cubic: function(p) { return Math.pow(p, 3); }, quart: function(p) { return Math.pow(p, 4); }, quint: function(p) { return Math.pow(p, 5); }, expo: function(p) { return Math.pow(2, 8 * (p - 1)); }, circ: function(p) { return 1 - Math.sin(Math.cos(p)); }, sine: function(p) { return 1 - Math.cos(p * Math.PI / 2); }, elastic: function(p, x) { return Math.pow(2, 10 * (p - 1)) * Math.cos(20 * Math.PI * x / 3 * p); }, bow: function(p, x) { return Math.pow(p, 2) * ((x + 1) * p - x); }, bounce: function(p) { for(var a = 0, b = 1, result; 1; a += b, b /= 2) { if (p >= (7 - 4 * a) / 11) { return -Math.pow((11 - 6 * a - 11 * p) / 4, 2) + Math.pow(b, 2) } }//; } }); isFinite = function(value) { if (typeof value !== 'number') { return false; } if (value !== value || value === Infinity || value === -Infinity) { return false; } return true; };