Math Mode Color – How to Strike Through or Cancel Using Different Colors in the Same Line

cancelcolormath-modestrikeout

For example, suppose I had an equation

x = 2 + 1 – 2 – 1 (obviously toy example)

I want the +2 to cancel out with the -2, +1 to cancel out with the -1

So in Latex I would want something like

enter image description here

Is there a simple way to implement multi-colored strike through or cancel in Latex?

enter image description here

A similar question is found here but it is for global coloring
crossing out using different colour

Best Answer

One possibility is to use cancel. (EDIT: Replaced \textcolor by color, big thanks to Werner!)

\documentclass{article}
\usepackage{cancel,xcolor}
\newcommand{\Cancel}[2][black]{{\color{#1}\cancel{\color{black}#2}}}
\begin{document}
\[x~=~\Cancel[blue]{2}+\Cancel[red]{1}-
 \Cancel[blue]{2}-\Cancel[red]{1}\]
\end{document}

enter image description here

Note, however, that an ambient color will be without effect, i.e. instead of {\color{green}\Cancel[blue]{2}+\Cancel[red]{1}} you'd need to do \Cancel[blue]{\color{green} 2}+\Cancel[red]{\color{green} 1} unfortunately. I guess that there will be better ways and am looking forward to learn new tricks.

EDIT: Just for fun: a TikZ version. The option X will do an \xcancel sort of cross out.

\documentclass{article}
\usepackage{tikz}
\newif\ifCancelX
\tikzset{X/.code={\CancelXtrue}}
\newcommand{\Cancel}[2][]{\relax
\ifmmode%
  \tikz[baseline=(X.base),inner sep=0pt] {\node (X) {$#2$};
  \tikzset{#1}
  \draw[#1,overlay,shorten >=-2pt,shorten <=-2pt] (X.south west) -- (X.north east);
  \ifCancelX
    \draw[#1,overlay,shorten >=-2pt,shorten <=-2pt] (X.north west) -- (X.south east);   
  \fi}
\else
  \tikz[baseline=(X.base),inner sep=0pt] {\node (X) {#2};
  \tikzset{#1}
  \draw[#1,overlay,shorten >=-2pt,shorten <=-2pt] (X.south west) -- (X.north east);
  \ifCancelX
    \draw[#1,overlay,shorten >=-2pt,shorten <=-2pt] (X.north west) -- (X.south east);
  \fi}%
\fi}

\begin{document}
\[x~=~\Cancel[blue,X]{2}+\Cancel[red]{\frac{1}{2}}-
 \Cancel[blue]{2}-\Cancel[red, line width=1pt]{\frac{1}{2}}\]
\end{document}

enter image description here