新生动感爱心代码来了(pyrhon)

相信很多刚上大学的小伙伴已经逐步开始学python了,旺仔当年也是从python是起手,并且也是从爱心开始绘制自己的第一个图像啦。话不多说,先来看看效果图:

我们本次主要用到了matplotlib模块和numoy模块,分别用于绘图,和矩阵运算绘制图画。

注意这里可能要添加这一段代码,atplotlib.use('TkAgg')matplotlib.use('Qt5Agg') 的作用是指定 Matplotlib 使用的图形后端(backend)。后端是 Matplotlib 用于绘图和显示图形的接口,不同的后端支持不同的功能和表现。我开始使用的pyahcarm默认后端不是这样的,可能会导致不兼容从而无图像显示。

matplotlib.use('TkAgg')  # 尝试 'Qt5Agg' 如果 'TkAgg' 无效

原码如下:

import matplotlib
matplotlib.use('TkAgg')  # 尝试 'Qt5Agg' 如果 'TkAgg' 无效
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from matplotlib.patches import Circle, Polygon

# 设置随机种子以确保星星位置每次运行一致
np.random.seed(42)

# 创建星星数据
num_stars = 100
stars_x = np.random.uniform(-20, 20, num_stars)
stars_y = np.random.uniform(-20, 20, num_stars)
stars_size = np.random.uniform(20, 100, num_stars)
stars_alpha_initial = np.random.uniform(0.5, 1.0, num_stars)

# 创建画布
fig, ax = plt.subplots(figsize=(8, 8))
ax.set_xlim(-30, 30)
ax.set_ylim(-30, 30)
ax.set_facecolor('black')
ax.axis('off')  # 隐藏坐标轴

# 绘制星星
stars = ax.scatter(stars_x, stars_y, s=stars_size, c='white', alpha=stars_alpha_initial)


# 心形参数方程
def heart_curve(t, scale=1):
    x = scale * 16 * np.sin(t) ** 3
    y = scale * (13 * np.cos(t) - 5 * np.cos(2 * t) - 2 * np.cos(3 * t) - np.cos(4 * t))
    return x, y


# 初始化心形
t = np.linspace(0, 2 * np.pi, 1000)
x, y = heart_curve(t, scale=1)
heart_line, = ax.plot(x, y, lw=2, color='red')

# 创建填充心形的多边形
verts = np.column_stack((x, y))
polygon = Polygon(verts, closed=True, facecolor='red', edgecolor='none', alpha=0.6)
ax.add_patch(polygon)

# 添加发光效果
glow = Circle((0, 0), 0.1, color='pink', alpha=0.6, zorder=1)
ax.add_patch(glow)

# 初始化颜色映射
cmap = plt.get_cmap('hot')


# 更新函数
def update(frame):
    # 更新心形大小(脉动效果)
    scale = 1 + 0.1 * np.sin(frame * 0.1)
    x, y = heart_curve(t, scale)

    # 更新心形线条
    heart_line.set_data(x, y)

    # 更新填充心形的多边形
    verts = np.column_stack((x, y))
    polygon.set_xy(verts)


    # 更新发光效果大小和透明度
    glow.set_radius(0.1 + 0.05 * np.sin(frame * 0.1))
    glow.set_alpha(0.6 + 0.2 * np.sin(frame * 0.1))

# 创建动画
ani = FuncAnimation(fig, update, frames=200, interval=50, blit=False)

# 显示动画
plt.show()

                                                                                                                                                                                          

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值