Skip to content

Instantly share code, notes, and snippets.

@doug
Last active August 29, 2015 14:00
Show Gist options
  • Save doug/11063351 to your computer and use it in GitHub Desktop.
Save doug/11063351 to your computer and use it in GitHub Desktop.
JsKeyFrameEffect to extend web-animations.js
// JSKeyFrameEffect to extend web-animations.js
function JSKeyFrameEffect(model, keyframes) {
if (keyframes.length === 0) {
if (console) {
console.warn('Must provide keyframes.');
}
return function() {};
}
if (keyframes[0].offset === undefined) {
var step = 1.0/(keyframes.length-1 || 1);
for(var i=0,l=keyframes.length;i<l;i++) {
keyframes[i].offset = i*step;
}
}
var finished = false;
var epsilon = 0.02;
return function(t, anim) {
var from;
var to;
for(var i=0,l=keyframes.length;i<l;i++) {
to = keyframes[i];
if (to.offset > t) {
break;
}
from = to;
}
var key;
if (from === to || 1-t < epsilon) {
// force set the final values
for(key in to) {
if (key === 'offset') {
continue;
}
model[key] = to[key];
}
return;
}
if (from === undefined) {
from = model;
}
var timeDelta = to.offset - (from.offset||0);
var p = (t - (from.offset||0)) / timeDelta;
var fromValue, toValue, valueDelta, value;
for(key in to) {
if (key === 'offset') {
continue;
}
fromValue = from[key] || 0;
toValue = to[key] || 0;
valueDelta = toValue - fromValue;
value = fromValue + p * valueDelta;
model[key] = value;
}
};
}
// Example of use
// var state = {
// thing: 10,
// other: 1
// };
// var effect = JSKeyFrameEffect(state, [
// {thing: 0, other: 10},
// {thing: 1, other: 1},
// ]);
// var animation = new Animation(
// null,
// effect,
// {
// easing: 'ease-in-out',
// duration: 1
// }
// );
// document.timeline.play(animation);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment