Last active
September 1, 2022 18:55
-
-
Save okorz001/2a3cfc0c0ca30c52caeb0d6e1c97ae14 to your computer and use it in GitHub Desktop.
Generate SVG of regular polygons
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
#!/usr/bin/env python | |
import argparse | |
import math | |
parser = argparse.ArgumentParser(description=""" | |
Generates a SVG of a regular polygon. By default, a convex polygon is generated, | |
but the --advance option may be used to generate star polygons instead. | |
""") | |
parser.add_argument('points', type=int, metavar='POINTS', | |
help='the number of points') | |
parser.add_argument('--precision', type=int, default=3, metavar='DIGITS', | |
help='number of significant digits for rounding') | |
parser.add_argument('--scale', type=int, default=1, metavar='RADIUS', | |
help='the radius of the unit circle') | |
parser.add_argument('--transpose', action='store_true', | |
help='flip X and Y coordinates (start from the top)') | |
parser.add_argument('--stroke', type=int, default=0, metavar='WIDTH', | |
help='the width of the stroke (border)') | |
parser.add_argument('--rounded', action='store_true', | |
help='use rounded corners') | |
parser.add_argument('--advance', type=int, default=1, metavar='POINTS', | |
help='number of points to advance when drawing each line') | |
args = parser.parse_args() | |
def p(n): | |
rad = 2 * n / args.points * math.pi | |
if (args.transpose): | |
rad -= math.pi / 2 | |
return (round(args.scale * math.cos(rad), args.precision), | |
round(args.scale * math.sin(rad), args.precision)) | |
origin = -1 * (args.scale + args.stroke / 2) | |
size = 2 * args.scale + args.stroke | |
linejoin = 'round' if args.rounded else 'mitre' | |
path = "M " | |
for i in range(0, args.points * args.advance, args.advance): | |
path += " {0},{1}".format(*p(i % args.points)) | |
path += " z" | |
svg = f""" | |
<svg viewBox="{origin} {origin} {size} {size}"> | |
<path stroke-width="{args.stroke}" stroke-linejoin="{linejoin}" | |
d="{path}"/> | |
</svg> | |
""".strip() | |
print(svg) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Samples: https://codepen.io/okorz001/pen/jOmjJjp