Skip to content

Instantly share code, notes, and snippets.

@peteroupc
Last active October 13, 2015 11:17
Show Gist options
  • Save peteroupc/4187083 to your computer and use it in GitHub Desktop.
Save peteroupc/4187083 to your computer and use it in GitHub Desktop.
Gets a timing function from a "transition-timing-function" string
// Gets a timing function from a "transition-timing-function" string
// Written by Peter O. in 2012, released to the public domain
// Returns the function itself if the object passed in is a Function object,
// or the "ease" function if the object is null or undefined
// This file is in the public domain. Peter O., 2012. http://upokecenter.dreamhosters.com
// Public domain dedication: http://creativecommons.org/publicdomain/zero/1.0/
function getTimingFunction(f){
if(typeof f=="undefined" || f==null)f="ease";
if(typeof f=="function" || (f && f.constructor==Function))return f;
if(f=="step-start")return function(v){ return (v>0) ? 1.0 : 0 };
if(f=="step-end")return function(v){ return (v<1) ? 0 : 1.0 };
if(f.indexOf("steps(")==0){
var e=(/^steps\((\d+)\s*\)$/).exec(f);
if(e){
var s=parseInt(e[1]);
if(s>0){ return function(x){ return Math.floor(x*s)/s } };
}
e=(/^steps\((\d+)\s*,\s*(start|end)\s*\)$/).exec(f);
if(e){
var s=parseInt(e[1]);
if(s>0){
if(e[2]=="end")return function(x){ return Math.floor(x*s)/s };
return function(x){ return Math.ceil(x*s)/s };
}
}
return function(v){ return v };
}
var bez=[0,0,1,1];
if(f=="linear")bez=[0,0,1,1];
else if(f=="ease-in")bez=[0.42,0,1,1];
else if(f=="ease-out")bez=[0,0,0.58,1];
else if(f=="ease-in-out")bez=[0.42,0,0.58,1];
else if(f=="ease")bez=[0.25,0.1,0.25,1];
else if(f.indexOf("cubic-bezier(")==0){
var e=(/^cubic-bezier\((\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\s*\)$/).exec(f);
if(e){
bez=[parseFloat(e[1]),parseFloat(e[2]),parseFloat(e[3]),pars];
}
}
return function(v){
var t=0.5;
var interval=0.25;
var mt=0;
if(v<=0)return 0.0;
if(v>=1)return 1.0;
for(var i=0;i<50;i++){
mt=1-t;
var x=3*mt*mt*t*bez[0]+3*mt*t*t*bez[2]+t*t*t;
var diff=x-v;
if(Math.abs(diff)<1.1920929e-07){
break;
} else if(diff>0){ // too far to the right
t-=interval;
} else { // too far to the left
t+=interval;
}
interval/=2.0;
}
mt=1-t;
var y=3*mt*mt*t*bez[1]+3*mt*t*t*bez[3]+t*t*t;
if(y<0)y=0; if(y>1)y=1;
return y;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment