We drew an ellipse centered at origin without tilt. In this project, we will draw a general ellipse that can be centered at any location and any tilt angle. The parametric equation for this general ellipse is as follows:
x = cx + a*math.cos(t)*math.cos(math.radians(angle))-b*math.sin(t)*math.sin(math.radians(angle))
y = cy + a*math.cos(t)*math.sin(math.radians(angle))+b*math.sin(t)*math.cos(math.radians(angle))
(cx, cy) is the coordinate of the center of the ellipse. angle is the tilt angle of the ellipse. Range parameter t from 0 to 2π gradually to draw general ellipses.
Solution:
import turtle
import math
screen = turtle.Screen()
screen.setup(1000,1000)
screen.title("General Ellipse with Parametric Equation - PythonTurtle.Academy")
screen.tracer(0,0)
turtle.speed(0)
turtle.hideturtle()
turtle.up()
n = 2000
# (cx,cy): center of ellipse, a: width, b:height, angle: tilt
def ellipse(cx,cy,a,b,angle):
# draw the first point with pen up
t = 0
x = cx + a*math.cos(t)*math.cos(math.radians(angle))-b*math.sin(t)*math.sin(math.radians(angle))
y = cy + a*math.cos(t)*math.sin(math.radians(angle))+b*math.sin(t)*math.cos(math.radians(angle))
turtle.up()
turtle.goto(x,y)
turtle.down()
turtle.color('red')
# draw the rest with pen down
for i in range(n):
x = cx + a*math.cos(t)*math.cos(math.radians(angle))-b*math.sin(t)*math.sin(math.radians(angle))
y = cy + a*math.cos(t)*math.sin(math.radians(angle))+b*math.sin(t)*math.cos(math.radians(angle))
turtle.goto(x,y)
t += 2*math.pi/n
ellipse(-200,-100,200,100,45)
ellipse(200,100,40,200,80)
turtle.update()