# Animate a Line in Beamer

Following code must be changed into an animation. In the code where the "foreach" is, will be corresponding to one frame for each number, given 20 frames in total. Hence, when the animation is running the line is been drawn in real time.

\documentclass{standalone}
\usepackage{tikz}

\begin{document}
\begin{tikzpicture}

\path[use as bounding box] (0,0) rectangle (11.5,12);

\gdef\oldy{-2}
\foreach \x in {-2.9,-2.85,-2.8,...,-1.9}
{
\pgfmathsetmacro{\y}{0.2*rand-1.6}
\pgfmathsetmacro{\oldx}{\x-0.05}
\draw (\oldx+8.5,\oldy+11) -- (\x+8.5,\y+11);
\xdef\oldy{\y}
}

\end{tikzpicture}
\end{document}


The code so far. However, the line change for each iteration.

\documentclass{beamer}
\usepackage{tikz,animate}
\newcounter{upperbound}

\begin{document}

\begin{frame}
\frametitle{ABC}
\begin{animateinline}[%
controls,
begin={\begin{tikzpicture}
\foreach [count=\i] \j in {a,...,u}
\node [scale=0.02] (\j) at (\i*0.30,0+rand*0.2) {};},
end={\end{tikzpicture}}
]{5}
\multiframe{20}{iCount=2+1}{%
\setcounter{upperbound}{\iCount}
\foreach [remember=\j as \k (initially a)] \j in {b,...,\alph{upperbound}} {
\draw (\k) -- (\j);
}
}
\end{animateinline}
\end{frame}
\end{document}

• Is tex.stackexchange.com/questions/281354/… helpful? Oct 16, 2017 at 17:59
• Something like this. However everytime the code runs the \foreach in the multiframe block, the rand will be different. Hence, every time a new block of the line is added, the previous line there is ready drawn will change. Oct 17, 2017 at 9:47

Frames of the animated graph are built by repeatedly appending a new line segment to the previously saved state of the graph. Saving the states of a graph ensures that the random number is only calculated once per line segment. The solution makes use of the xsavebox package:

\documentclass{standalone}

\usepackage{tikz}
\usepackage{animate}
\usepackage{xsavebox}

\begin{document}

\gdef\oldy{-2}
%empty first frame:
\xsbox{mygraph}{\tikz \path[use as bounding box] (5.5,8.95) rectangle (6.6,9.65);}%

\begin{animateinline}[controls,scale=5]{8}
\xusebox{mygraph}
\newframe
\multiframe{20}{rx=-2.9+0.05}{%
\pgfmathsetmacro{\y}{0.2*rand-1.6}%
\xsbox{mygraph}{%
%repeat previous graph
\makebox[0pt][l]{\xusebox{mygraph}}%
%append new line segment
\begin{tikzpicture}
\path[use as bounding box] (5.5,8.95) rectangle (6.6,9.65);
\pgfmathsetmacro{\oldx}{\rx-0.05}
\draw [line cap=round] (\oldx+8.5,\oldy+11) -- (\rx+8.5,\y+11);
\end{tikzpicture}%
}%
\xusebox{mygraph}%
\xdef\oldy{\y}%
}
\end{animateinline}

\end{document}