Advertisement
Guest User

Untitled

a guest
Apr 25th, 2019
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.30 KB | None | 0 0
  1. /**
  2. * Initialize animation on an SVG path or set of paths, this returns a controller
  3. * object
  4. *
  5. * var lines = animate({
  6. * parent: "#someElement",
  7. * selector: ".theActualLines",
  8. * duration: 2500
  9. * })
  10. *
  11. * Then kick off the animation by calling play() on the controller:
  12. *
  13. * lines.play()
  14. *
  15. * animate accepts the following options:
  16. *
  17. * @param {String} paths A selector describing a set of SVG path elements
  18. * @param {Number} duration Duration of the animation in milliseconds
  19. * @param {Object} args - An object containing the following
  20. * @param {String} args.selector - A selector string describing a set of SVG path elements
  21. * @param {Number} [args.duration=1500] - Duration of the animation in milliseconds
  22. * @param {Boolean|String} [args.loop=false] - Loop the animation or not
  23. * @return {Object}
  24. */
  25. var animate = function(args) {
  26. var duration =
  27. args.duration !== undefined ? parseInt(args.duration, 10) : 1500,
  28. parent = args.parent !== undefined ? args.parent : "body",
  29. pathNodes = $(parent).find(args.selector),
  30. easing = 1.8;
  31. /**
  32. * QuerySelectorAll returns a nodeList, which doesn't support forEach/map/filter/reduce iteration
  33. */
  34. for (var n = 0; n < pathNodes.length; n++) {
  35. var len = pathNodes[n].getTotalLength();
  36. pathNodes[n].style.strokeDasharray = len - 1 + " " + len;
  37. pathNodes[n].style.strokeDashoffset = len;
  38. pathNodes[n].setAttribute("data-length", len);
  39. }
  40.  
  41. var getEndTime = function() {
  42. return new Date().getTime() + duration;
  43. };
  44.  
  45. var controller = {
  46. endTime: false
  47. };
  48.  
  49. controller.play = function() {
  50. var ratio, offset;
  51.  
  52. if (controller.endTime === false) {
  53. controller.endTime = getEndTime();
  54. }
  55.  
  56. ratio = Math.max(0, controller.endTime - new Date().getTime()) / duration;
  57.  
  58. for (var n = 0; n < pathNodes.length; n++) {
  59. var len = pathNodes[n].getAttribute("data-length");
  60. offset = len * Math.pow(ratio, easing);
  61. pathNodes[n].style.strokeDashoffset = offset;
  62. }
  63.  
  64. if (args.loop && ratio <= 0) {
  65. ratio = 1;
  66. controller.endTime = getEndTime();
  67. }
  68.  
  69. if (ratio > 0) {
  70. window.requestAnimationFrame(controller.play);
  71. }
  72. };
  73. return controller;
  74. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement