Lately I have been more interested in the reactivity of VueJS to generate svg shapes as components. Components offer a fantastic way to re-use code and also share functionality between apps and/or services.
I found a nice little utility csshexagon.com made by Brenna github.com/brenna that generates a CSS hexagon based on it's width. That seemed like a fantastic idea and I played around with the demo for quite some time because it was that much fun to use.
I wanted to make a monogram of my initials and print it to PDF as part of a side project I currently busy with but printing CSS margins and weird positioning ended up breaking the shape.
I created a Vue component to render svg points in a hexagon, fill the background and render your initials in the center .
I reached for SVG since it's well supported and allows for lots of flexibility when trying to do custom things. The experiment I attempted was that SVG would play well with VueJS. Also crafting shapes as components that automatically builds out the internals of the SVG based on an initial starting point (like width) would be really cool.
To build a hexagon monogram as a SVG you need a couple of things.
- Initial width
- 6 points or coordinates
- Calculated height
- Letters to generate the monogram with
- Background color
All of those are sent through as component config via props but to calculate the 6 coordinates is not that arbitrary.
The finished product first:
A hexagon is a polygon with point coordinates in a viewbox of a fixed size. The coordinates will be generated starting at (0,0) on the top left and stretches to (width, autoHeight) on the bottom right. To get a visually appealing shape, the height will be a little bit more than the width.
The calculations uses Pythagoras#In_mathematics to
calculate the points as horizontal and vertical movement along the shape. If the width is
80, you start with the top point being half the full width and zero at the topmost point. We also want a 30deg drop on all the diagonal sides to make the shape visually looking nice.
You will see that the
<polygon points="..." is where we need to calculate those
using the width. Lets work through the 6 points and how I got to them, starting
at the top point of the hexagon, they are broken up as indexed (x,y)
coordinates. All values will be rounded up to 2 decimal points.
The component to render a hexagon shaped monogram is straight forward.
<monogram width="80" letters="EM" :primary-color="primaryColor" />
width: The pixel width that you want and is required. It acts as the starting condition and all the SVG points and sides are calculated from that initially.
letters: A string of two letters that will render in the middle of the shape.
primary-color: Is the string CSS color value that you want the background fill to be.
This will render a nicely scaled hexagon with your properties.