[Tex/LaTex] Triangular numbers in TikZ

tikz-pgf

I need to draw an image of the first three triangular numbers inscribed in a square.

The first three triangular numbers

Now, I have two problems constructing this image.

  • Construct the circles perfectly centered
  • The shading

It is acceptable to answer only my first question (in order to correspond to the one question, one post policy) although I would be glad if someone answered both.

Now I have no minimal example, but in order to construct this image any packages would suffice, although my preference is for TikZ.

I am using a variety of packages, although I doubt any of them would interfere in the construction of this image.

  • Does anyone have any tips or suggestions for how to construct the first n triangular numbers inside a square (with "correct" shading)?

Best Answer

Try something like:

\documentclass{article}
\usepackage{tikz}

\newlength\radius
\pgfmathsetlength{\radius}{0.5cm}
\newcommand\drawballs[2][]{%
    \foreach \y [evaluate=\y as \yy using #2+1-\y] in {1,...,#2} {%
        \foreach \x in {1,...,\yy} {%
            \shade[shading=ball,ball color=white,#1] 
                ({(2*\x-2+\y)*\radius},{sqrt(3)*\y*\radius}) circle (\radius); 
        };
    }%
}

\begin{document}

\begin{tikzpicture}
    \drawballs{1}
    \drawballs[xshift=2cm]{2}
    \drawballs[xshift=5cm]{3}
\end{tikzpicture}

\end{document}

output of code