Last active
October 5, 2016 09:52
-
-
Save cgarnier/4799d76603b14c0d19184d4c8c081c10 to your computer and use it in GitHub Desktop.
Animate a svg path with TweenMax
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
/** | |
* Animate a dashed svg path | |
* @param el DOM path element | |
* @param width Width of the dashes | |
* @param space Space between the dashes | |
*/ | |
animateLine (el, width, space) { | |
let total = Math.floor(el.getTotalLength()) | |
let segment = [width, space] | |
console.log('total,', total) | |
var line = { | |
step: 0, | |
dashes: [0] | |
} | |
TweenMax.to(line, 2, { | |
step: total, | |
onUpdate: () => { | |
let dashNumber = line.dashes.reduce((a, b) => a + b, 0) | |
let missing = Math.floor(line.step) - dashNumber | |
let stuffing = 1 + total - (dashNumber + missing) | |
let index = line.dashes.length - 1 | |
while (missing > 0) { | |
if (line.dashes[ index ] === segment[index % 2]) { | |
line.dashes.push(0) | |
index++ | |
} | |
line.dashes[ index ]++ | |
missing-- | |
} | |
let finalArray = [].concat(line.dashes) | |
if (index % 2 === 0) { | |
finalArray.push(stuffing) | |
} else { | |
finalArray = finalArray.concat([width, Math.max(0, stuffing - width)]) | |
} | |
el.setAttribute('stroke-dasharray', finalArray.join(',')) | |
} | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment