[Tex/LaTex] TikZ: Intersection of two lines

intersectionstikz-pgf

what is the easiest way to determine the intersection of two lines? I tried

\usetikzlibrary{intersections}
\begin{tikzpicture}[every node/.style={black,above right}]
\draw[name path=line 1] (0,0) -- (2,2);
\draw[name path=line 2] (2,0) -- (0,2);
\fill[red,name intersections={of=line 1 and line 2}]
    (intersection-1) circle (2pt) node {1}
    (intersection-2) circle (2pt) node {2}
\end{tikzpicture}

enter image description here

Best Answer

The reason the code does not work as provided is that there is only one intersection, and so (intersection-2) does not exist. One way to alleviate this kind of issue is to specify total=\t to contain the total number of intersections and the use a foreach to loop through each intersection:

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{intersections}

\begin{document}
\begin{tikzpicture}[every node/.style={black,above right}]
\draw[name path=line 1] (0,0) -- (2,2);
\draw[name path=line 2] (2,0) -- (0,2);
\fill[red,name intersections={of=line 1 and line 2,total=\t}]
    \foreach \s in {1,...,\t}{(intersection-\s) circle (2pt) node {\footnotesize\s}};
\end{tikzpicture}
\end{document}