Created
August 24, 2014 19:35
-
-
Save wchargin/5211cb5bf78770e50da1 to your computer and use it in GitHub Desktop.
SVG to Processing.JS
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
# svg2pjs - SVG to Processing.JS converter | |
import re | |
def command(s, last=None, lastcp=None, scale=1.0): | |
first = s[0] | |
absolute = first.istitle() | |
first = first.lower() | |
if first == 'z': | |
return 'endPath();' | |
points = [float(x) * scale for x in s[1:].split(',')] | |
if not absolute: | |
for i in xrange(len(points)): | |
points[i] += last[i % 2] | |
newControl = points[-4:-2] if len(points) >= 4 and first in 'cs' else None | |
newPoint = points[-2:] if len(points) >= 2 else last | |
points = ', '.join(map(str, points)) | |
if first == 'm' or first == 'l': | |
return 'vertex({0});'.format(points), newPoint, None | |
elif first == 'c': | |
return 'bezierVertex({0});'.format(points), newPoint, newControl | |
elif first == 's': | |
lastcpx = ', '.join(map(str, lastcp)) | |
return 'bezierVertex({0}, {1});'.format(lastcpx, points), newPoint, newControl | |
else: | |
return '// {0}'.format(s), last, lastcp | |
def color(hexval): | |
r = int(hexval[0:2], 16) | |
g = int(hexval[2:4], 16) | |
b = int(hexval[4:6], 16) | |
return 'fill({0}, {1}, {2});'.format(r, g, b) | |
def path(text): | |
text = re.sub(r'(\d)-(\d)', r'\1,-\2', text) | |
match = re.match(r'<path fill="#?([^"]*)" d="([^"]*)" ?/>', text) | |
fill = match.group(1) | |
d = match.group(2) | |
if re.match(r'[A-Fa-f0-9]{6}', fill): | |
print color(fill) | |
else: | |
print 'noFill();' | |
commandpoints = re.split('([A-Za-z])', d)[1:-2] # take off 'z'; added later | |
commands = [commandpoints[i] + commandpoints[i+1] for i in xrange(0, len(commandpoints), 2)] | |
point = None | |
cp = None | |
for c in commands: | |
a, point, cp = command(c, point, cp, 1.0) | |
print a |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment