Skip to content

Instantly share code, notes, and snippets.

@dievardump
Created December 20, 2019 14:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dievardump/a34f6fd9b4a67bae8fb59a7ece690d11 to your computer and use it in GitHub Desktop.
Save dievardump/a34f6fd9b4a67bae8fb59a7ece690d11 to your computer and use it in GitHub Desktop.
Very simple animation class vanilla js
/**
Usage
const animate = new Animate((value, elapsed) => {
console.log(value, elapsed);
}, {
duration: 5000
});
animate.animate(0, 100);
*/
export default class {
constructor(callback = (value => {}), options) {
const default_options = {
duration : 1000,
transition : function(p) {
return p;
}
};
this.options = {
...default_options,
...options
};
this.iterate = this._iterate.bind(this);
this.callback = callback;
this.from = 0;
this.to = 100;
this.time = null;
this.reqId = null;
}
animate(from, to) {
this.from = from;
this.to = to;
this.start = +(new Date);
this.iterate();
}
render(from, to, delta) {
var value = (to-from) * delta+from;
return value;
}
_iterate() {
const now = +(new Date);
const elapsed = (now-this.start);
const duration = this.options.duration;
const percentage = Math.min(1, elapsed/duration);
const delta = this.options.transition(percentage);
const value = this.render(this.from, this.to, delta);
this.callback(value, percentage);
if (percentage < 1) {
requestAnimationFrame(this.iterate);
}
}
}
const Transitions = {
Pow: function(p, x){
return Math.pow(p, x && x[0] || 6);
},
Expo: function(p){
return Math.pow(2, 8 * (p - 1));
},
Circ: function(p){
return 1 - Math.sin(Math.acos(p));
},
Sine: function(p){
return 1 - Math.cos(p * Math.PI / 2);
},
Back: function(p, x){
x = x && x[0] || 1.618;
return Math.pow(p, 2) * ((x + 1) * p - x);
},
Bounce: function(p){
var value;
for (var a = 0, b = 1; 1; a += b, b /= 2){
if (p >= (7 - 4 * a) / 11){
value = b * b - Math.pow((11 - 6 * a - 11 * p) / 4, 2);
break;
}
}
return value;
},
Elastic: function(p, x){
return Math.pow(2, 10 * --p) * Math.cos(20 * p * Math.PI * (x && x[0] || 1) / 3);
}
};
const ease = function(transition, params) {
params = params ? (Array.isArray(params) ? params : [params]) : [];
return {
easeIn: function(pos){
return transition(pos, params);
},
easeOut: function(pos){
return 1 - transition(1 - pos, params);
},
easeInOut: function(pos){
return (pos <= 0.5 ? transition(2 * pos, params) : (2 - transition(2 * (1 - pos), params))) / 2;
}
};
};
['Quad', 'Cubic', 'Quart', 'Quint'].forEach(function(name, i){
Transitions[name] = ease(function(p) {
return Math.pow(p, i + 2);
});
});
export {Transitions as Transitions};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment