Last active
July 4, 2021 14:48
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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!')); |
Yes, sorry. I forgot to include in the exampleOn Sat, Jul 3, 2021 at 2:31 PM echofriend ***@***.***> ***@***.*** commented on this gist.
Is it possible to set the animation speed?
?You are receiving this because you authored the thread.Reply to this email directly, view it on GitHub, or unsubscribe.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Is it possible to set the animation speed?