Triangles and arrows are one of the most used glyphs in modern web designs. In this article we are going to discuss 3 techniques to draw both of them, defining some customizable properties like thickness, orientation and color.
The most common technique for drawing triangles is to create an empty div (with both width and height equal to zero) and use its borders to create the arrow tip. The solution is based on the fact that borders in HTML elements join with 45° junctions. If we draw one of the borders and set its adjacent borders to be transparent, we can easily obtain the desired triangle. To create right-triangles, for example, it’s sufficient to draw the left border and set both top and bottom borders to be transparent, as shown in the following snippet.
This solution is compatible with all modern browsers (including ie8) and is very flexible, since colors and thickness can be easily changed by modifying CSS entries.
CSS arrows (rotation)
Drawing arrows may be a little more tricky, but we can still use div borders for our goal. If we draw two adjacent borders choosing the same colour and rotate the figure properly, we can obtain an arrow pointing everywhere we want. The complexity in this case is to create a cross-browser solution, since ie8 needs an image transform matrix to perform the rotation.
This solution offers the advantage to be compatible in all browsers and the ability to customize arrow direction (for further information see Matrix Filter documentation, rotation example section with customizable costheta and sintheta values). Unfortunately, since the arrow tip is obtained with a div angle, it is limited to be a 90° angle.
An interesting technique to draw arrows is to use HTML canvas. Thanks to canvas, we can draw lines of with arbitrary thickness, colors and angles. This solution is very flexible since we can draw any kind of shape. Unfortunately, canvas are not supported from ie8 and we need to add an excanvas library call to our code, which slows down page load. Secondly, canvas don’t naturally fit to their content, so we must manually set up their dimensions. The following example shows how to use canvas to draw arrows.
In this post we have seen 3 techniques to draw triangles and arrows in HTML documents. Each of them has strenghts and drawbacks, so it’s up to you to choose what is the best for your needs. As always, if you know better solutions for this argument we can freely discuss about them in comments. Thanks for your attention and see you soon!