# Can I change colors within a \draw?

I was hoping to draw something like the following:

And I can by using \draw twice:

\documentclass{standalone}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}[line width=1mm]
\draw[fill=red](0,0)rectangle(4,4)--(8,8);
\draw[fill=blue](8,8)rectangle(12,12);
\end{tikzpicture}
\end{document}


However I was hoping to do this with a single \draw. I can do this easily if both of the squares were the same color. à la,

\documentclass{standalone}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}[line width=1mm,fill=red]
\draw(0,0)rectangle(4,4)--(8,8)rectangle(12,12);
\end{tikzpicture}
\end{document}


But I can't figure out how to get two differently colored shapes with a single draw. Is there a way to change colors partway through a draw?

• Is it an alternative to use nodes instead of rectangles? Feb 8 '17 at 16:00
• @TorbjørnT. I am not sure what you mean, I would like to draw rectangles, if this can be attained with nodes I am interested. Feb 8 '17 at 16:04
• According to the pgfmanual, \draw is \path[draw], rectangle is a (sub)path, and colour options anywhere in the path apply to the whole path, with the last option winning. So working with nodes is the way to go. Feb 8 '17 at 16:27
• What is the advantage of doing this in one draw? -something to do with line joints? Feb 8 '17 at 23:07
• @hpekristiansen I am trying to code golf in tikz. :p Feb 8 '17 at 23:14

You could perhaps draw a line from (0,0) to (4,4) and add a node at each end.

\documentclass{standalone}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}[line width=1mm,every node/.style={outer sep=0pt,minimum size=2cm}]
\draw(0,0) node[draw=black,fill=red,below left] {} -- (4,4) node[draw=black,fill=blue,below left] {};
\end{tikzpicture}
\end{document}


You could try with customized arrow tips (from arrows.meta)

\documentclass[tikz,border=2mm]{standalone}
\usetikzlibrary{arrows.meta}

\begin{document}
\begin{tikzpicture}
\draw[{Turned Square[open, fill=red, length=1cm]}
-
{Turned Square[open, fill=blue, length=1cm]}]
(0,0)--(4,4);
\end{tikzpicture}
\end{document}