Created
October 26, 2011 12:11
-
-
Save itsbth/1316172 to your computer and use it in GitHub Desktop.
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
from lxml.etree import parse | |
NS = {'svg': 'http://www.w3.org/2000/svg'} | |
CMD = 'ctx.{0}({1}, {2});' | |
FUN = r''' | |
function (ctx) {{ | |
ctx.save(); | |
ctx.beginPath(); | |
{0} | |
//ctx.closePath(); | |
ctx.stroke(); | |
ctx.restore(); | |
}}, | |
''' | |
def parse_poly(poly): | |
items = [] | |
lst = [p for p in poly.split(' ') if p] | |
items.append(CMD.format('moveTo', *lst[0].split(','))) | |
for point in lst: | |
items.append(CMD.format('lineTo', *point.split(','))) | |
return items | |
def parse_path(path): | |
items = [] | |
cx, cy = 0, 0 | |
for cmd in (c for c in path.split(' ') if c): | |
c, args = cmd[0], cmd[1:].split(',') if len(cmd) > 1 else [] | |
line = '#unknown' | |
if c == 'M': | |
cx, cy = args | |
line = 'ctx.moveTo({0}, {1});'.format(*args) | |
elif c == 'L': | |
cx, cy = args | |
line = 'ctx.lineTo({0}, {1});'.format(*args) | |
elif c == 'V': | |
cy = args[0] | |
line = 'ctx.lineTo({0}, {1});'.format(cx, args[0]) | |
elif c == 'H': | |
cx = args[0] | |
line = 'ctx.lineTo({0}, {1});'.format(args[0], cy) | |
elif c == 'Q' or c == 'C': | |
cx, cy = args[4:] | |
line = 'ctx.bezierCurveTo({0}, {1}, {2}, {3}, {4}, {5});'.format(*args) | |
elif c == 'Z': | |
line = 'ctx.closePath();' | |
else: | |
line = '//unknown({0}, #{1})'.format(c, len(args)) | |
items.append(line) | |
return items | |
def main(infile): | |
tree = parse(infile) | |
items = [] | |
for poly in tree.xpath('svg:g/svg:polygon/@points', namespaces=NS): | |
items.append(parse_poly(poly)) | |
for path in tree.xpath('svg:g/svg:path/@d', namespaces=NS): | |
items.append(parse_path(path)) | |
print("window.funs = [") | |
for item in items: | |
print(FUN.format(('\n ').join(item))) | |
print("];") | |
if __name__ == '__main__': | |
import sys | |
main(sys.argv[1]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment