我需要制作一些相当简单的动画,但我还需要一个滑块来让用户以交互方式更改动画的参数。我希望它在网上发生;即,如果用户在播放动画时更改了参数,则动画应该从旧动态平滑过渡到新动态。
到目前为止,我已经编写了一个接受参数并制作动画的函数。但在我之前提到的意义上,它不是交互式的。我的代码中没有滑块或任何真正交互的东西。尽管如此,动画部分至少运行顺利。
这是我的代码的简化版本:一个点围绕中心旋转,距中心指定距离r
和角速度w
。用户可以将它们作为参数来查看动画。(如果您在代码中看到从未使用过的内容,请不要为之烦恼,这可能是因为我忘记将其从原始代码中删除,因为它更长。)
import numpy as np
%matplotlib notebook
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
def simplified_code(w,r):
fps = 36
M = int(.75*fps*2*np.pi/w)
T_final = 2*np.pi/w*16
def positions(t):
x = r*np.cos(w*t)
y = r*np.sin(w*t)
return x,y
fig = plt.figure()
ax = fig.add_subplot(111, aspect='equal', autoscale_on=False, )
ax.grid()
# position
x_e, y_e = [], []
# trajectory and center
traj_e, = plt.plot([],[],'-g',lw=1)
e, = plt.plot([], [], 'ok')
# time
time_text = ax.text(0.02, 0.95, '', transform=ax.transAxes)
def init():
ax.set_xlim(-(r+0.5), (r+0.5))
ax.set_ylim(-(r+0.5), (r+0.5))
ax.plot([0], ms=7, c='k',marker='o')
return d,e,traj_e
def update(frame):
x,y = positions(frame)
x_e.append(x)
y_e.append(y)
traj_e.set_data(x_e[-M:], y_e[-M:])
e.set_data(x, y)
time_text.set_text('time = %.1f' % frame)
return traj_d,traj_e,d,e, orb
return FuncAnimation(fig, update, frames=np.linspace(0, T_final, T_final*fps),
init_func=init, blit=True, interval=1./36*1000)
请注意,可以停止动画,通过滑块更改参数并重新运行。我想避免动画中的这种暂停。我会很感激任何帮助。