x 2 + ( y − x 2 3 ) 2 = 1 x^2+(y-\sqrt[3]{x^2})^2=1 x2+(y−3x2 )2=1 将原函数变形: y = x 2 3 ± 1 − x 2 y=\sqrt[3]{x^2}\pm\sqrt{1-x^2} y=3x2 ±1−x2
显然,x的值域为:[-1,1] 在值域内取适当个x的值,并求出相应y的值,用描点法绘制曲线,填充颜色,即可得到一个心形图。 在此基础上进行扩展,对心形图的位置和大小设定随机参数,即可获得随机的多个心形图。
import random
import turtle
# import numpy as np
pen = turtle.Pen()
# pen.speed(10)
pen.ht()
'''pen.begin_fill() for i in range(360): i /= 180 / math.pi length = A * (1 - math.cos(i)) x, y = length * math.cos(i), length * math.sin(i) pen.goto(x, y) pen.end_fill()'''
# for i in range(360):
# i /= math.pi
# length = A * (1 - math.sin(i))
# x, y = length * math.cos(i), length * math.sin(i)
random.seed(100)
times = 100
# X = sorted((1 - np.random.random(times)))
X = [_ / times for _ in range(times)]
d = [[x ** (2 / 3), (1 - x ** 2) ** 0.5] for x in X]
pos = [None] * times * 4
for i in range(len(X)):
pos[i + times * 0] = [X[i], d[i][0] + d[i][1]]
pos[i + times * 1] = [X[-i - 1], d[-i - 1][0] - d[-i - 1][1]]
pos[i + times * 2] = [-X[i], d[i][0] - d[i][1]]
pos[i + times * 3] = [-X[-i - 1], d[-i - 1][0] + d[-i - 1][1]]
print('begin draw')
def draw(A=100, fillcolor='red', scale=1):
turtle.tracer(False)
start_x, start_y = pen.pos()
pen.seth(90)
pen.pu()
pen.goto(start_x, pos[0][1] * A + start_y)
pen.fillcolor(fillcolor)
pen.pd()
pen.begin_fill()
for x, y in pos:
pen.goto(x * scale * A + start_x, y * A + start_y)
pen.end_fill()
turtle.update()
def draw_more():
for i in range(100):
pen.pu()
pen.goto(random.randint(-900, 900), random.randint(-500, 500))
# pen.pd()
draw(A=random.randint(10, 100), fillcolor=random_color(), scale=1.2)
def hex_(num):
return f'{hex(num)[2:]:0>2}'
def random_color():
r, g, b = random.randint(200, 255), random.randint(0, 20), random.randint(0, 20)
return f'#{hex_(r)}{hex_(g)}{hex_(b)}'
turtle.Screen().delay(False)
pen.pencolor('snow')
for i in range(100):
draw_more()
pen.clear()
turtle.done()
注意描点的顺序,要保证连贯性,否则无法正常闭合,也就无法正常填充颜色。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/184226.html原文链接:https://javaforall.cn