Tween.js 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. var Emitter = require('./Emitter');
  2. var State = require('./State');
  3. var easing = require('./easing');
  4. var now = require('./now');
  5. var each = require('./each');
  6. var raf = require('./raf');
  7. var isFn = require('./isFn');
  8. exports = Emitter.extend({
  9. className: 'Tween',
  10. initialize: function(target) {
  11. this.callSuper(Emitter, 'initialize', arguments);
  12. this._target = target;
  13. this._dest = {};
  14. this._duration = 0;
  15. this._progress = 0;
  16. this._origin = {};
  17. this._diff = {};
  18. this._ease = easing['linear'];
  19. this._state = new State('pause', {
  20. play: {
  21. from: 'pause',
  22. to: 'play'
  23. },
  24. pause: {
  25. from: 'play',
  26. to: 'pause'
  27. }
  28. });
  29. },
  30. to: function(props, duration, ease) {
  31. var origin = {};
  32. var target = this._target;
  33. var diff = {};
  34. ease = ease || this._ease;
  35. this._dest = props;
  36. this._duration = duration || this._duration;
  37. this._ease = isFn(ease) ? ease : easing[ease];
  38. each(props, function(val, key) {
  39. origin[key] = target[key];
  40. diff[key] = val - origin[key];
  41. });
  42. this._origin = origin;
  43. this._diff = diff;
  44. return this;
  45. },
  46. progress: function(progress) {
  47. var ease = this._ease;
  48. var target = this._target;
  49. var origin = this._origin;
  50. var diff = this._diff;
  51. var dest = this._dest;
  52. var self = this;
  53. if (progress != null) {
  54. progress = progress < 1 ? progress : 1;
  55. this._progress = progress;
  56. each(dest, function(val, key) {
  57. target[key] = origin[key] + diff[key] * ease(progress);
  58. });
  59. self.emit('update', target);
  60. return this;
  61. }
  62. return this._progress;
  63. },
  64. play: function() {
  65. var state = this._state;
  66. if (state.is('play')) return;
  67. state.play();
  68. var startTime = now();
  69. var progress = this._progress;
  70. var duration = this._duration * (1 - progress);
  71. var target = this._target;
  72. var self = this;
  73. function render() {
  74. if (state.is('pause')) return;
  75. var time = now();
  76. self.progress(progress + (time - startTime) / duration);
  77. if (self._progress === 1) {
  78. state.pause();
  79. self.emit('end', target);
  80. return;
  81. }
  82. raf(render);
  83. }
  84. raf(render);
  85. return this;
  86. },
  87. pause: function() {
  88. var state = this._state;
  89. if (state.is('pause')) return;
  90. state.pause();
  91. return this;
  92. },
  93. paused: function() {
  94. return this._state.is('pause');
  95. }
  96. });
  97. module.exports = exports;