Tutorial Request: drawing multi sided polygons w/ Bezier Curves
-
Hello!
I'm still a bit new to programmatic drawing and I was curious about writing scripts to make multi-sided polygons such as triangles, hexagons, etc. using the BezierPath() method.
My math skills are rather rusty at this point so I'd love some pointers.
Thanks!
-
hello @micahmicah,
regular polygons can be described using vectors.
a vector has a length and an angle.
in regular polygons:
- all sides have the same length
- the sum of all external angles is 360°
here is a simple example in code:
# define polygon parameters x, y = 300, 200 sides = 5 perimeter = 1640 angleStart = 0 angleTotal = 360 autoclose = True # calculate side length & angle side = perimeter / sides angleStep = abs(angleTotal / sides) # convert angles to radians! angleStep = radians(angleStep) angleStart = radians(angleStart) # create the polygon shape B = BezierPath() angle = angleStart for i in range(sides): # this is the crucial part: # use trigonometry to calculate point B # from point A, angle, and distance x += cos(angle) * side y += sin(angle) * side if i == 0: B.moveTo((x, y)) else: B.lineTo((x, y)) angle += angleStep if autoclose: B.closePath() fill(0, 1, 1) strokeWidth(30) lineCap('round') lineJoin('round') stroke(1, 0, 1) drawPath(B)
-
bonus: Turtle
from turtle import * x, y = 300, 200 sides = 7 side = 100 angleTotal = 360 angleStep = abs(angleTotal / sides) Screen() t = Turtle() for i in range(sides): t.forward(side) t.left(angleStep) done()
↳ run this script in Terminal or SublimeText
-
Thank you so much!