[Tex/LaTex] TikZ: Intersection for Fraction Diagram

fractionstikz-pgf

I am trying to create fraction diagrams for children using TikZ.

Is there an elegant way to fix the top of this diagram of 1/2 in a way that will scale when I want to show, say 29/6 with triangles… and eventually other shapes? It seems that intersections of paths that meet at non-90 degree angles don't quite intersect the way I want them to…

Messed up picture

\documentclass{article}

\usepackage{tikz}
\usepackage{xcolor}

\begin{document}

\(\frac{1}{2}\)

\begin{tikzpicture}
\filldraw[fill=gray, draw=black, thick] (0,0)--(1,0)--(1,2)--cycle;
\draw[thick] (1,0)--(2,0)--(1,2)--cycle;
\end{tikzpicture}

\end{document}

Best Answer

I am not sure if this is what you want, but looking at the linked image, it seems to be so: I borrowed some code from Ignasi's answer to How to draw triangular grid in TikZ?. Since the triangular grid is built with \nodes, you can easily use their anchors to do the filling, which I placed in the background layer:

enter image description here

The code:

\documentclass[tikz,border=2mm]{standalone}
\usetikzlibrary{shapes,backgrounds}

\newcommand\grid[1]{
\foreach \i [count=\row from 0, remember=\row as \lastrow (initially 0)] in {0,...,#1}
  {
  \foreach \j [count=\column from 0, remember=\column as \lastcolumn (initially 0)] in {0,...,\i}
    {
    \ifnum\row=0
      \node[tri](0-0) {};
    \else
      \ifnum\column=0
        \node[tri, anchor=north](\row-0) at (\lastrow-0.corner 2) {};
      \else
         \node[tri, anchor=north](\row-\column) at (\lastrow-\lastcolumn.corner 3) {};
      \fi
    \fi
    }
  }
}

\begin{document}

\begin{tikzpicture}[
tri/.style={
  draw,
  regular polygon,
  regular polygon sides=3, 
  minimum size=2cm, 
  inner sep=0pt,
  outer sep=0pt,
  line width=1pt
  }
]
\grid{3}
\begin{pgfonlayer}{background}
  \filldraw[cyan!30] 
    (0-0.corner 1) -- 
    (3-3.corner 3) -- 
    (3-0.corner 2) -- 
    cycle;
\end{pgfonlayer}

\begin{scope}[xshift=8cm]
\grid{3}
\begin{pgfonlayer}{background}
  \filldraw[cyan!30] 
    (3-0.corner 1) -- 
    (3-3.corner 1) -- 
    (3-3.corner 3) -- 
    (3-0.corner 2) -- 
    cycle;
\end{pgfonlayer}
\end{scope}

\begin{scope}[yshift=-8cm]
\grid{3}
\begin{pgfonlayer}{background}
  \filldraw[cyan!30] 
    (2-0.corner 1) -- 
    (2-2.corner 1) -- 
    (3-1.corner 3) -- 
    cycle;
\end{pgfonlayer}
\end{scope}

\begin{scope}[xshift=8cm,yshift=-8cm]
\grid{3}
\begin{pgfonlayer}{background}
  \filldraw[cyan!30] 
    (0-0.corner 1) -- 
    (3-1.corner 3) -- 
    (3-0.corner 2) -- 
    cycle;
\end{pgfonlayer}
\draw[line width=1pt]
  (0-0.corner 1) -- (3-1.corner 3);
\end{scope}
\end{tikzpicture}

\end{document}