Animation.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. var Timing = {
  2. easeIn: function easeIn(pos) {
  3. return Math.pow(pos, 3);
  4. },
  5. easeOut: function easeOut(pos) {
  6. return Math.pow(pos - 1, 3) + 1;
  7. },
  8. easeInOut: function easeInOut(pos) {
  9. if ((pos /= 0.5) < 1) {
  10. return 0.5 * Math.pow(pos, 3);
  11. } else {
  12. return 0.5 * (Math.pow(pos - 2, 3) + 2);
  13. }
  14. },
  15. linear: function linear(pos) {
  16. return pos;
  17. }
  18. };
  19. function Animation(opts) {
  20. this.isStop = false;
  21. opts.duration = typeof opts.duration === 'undefined' ? 1000 : opts.duration;
  22. opts.timing = opts.timing || 'linear';
  23. var delay = 17;
  24. function createAnimationFrame() {
  25. if (typeof setTimeout !== 'undefined') {
  26. return function(step, delay) {
  27. setTimeout(function() {
  28. var timeStamp = +new Date();
  29. step(timeStamp);
  30. }, delay);
  31. };
  32. } else if (typeof requestAnimationFrame !== 'undefined') {
  33. return requestAnimationFrame;
  34. } else {
  35. return function(step) {
  36. step(null);
  37. };
  38. }
  39. };
  40. var animationFrame = createAnimationFrame();
  41. var startTimeStamp = null;
  42. var _step = function step(timestamp) {
  43. if (timestamp === null || this.isStop === true) {
  44. opts.onProcess && opts.onProcess(1);
  45. opts.onAnimationFinish && opts.onAnimationFinish();
  46. return;
  47. }
  48. if (startTimeStamp === null) {
  49. startTimeStamp = timestamp;
  50. }
  51. if (timestamp - startTimeStamp < opts.duration) {
  52. var process = (timestamp - startTimeStamp) / opts.duration;
  53. var timingFunction = Timing[opts.timing];
  54. process = timingFunction(process);
  55. opts.onProcess && opts.onProcess(process);
  56. animationFrame(_step, delay);
  57. } else {
  58. opts.onProcess && opts.onProcess(1);
  59. opts.onAnimationFinish && opts.onAnimationFinish();
  60. }
  61. };
  62. _step = _step.bind(this);
  63. animationFrame(_step, delay);
  64. }
  65. // stop animation immediately
  66. // and tigger onAnimationFinish
  67. Animation.prototype.stop = function() {
  68. this.isStop = true;
  69. };
  70. if (typeof module === "object" && typeof module.exports === "object") {
  71. module.exports = Animation;
  72. }