[Tex/LaTex] Tikz coordinates relative to a node, and outside it

coordinatesnodestikz-pgf

Given a rectangular node X I have access to the coordinates (X.north), (X.east) and the like. However, I want to be able to draw two sides of a right-angled triangle on top of the node. For example, if the node's top left and top right coordinates were (0,3) and (2,3) then I want to draw (0,3) -- (1,4) -- (2,3).

In other words:

\draw (X.north west) -- <what goes here?> -- (X.north east);

How do I obtain my middle point using only the node itself? The best I can do is

\draw (X.north west) -- ([shift={(X.north)}] X.north)-- (X.north east);

but that seems a little clumsy.

Best Answer

That's what the calc library is for:

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{calc}
\begin{document}
\begin{tikzpicture}
\node [draw] (X) {X node};
\draw (X.north west) -- ($(X.north west)!cos(45)!45:(X.north east)$) -- (X.north east);
\end{tikzpicture}
\end{document}

The syntax is as follows:

($(A)!<fraction>!(B)$) referst to the point that lies <fraction> of the way along the line from (A) to (B). ($(A)!0.5!(B)$) would refer to the midpoint of the connecting line, ($(A)!0!(B)$) refers to (A), and ($(A)!1!(B)$) refers to (B). If the number is greater than 1 or less than 0, the path is extrapolated.

The syntax ($(A)!<fraction>!<angle>:(B)$) refers to the point that lies <fraction> of the way along the line from (A) to (B) after that line has been rotated around (A) by <angle> degrees.

For a right-angled triangle, we know that if the angle between the hypotenuse and the adjacent side is 45°, the length of the adjacent side is cos(45)*h.

Similarly for other angles:

\documentclass[border=5mm]{standalone}
\usepackage{tikz}
\usetikzlibrary{calc}
\begin{document}
\begin{tikzpicture}
\node [draw, outer sep=0pt] (X) {X node};
\foreach \angle in {15,30,...,75}{
    \draw [red!\angle!blue] (X.north west) -- ($(X.north west)!cos(\angle)!\angle:(X.north east)$) -- (X.north east);
}
\end{tikzpicture}
\end{document}