3

I want to draw a cube with TikZ. But when I make the edge thicker, the cube turns out to be: enter image description here

and here is the code:

\begin{tikzpicture}

\draw[black,line width=2pt] (0,2,0) -- (2,2,0) -- (2,2,2) -- (0,2,2) -- (0,2,0) --cycle; \draw[black,line width=2pt] (0,2,2) -- (2,2,2) -- (2,0,2) -- (0,0,2) -- (0,2,2) --cycle; \draw[black,line width=2pt] (2,2,2) -- (2,2,0) -- (2,0,0) -- (2,0,2) -- (2,2,2) --cycle;

\end{tikzpicture}

Is there any easy way to clip the “rag", or is there any other way to draw a cube?

piper39
  • 53
  • There is this thread here: https://tex.stackexchange.com/questions/12020/what-is-the-easiest-way-to-draw-a-3d-cube-with-tikz – anis Jan 02 '23 at 08:55
  • More precisely, this answer here: https://tex.stackexchange.com/a/30102/216067 you can see that they used multiple scopes to defined 3 squares. – anis Jan 02 '23 at 08:58
  • 1
    I add [line join=round] after \begin{tikzpicture} and fix the problem – piper39 Jan 02 '23 at 09:14
  • There's also https://tex.stackexchange.com/q/21054/86 – Andrew Stacey Jan 02 '23 at 10:08

2 Answers2

2

I am answering this, as I can not see this solution in any of the other posts about cubes.

First draw the convex hull of the cube and then draw all other line segments with line cap=round, so that they do not protrude the border.

\documentclass[tikz, border=1cm]{standalone}
\begin{document}
\begin{tikzpicture}[line width=2pt]
\draw (0,2,0) -- (2,2,0) -- (2,0,0) -- (2,0,2) -- (0,0,2) -- (0,2,2) -- cycle;
\draw[line cap=round] (2,2,2) -- (0,2,2) (2,2,2) -- (2,0,2) (2,2,2) -- (2,2,0);
\end{tikzpicture}
\end{document}

A cube

Drawing everything with line join=round will round over all corners of the cube, which dependent on use case might be acceptable. One advantage of this is that it does not matter in which order things are drawn.

Edit: Actually line cap=round is not needed at all. The default line cap=butt will not protrude. For other shapes with more acute outer angles, it might be needed to clip the additional line segments.

1

A cube with Mathcha.

\documentclass[a4paper,12pt]{article}
\usepackage{tikz}

\begin{document} \tikzset{every picture/.style={line width=0.75pt}} \begin{tikzpicture}[x=0.75pt,y=0.75pt,yscale=-1,xscale=1] \draw [line width=1.5] (206,177.74) -- (253.94,129.8) -- (372.8,129.8) -- (372.8,241.66) -- (324.86,289.6) -- (206,289.6) -- cycle ; \draw [line width=1.5] (372.8,129.8) -- (324.86,177.74) -- (206,177.74) ; \draw [line width=1.5] (324.86,177.74) -- (324.86,289.6) ; \end{tikzpicture} \end{document}

enter image description here

Sebastiano
  • 54,118