TikZ-PGF – Techniques for Managing Overlapping Fills

tikz-pgf

I would like to create a graphic representing a stack of rectangles. I would ideally like a simple command like \stack{5} to create a stack of 5.

I can use the following code:

\draw[fill=blue] (0.4,-0.4) rectangle +(3,2);
\draw[fill=blue] (0.3,-0.3) rectangle +(3,2);
\draw[fill=blue] (0.2,-0.2) rectangle +(3,2);
\draw[fill=blue] (0.1,-0.1) rectangle +(3,2);
\draw[fill=blue] (0.0,-0.0) rectangle +(3,2);

enter image description here

However, it seems hard to turn that into a command, and if we need to shift the stack around it is a hassle to change all of the coordinates. I was thinking this might be better:

\draw[fill=blue] (0.4,-0.4)
  rectangle +(3,2) ++(-0.1,0.1)
  rectangle +(3,2) ++(-0.1,0.1)
  rectangle +(3,2) ++(-0.1,0.1)
  rectangle +(3,2) ++(-0.1,0.1)
  rectangle +(3,2) ++(-0.1,0.1);

enter image description here

This has the advantage that shifting it around only changes the coordinates in one obvious place, and it is even a little more clear about what is intended.

Unfortunately, this second version fills all the rectangles first, and then draws their outlines, so the "top" rectangle does not cover the rest of the stack.

Is there a simple way to draw overlapping regions using relative draw commands?

Best Answer

Here's a solution that exploits the fact that paths constructed using the edge command are separate and thus are drawn separately. An edge path is as flexible as a to path so can be adapted to draw just about anything, including a rectangle. So we define a new to path and an edge style that invokes. it.

\documentclass{article}
%\url{http://tex.stackexchange.com/q/68555/86}
\usepackage{tikz}

\tikzset{
  edge rectangle/.style={
    to path={ rectangle (\tikztotarget)}
  }
}

\begin{document}
\begin{tikzpicture}
\draw[every edge/.append style={edge rectangle,fill=blue}] (0.4,-0.4)
  edge +(3,2) ++(-0.1,0.1)
  edge +(3,2) ++(-0.1,0.1)
  edge +(3,2) ++(-0.1,0.1)
  edge +(3,2) ++(-0.1,0.1)
  edge +(3,2) ++(-0.1,0.1);
\end{tikzpicture}
\end{document}

This results in the following:

stacked rectangles via edge commands

Related Question