Last active
July 7, 2016 19:01
-
-
Save revazi/a3cc6af77adb4d46349999eb993e225a to your computer and use it in GitHub Desktop.
SVG path animation function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* args = { | |
* infiniteLoop: true/false(default = false), | |
* loopCount: number of animation loop(default = 1), | |
* duration: seconds in integer(default = 2), | |
* transition: transition effect(default = linear) | |
* } | |
* | |
* Author: Revaz Zakalashvili | |
* Inspiration: https://jakearchibald.com/2013/animated-line-drawing-svg/ | |
* | |
*/ | |
function animateSvgPath(path, args) { | |
var length = path.getTotalLength(); | |
var count = 0; | |
const infiniteLoop = args.infiniteLoop ? args.infiniteLoop : false; | |
const duration = args.duration ? args.duration : 2; | |
const transition = args.transition ? args.transition : 'linear'; | |
const loopCount = args.loopCount ? args.loopCount : 1; | |
const infinite = args.infinite ? args.infinite : false; | |
(function(){ | |
function recursiveAnimator(){ | |
length = path.getTotalLength(); | |
// Clear any previous transition | |
path.style.transition = path.style.WebkitTransition = 'none'; | |
// Set up the starting positions | |
path.style.strokeDasharray = length + ' ' + length; | |
path.style.strokeDashoffset = length; | |
// Browser piicks up the starting position before animating | |
path.getBoundingClientRect(); | |
// Define transition | |
path.style.transition = path.style.WebkitTransition = 'stroke-dashoffset '+ duration +'s '+transition; | |
//Go! | |
path.style.strokeDashoffset = -1*length; | |
//if loop isn't infinite increment count | |
if(!infiniteLoop) { | |
count++; | |
if (count == loopCount) return 0; | |
} | |
//using the timout function to match the next call and animation duration | |
setTimeout(recursiveAnimator, duration*1000); | |
} | |
return recursiveAnimator(); | |
})(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment