Skip to content

Instantly share code, notes, and snippets.

@louisswarren
Last active March 4, 2021 01:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save louisswarren/cf7a1cd207f0a34180aa276e95ee73c0 to your computer and use it in GitHub Desktop.
Save louisswarren/cf7a1cd207f0a34180aa276e95ee73c0 to your computer and use it in GitHub Desktop.
Generate svg grids
import sys
from svg import *
def log(*a, **k):
print(*a, **k, file=sys.stderr)
GRID = int(sys.argv[1]) if len(sys.argv) > 1 else 6
GAP = 20
# Basic header
svg_header()
svg_open(width=8*GAP*(GRID+2), height=8*GAP*(GRID+2), x_bias=0, y_bias=0,
xw=GAP*(GRID+2), yh=GAP*(GRID+2))
for x in range(1, GRID + 2):
svg_line((GAP*x, 1), (GAP*x, GAP*(GRID + 1)+GAP-1), stroke='black')
for y in range(1, GRID + 2):
svg_line((1, GAP*y), (GAP*(GRID+1)+GAP-1, GAP*y), stroke='black')
# Footer
svg_close()
.PHONY: test
test: grid6.svg grid7.svg grid8.svg grid9.svg grid6.png grid7.png grid8.png grid9.png
grid%.svg: grid.py
python3 $^ $* > $@
%.png: %.svg
convert $^ $@
.PHONY: clean
clean:
rm -f *.png *.svg
def xml(tag, _xml_tag_is_a_singleton=True, **options):
s = f'<{tag}'
kw_attrib = lambda x: x.replace('_', '-')
if options:
s += ' '
s += ' '.join(f'{kw_attrib(k)}="{str(v)}"' for k, v in options.items())
if _xml_tag_is_a_singleton:
s += ' />'
else:
s += '>'
print(s)
def xml_open(*args, **kwargs):
xml(*args, **kwargs, _xml_tag_is_a_singleton=False)
def xml_close(tag):
print(f'</{tag}>')
def svg_header():
'<?xml version="1.0" encoding="UTF-8" standalone="no"?>'
def svg_open(width, height, x_bias, y_bias, xw, yh):
vb = f'{x_bias} {y_bias} {xw} {yh}'
ns = 'http://www.w3.org/2000/svg'
xml_open('svg', width=width, height=height, viewBox=vb, xmlns=ns)
def svg_close():
xml_close('svg')
def svg_poly(*points, **opts):
point_str = ' '.join(f'{x},{y}' for x, y in points)
xml('polyline', points=point_str, **opts)
def svg_circle(point, radius, **opts):
xml('circle', cx=point[0], cy=point[1], r=radius, **opts)
def svg_line(p1, p2, **opts):
xml('line', x1=p1[0], y1=p1[1], x2=p2[0], y2=p2[1], **opts)
def svg_rect(p, width, height, x_radius=0, y_radius=0, **opts):
xml('rect', x=p[0], y=p[1], width=width, height=height,
rx=x_radius, ry=y_radius, **opts)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment