Python跳动蓝色爱心代码
时间: 2025-04-07 09:12:58 浏览: 39
要在Python中实现一个“跳动的蓝色爱心”,可以借助`matplotlib`库来进行动画效果绘制。下面是一个简单的示例代码:
```python
import numpy as np
from matplotlib import pyplot as plt
from matplotlib.animation import FuncAnimation
# 定义爱心形状函数
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, y
fig, ax = plt.subplots()
ax.set_xlim(-20, 20)
ax.set_ylim(-20, 20)
line, = ax.plot([], [], lw=2, color='blue') # 蓝色线条表示爱心
def init():
line.set_data([], [])
return line,
scale_factor = [i / 10 for i in range(1, 20)] + [i / -10 for i in range(19, 0, -1)]
def animate(i):
t = np.linspace(0, 2 * np.pi, 1000)
x, y = heart(t)
factor = scale_factor[i]
scaled_x = x * factor
scaled_y = y * factor
line.set_data(scaled_x, scaled_y)
return line,
ani = FuncAnimation(fig, animate, frames=len(scale_factor), interval=50, blit=True, init_func=init)
plt.axis('off')
plt.show()
```
**解释**:
1. 使用了`t=np.linspace()`生成一系列角度值,并通过`heart()`函数计算出对应的x、y坐标点,形成心形曲线。
2. `FuncAnimation`用于创建动态效果——让心脏随着比例因子缩放而呈现跳跃感。
注意运行此程序之前需要安装好所需的模块如numpy与matplotlib等依赖项!
阅读全文
相关推荐
















