Created
August 7, 2015 03:13
-
-
Save nydame/4c15673dee68828f0afc to your computer and use it in GitHub Desktop.
Scale an SVG path element with a simple javascript function
This file contains hidden or 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
function scalePathUp(path, num) { | |
// make sure num is > 0 and DOM element path has "d" attribute | |
if ( num <= 0 || typeof path.getAttribute("d") !== "string" ) {return false;} | |
var coords = [], | |
fragmentsAr = [], | |
idx, | |
jdx, | |
kdx, | |
lettersAr = [], | |
pattern = /[achlqstvz]/gi, | |
pathD = path.getAttribute("d"), | |
start = 0, | |
subfragAr = []; | |
// preserve original d | |
path.setAttribute("originalD", pathD); | |
// Find fragments of d starting at any of the following letters: A,a,C,c,H,h,L,l,Q,q,S,s,T,t,V,v,Z or z (see SVG Path spec). First fragment can start with anything (M or m expected). | |
// | |
// start by listing each occurence of one of these letters | |
lettersAr = pathD.match(pattern); | |
// slice d into fragments, each of which starts with one of these letters | |
for (idx = 0; idx < lettersAr.length; idx++) { | |
fragmentsAr.push( pathD.slice( start, pathD.indexOf( lettersAr[idx]) ) ); | |
start = pathD.indexOf( lettersAr[idx] ); | |
}; | |
// don't forget the last one... | |
fragmentsAr.push( pathD.slice( start)); | |
// for each fragment that doesn't start with M or m, create an array of strings that were separated by spaces; the first one should just be a letter, but the others are expected to be floating-point numbers (typically 2) separated by a comma(s) | |
for (idx = 0; idx < fragmentsAr.length; idx++) { | |
if (fragmentsAr[idx].charAt(0) === 'M' || fragmentsAr[idx].charAt(0) === 'm') {continue;} | |
subfragAr = fragmentsAr[idx].split(" "); | |
// split up the pairs (or larger groups) of numbers | |
for (jdx = 0; jdx < subfragAr.length; jdx++) { | |
coords = subfragAr[jdx].split(","); | |
// finally do the multiplication on each number; ignore non-numbers | |
for (kdx = 0; kdx < coords.length; kdx++) { | |
if ( parseFloat(coords[kdx]) == coords[kdx] ) { | |
coords[kdx] *= num; // AT LAST! | |
} | |
}; | |
// squish new numbers back together into comma-separated groups (typically pairs) | |
subfragAr[jdx] = coords.join(","); | |
}; | |
// squish strings back together separated by spaces | |
fragmentsAr[idx] = subfragAr.join(" "); | |
}; | |
// assemble new "d" from updated fragments | |
pathD = fragmentsAr.join(""); | |
path.setAttribute("d", pathD); | |
return true; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment