WxCountUp.js 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. /**
  2. * 数字滚动
  3. *
  4. * @param {String} target 滚动对象
  5. * @param {Number} endVal 滚动结束时的数字
  6. * @param {Object} options 配置
  7. * @param {Object} context 微信小程序当前this对象
  8. *
  9. * forked from https://github.com/inorganik/CountUp.js
  10. */
  11. class WxCountUp {
  12. constructor(target = '', endVal = 0, options = {}, context = {}) {
  13. var _this = this
  14. this.target = target;
  15. this.endVal = endVal;
  16. this.options = options;
  17. this.context = context;
  18. this.version = '1.0.0';
  19. this.defaults = {
  20. startVal: 0,
  21. decimalPlaces: 0,
  22. duration: 2,
  23. useEasing: true,
  24. useGrouping: true,
  25. smartEasingThreshold: 999,
  26. smartEasingAmount: 333,
  27. separator: ',',
  28. decimal: '.',
  29. prefix: '',
  30. suffix: ''
  31. }
  32. this.finalEndVal = null;
  33. this.useEasing = true;
  34. this.countDown = false;
  35. this.error = '';
  36. this.startVal = 0;
  37. this.paused = true;
  38. this.count = function (timestamp) {
  39. if (!_this.startTime) {
  40. _this.startTime = timestamp;
  41. }
  42. var progress = timestamp - _this.startTime;
  43. _this.remaining = _this.duration - progress;
  44. // to ease or not to ease
  45. if (_this.useEasing) {
  46. if (_this.countDown) {
  47. _this.frameVal = _this.startVal - _this.easingFn(progress, 0, _this.startVal - _this.endVal, _this.duration);
  48. }
  49. else {
  50. _this.frameVal = _this.easingFn(progress, _this.startVal, _this.endVal - _this.startVal, _this.duration);
  51. }
  52. }
  53. else {
  54. if (_this.countDown) {
  55. _this.frameVal = _this.startVal - ((_this.startVal - _this.endVal) * (progress / _this.duration));
  56. }
  57. else {
  58. _this.frameVal = _this.startVal + (_this.endVal - _this.startVal) * (progress / _this.duration);
  59. }
  60. }
  61. // don't go past endVal since progress can exceed duration in the last frame
  62. if (_this.countDown) {
  63. _this.frameVal = (_this.frameVal < _this.endVal) ? _this.endVal : _this.frameVal;
  64. }
  65. else {
  66. _this.frameVal = (_this.frameVal > _this.endVal) ? _this.endVal : _this.frameVal;
  67. }
  68. // decimal
  69. _this.frameVal = Math.round(_this.frameVal * _this.decimalMult) / _this.decimalMult;
  70. // format and print value
  71. _this.printValue(_this.frameVal);
  72. // whether to continue
  73. if (progress < _this.duration) {
  74. _this.rAF = doAnimationFrame(_this.count);
  75. }
  76. else if (_this.finalEndVal !== null) {
  77. // smart easing
  78. _this.update(_this.finalEndVal);
  79. }
  80. else {
  81. if (_this.callback) {
  82. _this.callback();
  83. }
  84. }
  85. };
  86. // 默认格式和缓和函数
  87. this.formatNumber = function (num) {
  88. var neg = (num < 0) ? '-' : '';
  89. var result, x, x1, x2, x3;
  90. result = Math.abs(num).toFixed(_this.options.decimalPlaces);
  91. result += '';
  92. x = result.split('.');
  93. x1 = x[0];
  94. x2 = x.length > 1 ? _this.options.decimal + x[1] : '';
  95. if (_this.options.useGrouping) {
  96. x3 = '';
  97. for (var i = 0, len = x1.length; i < len; ++i) {
  98. if (i !== 0 && (i % 3) === 0) {
  99. x3 = _this.options.separator + x3;
  100. }
  101. x3 = x1[len - i - 1] + x3;
  102. }
  103. x1 = x3;
  104. }
  105. // optional numeral substitution
  106. if (_this.options.numerals && _this.options.numerals.length) {
  107. x1 = x1.replace(/[0-9]/g, function (w) { return _this.options.numerals[+w]; });
  108. x2 = x2.replace(/[0-9]/g, function (w) { return _this.options.numerals[+w]; });
  109. }
  110. return neg + _this.options.prefix + x1 + x2 + _this.options.suffix;
  111. };
  112. this.easeOutExpo = function (t, b, c, d) {
  113. return c * (-Math.pow(2, -10 * t / d) + 1) * 1024 / 1023 + b;
  114. };
  115. this.options = __assign({}, this.defaults, options);
  116. this.formattingFn = (this.options.formattingFn) ? this.options.formattingFn : this.formatNumber;
  117. this.easingFn = (this.options.easingFn) ? this.options.easingFn : this.easeOutExpo;
  118. this.startVal = this.validateValue(this.options.startVal);
  119. this.frameVal = this.startVal;
  120. this.endVal = this.validateValue(endVal);
  121. this.options.decimalPlaces = Math.max(0 || this.options.decimalPlaces);
  122. this.decimalMult = Math.pow(10, this.options.decimalPlaces);
  123. this.resetDuration();
  124. this.options.separator = String(this.options.separator);
  125. this.useEasing = this.options.useEasing;
  126. if (this.options.separator === '') {
  127. this.options.useGrouping = false;
  128. }
  129. if (this.target && typeof target === 'string') {
  130. this.printValue(this.startVal);
  131. } else {
  132. this.error = '[CountUp] target is null or undefined';
  133. }
  134. }
  135. // 决定数字滚动的方向
  136. determineDirectionAndSmartEasing () {
  137. var end = (this.finalEndVal) ? this.finalEndVal : this.endVal;
  138. this.countDown = (this.startVal > end);
  139. var animateAmount = end - this.startVal;
  140. if (Math.abs(animateAmount) > this.options.smartEasingThreshold) {
  141. this.finalEndVal = end;
  142. var up = (this.countDown) ? 1 : -1;
  143. this.endVal = end + (up * this.options.smartEasingAmount);
  144. this.duration = this.duration / 2;
  145. }
  146. else {
  147. this.endVal = end;
  148. this.finalEndVal = null;
  149. }
  150. if (this.finalEndVal) {
  151. this.useEasing = false;
  152. }
  153. else {
  154. this.useEasing = this.options.useEasing;
  155. }
  156. }
  157. // 开始动画
  158. start (callback) {
  159. if (this.error || !this.context) {
  160. return;
  161. }
  162. this.callback = callback;
  163. if (this.duration > 0) {
  164. this.determineDirectionAndSmartEasing();
  165. this.paused = false;
  166. this.rAF = doAnimationFrame(this.count);
  167. } else {
  168. this.printValue(this.endVal);
  169. }
  170. }
  171. // 暂停/恢复动画
  172. pauseResume () {
  173. if (!this.paused) {
  174. abortAnimationFrame(this.rAF);
  175. } else {
  176. this.startTime = null;
  177. this.duration = this.remaining;
  178. this.startVal = this.frameVal;
  179. this.determineDirectionAndSmartEasing();
  180. this.rAF = doAnimationFrame(this.count);
  181. }
  182. this.paused = !this.paused;
  183. }
  184. // 重置为 startVal,以便动画可以再次运行
  185. reset () {
  186. abortAnimationFrame(this.rAF);
  187. this.paused = true;
  188. this.resetDuration();
  189. this.startVal = this.validateValue(this.options.startVal);
  190. this.frameVal = this.startVal;
  191. this.printValue(this.startVal);
  192. }
  193. // 通过一个新的 endVal 并开始动画
  194. update (newEndVal) {
  195. abortAnimationFrame(this.rAF);
  196. this.startTime = null;
  197. this.endVal = this.validateValue(newEndVal);
  198. if (this.endVal === this.frameVal) {
  199. return;
  200. }
  201. this.startVal = this.frameVal;
  202. if (!this.finalEndVal) {
  203. this.resetDuration();
  204. }
  205. this.determineDirectionAndSmartEasing();
  206. this.rAF = doAnimationFrame(this.count);
  207. }
  208. // 输出值
  209. printValue (val) {
  210. var result = this.formattingFn(val);
  211. var target = this.target
  212. this.context && this.context.setData({
  213. [target]: result
  214. })
  215. }
  216. // 是否数字类型
  217. ensureNumber (n) {
  218. return (typeof n === 'number' && !isNaN(n));
  219. }
  220. // 验证值的类型
  221. validateValue (value) {
  222. var newValue = Number(value);
  223. if (!this.ensureNumber(newValue)) {
  224. this.error = "[CountUp] invalid start or end value: " + value;
  225. return null;
  226. }
  227. else {
  228. return newValue;
  229. }
  230. }
  231. // 重置动画间隔
  232. resetDuration () {
  233. this.startTime = null;
  234. this.duration = Number(this.options.duration) * 1000;
  235. this.remaining = this.duration;
  236. }
  237. }
  238. /**
  239. * 复制对象
  240. */
  241. var __assign = (this && this.__assign) || function () {
  242. __assign = Object.assign || function(t) {
  243. for (var s, i = 1, n = arguments.length; i < n; i++) {
  244. s = arguments[i];
  245. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  246. t[p] = s[p];
  247. }
  248. return t;
  249. };
  250. return __assign.apply(this, arguments);
  251. };
  252. /**
  253. * 代替 requestAnimationFrame 帧渲染
  254. * copy from https://www.dennic365.com/blog/?p=87
  255. */
  256. var lastFrameTime = 0;
  257. // 模拟 requestAnimationFrame
  258. var doAnimationFrame = function (callback) {
  259. var currTime = new Date().getTime();
  260. var timeToCall = Math.max(0, 16 - (currTime - lastFrameTime));
  261. var id = setTimeout(function () { callback(currTime + timeToCall); }, timeToCall);
  262. lastFrameTime = currTime + timeToCall;
  263. return id;
  264. };
  265. // 模拟 cancelAnimationFrame
  266. var abortAnimationFrame = function (id) {
  267. clearTimeout(id)
  268. }
  269. export default WxCountUp