Skip to content

Instantly share code, notes, and snippets.

@aweffr
Last active November 21, 2018 02:45
Show Gist options
  • Save aweffr/ed58e2eca7353573b32fa959244217aa to your computer and use it in GitHub Desktop.
Save aweffr/ed58e2eca7353573b32fa959244217aa to your computer and use it in GitHub Desktop.
简化 CountUp.js emitting data instead of update dom (with format)
// https://github.com/danro/jquery-easing/blob/master/jquery.easing.js
const easeOutExpo = (t, b, c, d) => {
return c * (-Math.pow(2, -10 * t / d) + 1) * 1024 / 1023 + b;
};
const easeInCubic = (t, b, c, d) => {
return c * (t /= d) * t * t + b;
};
const easeOutCubic = (t, b, c, d) => {
return c * ((t = t / d - 1) * t * t + 1) + b;
};
const easeOutSine = (t, b, c, d) => {
return c * Math.sin(t / d * (Math.PI / 2)) + b;
};
export const easeFn = {
easeOutExpo, easeInCubic, easeOutCubic, easeOutSine
};
// const ensureNumber = (n) => {
// return (typeof n === 'number' && !isNaN(n));
// };
class CountUp {
constructor({start = 0, end = 1000, duration = 1000, easeFn, handler} = {}) {
this.startVal = start;
this.endVal = end;
this.duration = duration;
this.handler = (typeof handler === "function") ? handler : (value) => console.log(value);
this.easeFn = (typeof easeFn === "function") ? easeFn : easeOutSine;
}
start = () => {
this.rAF = requestAnimationFrame(this.count);
};
update = (value) => {
delete this.startTime;
if (this.rAF) cancelAnimationFrame(this.rAF);
this.startVal = this.frameVal || this.endVal;
this.endVal = value;
this.start();
};
count = (timestamp) => {
if (!this.startTime) {
this.startTime = timestamp;
}
this.timestamp = timestamp;
const progress = timestamp - this.startTime;
// const remaining = this.duration - progress; // used for `paused`
this.frameVal = this.easeFn(progress, this.startVal, this.endVal - this.startVal, this.duration);
// don't go past endVal since progress can exceed duration in the last frame
this.frameVal = Math.min(this.endVal, this.frameVal);
this.frameVal = Math.ceil(this.frameVal);
this.handler(this.frameVal);
// whether to continue
if (progress < this.duration) {
this.rAF = requestAnimationFrame(this.count);
}
};
}
export default CountUp;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment