Slide for animation with beamer an TikZ

animationsbeamerenvironmentstikz-pgf

With the commands \pause of beamer and \foreach of tikz together is possible to create slides that work as layers for an animation in video.

For example:

\documentclass{beamer}
\usepackage{pgf,tikz}

\begin{document}

\begin{frame}[fragile]
    \begin{tikzpicture}
        \foreach \x in {1,2,...,4}{
            \only<\x>{
                \clip (0,0) rectangle (8,4.5);
                \draw[line width=6pt] (0,0) rectangle (8,4.5);
                \fill (2*\x,\x) circle  (.2); % animated object
            }
        }
    \end{tikzpicture}
\end{frame}

\end{document}

I would like to create a new environment as follows:

\documentclass{beamer}
\usepackage{pgf,tikz}

\newenvironment{animation}[1]{
    \begin{frame}
    \begin{tikzpicture}
        \foreach \x in {1,2,...,#1}{
            \only<\x>{
}{
            }
        }
    \end{tikzpicture}
    \end{frame}
}

\begin{document}


\begin{animation}{4}
    \clip (0,0) rectangle (8,4.5);
    \draw[line width=6pt] (0,0) rectangle (8,4.5);
    \fill (2*\x,\x) circle  (.2);
\end{animation}

\end{document}

But doing it this way doesn't work. Would anyone know how this can be done? Whether it can be done?

Best Answer

Try with \NewDocumentEnvironment:

\documentclass{beamer}
\usepackage{pgf,tikz}
\NewDocumentEnvironment{animation}{m +b}{
    \begin{frame}
    \begin{tikzpicture}
        \foreach \x in {1,2,...,#1}{
            \only<\x>{#2}
        }
    \end{tikzpicture}
    \end{frame}
}{}  


\begin{document}
\begin{animation}{4}
    \clip (0,0) rectangle (8,4.5);
    \draw[line width=6pt] (0,0) rectangle (8,4.5);
    \fill (2*\x,\x) circle  (.2);
\end{animation}
\end{document}

enter image description here