A minimal tweening class, utilising stepped updates with optional easing
This file contains 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
// A minimal tweening class, utilising stepped updates with optional easing | |
class Tween { | |
constructor ({ from, to, change, steps, easeFn, duration, cb }) { | |
this.from = from | |
this.to = typeof to === 'undefined' ? from + change : to | |
this.change = typeof change === 'undefined' ? to - from : change | |
this.steps = typeof steps === 'number' ? steps : duration / 16 | |
this.duration = duration | |
this.easeFn = typeof easeFn !== 'function' ? t => t : easeFn | |
this.cb = typeof cb === 'undefined' ? () => {} : cb | |
this.step = 0 | |
this.update = this.update.bind(this) | |
} | |
tick () { this.step < this.steps && this.step++ } | |
update (now) { | |
if (now > this.endTime) { | |
this.step = this.steps | |
return this.stop() | |
} | |
this.requestId = window.requestAnimationFrame(this.update) | |
if (this.step < (now / this.endTime) * this.steps | 0) { | |
this.tick() | |
this.cb(this.value) | |
} | |
} | |
start () { | |
this.startTime = window.performance.now() | |
this.endTime = this.startTime + this.duration | |
this.requestId = window.requestAnimationFrame(this.update) | |
} | |
stop () { | |
if (this.requestId) window.cancelAnimationFrame(this.requestId) | |
this.cb(this.value) | |
} | |
get value () { return this.from + (this.to - this.from) * this.easeFn(this.step / this.steps) } | |
} |
This file contains 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
// Example One (Using `from` and `to`) | |
const exampleOne = new Tween({ | |
from: -10, | |
to: 0, | |
steps: 5, | |
duration: 1000, | |
cb: v => console.log(v) | |
}).start() | |
// Example Two (Using `from` and `change`) | |
const exampleTwo = new Tween({ | |
from: -10, | |
change: 10, | |
steps: 5, | |
duration: 1000, | |
cb: v => console.log(v) | |
}).start() | |
// Example Three (Using `easeFn`) | |
const exampleThree = new Tween({ | |
from: 0, | |
to: 10, | |
steps: 5, | |
duration: 1000, | |
cb: v => console.log(v), | |
easeFn: t => t < .5 ? Math.pow(t * 2, 2) / 2 : (1 - Math.pow(1 - (t * 2 - 1), 2)) / 2 + .5 | |
}).start() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment