import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
# 设置画布
fig, ax = plt.subplots()
ax.set_xlim(-2, 2)
ax.set_ylim(-2, 2)
ax.set_aspect('equal')
ax.axis('off') # 隐藏坐标轴
# 初始化爱心图案
heart_line, = ax.plot([], [], lw=2, color='red')
# 爱心的参数方程
def heart(t):
x = 16 * np.sin(t)**3
y = 13 * np.cos(t) - 5 * np.cos(2*t) - 2 * np.cos(3*t) - np.cos(4*t)
return x / 20, y / 20 # 缩放爱心大小
# 初始化函数
def init():
heart_line.set_data([], [])
return heart_line,
# 更新函数,用于动画
def update(frame):
t = np.linspace(0, 2 * np.pi, 1000)
x, y = heart(t)
# 添加动态效果:旋转和缩放
angle = frame * 0.05 # 旋转角度
scale = 1 + 0.1 * np.sin(frame * 0.1) # 缩放效果
x_rot = x * np.cos(angle) - y * np.sin(angle)
y_rot = x * np.sin(angle) + y * np.cos(angle)
x_rot *= scale
y_rot *= scale
heart_line.set_data(x_rot, y_rot)
heart_line.set_color((np.sin(frame * 0.1) * 0.5 + 0.5, 0.2, 0.2)) # 颜色变化
return heart_line,
# 创建动画
ani = FuncAnimation(fig, update, frames=200, init_func=init, blit=True, interval=50)
# 显示动画
plt.show()