Skip to content

Instantly share code, notes, and snippets.

@r3wt
Last active July 4, 2021 14:48
Show Gist options
  • Select an option

  • Save r3wt/172f61842c5d2a98cc3e49b336b6e988 to your computer and use it in GitHub Desktop.

Select an option

Save r3wt/172f61842c5d2a98cc3e49b336b6e988 to your computer and use it in GitHub Desktop.
@animateable decorator/mixin that can be used to add simple animations to any class object in javascript
const animateable = (a) => {
a.prototype.quad = function(x){
return x ** 2
};
a.prototype.linear = function(x){
return x;
};
a.prototype.animate = function({ duration=300, ease=this.quad, start, end, onUpdate, onComplete=()=>{}}){
let time = performance.now()
requestAnimationFrame(function animate() {
const delta = performance.now() - time
if (delta > duration){
return onUpdate(end,onComplete);
}
const pos = start + ease(delta / duration) * (end - start);
onUpdate(pos,()=>{
requestAnimationFrame(animate);
})
})
};
return a;
}
export default animateable;
class BasicHorse {
constructor(x,y) {
this.x = x;
this.y = y;
}
move(x,y,done) {
// we need to animate both x and y
let animations = [
this.animate({ start: this.x, end: x, onUpdate:(val,next)=>{ this.x=val; next() }, onComplete:done }),
this.animate({ start: this.y, end: y, onUpdate:(val,next)=>{ this.y=val; next() }, onComplete:done })
];
// return a function that allows us to cancel the animation
return function cancel() { animations.map(cancelAnimation=>cancelAnimation()) };
}
};
const AnimatableHorse = animatable(BasicHorse);
const horse = new AnimatableHorse(25,25);
horse.move(30,45,()=>console.log('the horse moved!'));
@echofriend
Copy link
Copy Markdown

Is it possible to set the animation speed?

@r3wt
Copy link
Copy Markdown
Author

r3wt commented Jul 4, 2021 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment