Title: Draw a chrysanthemum curve in Python
This program uses the following equations to draw the chrysanthemum curve:
The program loops variable t through the values 0 to 21π to generate the curve's points. It connects those points with lines of various colors to draw the curve.
draw_chrysanthemum_curve
The program uses tkinter to create a Canvas widget and then calls the following draw_chrysanthemum_curve method to draw the curve.
def draw_chrysanthemum_curve(self):
'''Draw the chrysanthemum curve.'''
# Define some colors.
colors = [
'Pink',
'Red',
...
'Violet',
]
# Scale and translate.
ymax = -11
ymin = 11
hgt = ymin - ymax
wid = hgt
self.window.update()
canvas_wid = self.canvas.winfo_width()
canvas_hgt = self.canvas.winfo_height()
scale = min(canvas_wid / wid, canvas_hgt / hgt)
dx = canvas_wid / 2
dy = canvas_hgt / 2
# Draw the curve.
num_lines = 5000
period = 21
# Generate the points.
t = 0
r = 5 * (1 + math.sin(11 * t / 5)) \
- 4 * math.pow(math.sin(17 * t / 3), 4) \
* math.pow(math.sin(2 * math.cos(3 * t) - 28 * t), 8)
pt1 = (dx + scale * r * math.sin(t), dy + scale * (-r) * math.cos(t))
dt = math.pi / num_lines
for i in range(num_lines + 1):
t = i * period * dt
r = 5 * (1 + math.sin(11 * t / 5)) \
- 4 * math.pow(math.sin(17 * t / 3), 4) \
* math.pow(math.sin(2 * math.cos(3 * t) - 28 * t), 8)
pt0 = pt1
pt1 = (dx + scale * r * math.sin(t), dy + scale * (-r) * math.cos(t))
self.canvas.create_line(pt0, pt1, fill=colors[int(t / math.pi)])
This method first creates a list of color names. It then defines some drawing parameters. The curve is bounded by the values -11 < x,y < 11. The code gets the canvas's dimensions and creates a scale factor to map the region -11 < x,y < 11 onto the canvas. The values cx and cy define the canvas's center.
Having defined the drawing parameters, the code loops through the desired number of line segments. For each, it calculates a value for t and plugs it into the equation for r. It uses the r value to calculate X and Y coordinates, suitably scaled and translated to center the curve on the canvas, and connects that point to the previous one.
To give each line segment an interesting color, the code divides t by π, truncates the result, and uses it as an index into the colors list. The value of t lies between 0 and 21π, so the color index lies between 0 and 21. The colors list holds 24 entries, so the index should be valid. (If you use more points for t, you can use the modulus operator % to keep the index within the list's bounds.)
Conclusion
This post just shows how to draw an interesting and colorful curve. Download the example to experiment with it and to see additional details.
|