要制作一个具有动漫效果的圆点沿曲线的动画,并时刻显示圆点的坐标位置,你需要使用一个编程语言和库来实现这个功能。以下是使用Python和其流行的绘图库matplotlib来实现这一目标的一个基本示例。
示例:
-
使用以下代码创建一个简单的动画:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
# 定义曲线函数
def curve(t):
x = t * np.cos(2 * np.pi * t)
y = t * np.sin(2 * np.pi * t)
return x, y
# 初始化函数,设置初始圆点位置
def init():
point.set_offsets([(0, 0)]) # 设置初始位置为(0, 0)
return point,
# 动画更新函数,用于更新圆点的位置和坐标显示
def update(frame):
t = frame / 10 # 将帧数转换为时间
x, y = curve(t) # 计算曲线上的点坐标
point.set_offsets([(x, y)]) # 更新圆点的位置
ax1.text(x, y, f"({round(x, 2)}, {round(y, 2)})", ha="center", va="center", size=12) # 显示圆点的坐标位置
return point, ax1.texts[-1], # 返回圆点和其坐标文本,以便在下一帧中使用
# 创建图形和坐标轴
fig, ax = plt.subplots()
ax1 = plt.axes([0.025, 0.85, 0.95, 0.1]) # 创建一个用于显示坐标文本的子图区域
ax.set_xlim(-2, 2) # 设置x轴的范围
ax.set_ylim(-2, 2) # 设置y轴的范围
ax.grid(False) # 不显示网格线
ax1.axis('off') # 不显示子图区域的轴线
# 创建初始圆点和坐标文本对象
point = plt.Circle((0, 0), 0.1, fill=True, color='blue')
ax.add_artist(point) # 将圆点添加到图形中
point_label = ax1.text(0, 0, "") # 初始坐标文本对象
# 创建动画对象,设置参数和循环等属性
ani = animation.FuncAnimation(fig, update, frames=np.linspace(0, 100, 100), interval=50, blit=True)
ani.save("animated_curve.gif", writer="imagemagick") # 将动画保存为GIF文件,需要安装ImageMagick库
plt.show() # 显示图形和动画
运行上述代码。它应该会生成一个动态的曲线动画,其中有一个蓝色的圆点沿着曲线移动,并且在每个位置上都显示其坐标。动画还会保存为一个GIF文件。你可以根据需要调整代码以更改圆点的大小、颜色、速度、曲线形状
实验:
# animation为动画模块
%matplotlib notebook
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
# 0. 设置中文黑体
plt.rcParams["font.sans-serif"] = ["SimHei"]
plt.rcParams["axes.unicode_minus"] = False
# 1. 准备正弦曲线数据
shang = np.linspace(0, 2*np.pi, 100)
xia = np.sin(x)
# 2. 创建画布和坐标系
fig = plt.figure(tight_layout=True)
ax = fig.add_subplot(111)
# 3. 绘制正弦曲线,同时把曲线改成蓝色
ax.plot(shang, xia, color='b')
# 4(1). 动画设计,其中num代表当前动画的帧率
def chenduxiu(num):
point_ani.set_data(x[num], y[num])
text_pt.set_text("x=%.3f, y=%.3f"%(x[num], y[num]))
return point_ani,text_pt
# 4(2). 曲线上红色圆点设置
plt.plot(x,y)
point_ani, = plt.plot(x[0], y[0], "ro")
text_pt = plt.text(4, 0.9, '', fontsize=16)
# 4(3).制作动画,其中frames表示动画的长度,即曲线上红色圆点移动的范围,interval表示更新动画的频率,blit表示是否更新所有的点
ani = animation.FuncAnimation(fig, chenduxiu, frames=100, interval=90, blit=True)
# 5.将动画保存为gif图片(用于上传博客)
ani.save("pratice7.3.gif", writer='pillow')
# 6.展示图表
plt.show()