Clip.js 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. var easingFuncs = require("./easing");
  2. /**
  3. * 动画主控制器
  4. * @config target 动画对象,可以是数组,如果是数组的话会批量分发onframe等事件
  5. * @config life(1000) 动画时长
  6. * @config delay(0) 动画延迟时间
  7. * @config loop(true)
  8. * @config gap(0) 循环的间隔时间
  9. * @config onframe
  10. * @config easing(optional)
  11. * @config ondestroy(optional)
  12. * @config onrestart(optional)
  13. *
  14. * TODO pause
  15. */
  16. function Clip(options) {
  17. this._target = options.target; // 生命周期
  18. this._life = options.life || 1000; // 延时
  19. this._delay = options.delay || 0; // 开始时间
  20. // this._startTime = new Date().getTime() + this._delay;// 单位毫秒
  21. this._initialized = false; // 是否循环
  22. this.loop = options.loop == null ? false : options.loop;
  23. this.gap = options.gap || 0;
  24. this.easing = options.easing || 'Linear';
  25. this.onframe = options.onframe;
  26. this.ondestroy = options.ondestroy;
  27. this.onrestart = options.onrestart;
  28. this._pausedTime = 0;
  29. this._paused = false;
  30. }
  31. Clip.prototype = {
  32. constructor: Clip,
  33. step: function (globalTime, deltaTime) {
  34. // Set startTime on first step, or _startTime may has milleseconds different between clips
  35. // PENDING
  36. if (!this._initialized) {
  37. this._startTime = globalTime + this._delay;
  38. this._initialized = true;
  39. }
  40. if (this._paused) {
  41. this._pausedTime += deltaTime;
  42. return;
  43. }
  44. var percent = (globalTime - this._startTime - this._pausedTime) / this._life; // 还没开始
  45. if (percent < 0) {
  46. return;
  47. }
  48. percent = Math.min(percent, 1);
  49. var easing = this.easing;
  50. var easingFunc = typeof easing === 'string' ? easingFuncs[easing] : easing;
  51. var schedule = typeof easingFunc === 'function' ? easingFunc(percent) : percent;
  52. this.fire('frame', schedule); // 结束
  53. if (percent === 1) {
  54. if (this.loop) {
  55. this.restart(globalTime); // 重新开始周期
  56. // 抛出而不是直接调用事件直到 stage.update 后再统一调用这些事件
  57. return 'restart';
  58. } // 动画完成将这个控制器标识为待删除
  59. // 在Animation.update中进行批量删除
  60. this._needsRemove = true;
  61. return 'destroy';
  62. }
  63. return null;
  64. },
  65. restart: function (globalTime) {
  66. var remainder = (globalTime - this._startTime - this._pausedTime) % this._life;
  67. this._startTime = globalTime - remainder + this.gap;
  68. this._pausedTime = 0;
  69. this._needsRemove = false;
  70. },
  71. fire: function (eventType, arg) {
  72. eventType = 'on' + eventType;
  73. if (this[eventType]) {
  74. this[eventType](this._target, arg);
  75. }
  76. },
  77. pause: function () {
  78. this._paused = true;
  79. },
  80. resume: function () {
  81. this._paused = false;
  82. }
  83. };
  84. var _default = Clip;
  85. module.exports = _default;