So maybe you need to draw a pentagon? or a hexagon? How about just a simple equilateral triangle? Any of those seemingly basic primitive regular polygons that you learned about back in geometry class. The Canvas API is extremely powerful and enables you to draw just about anything with Javascript. But that doesn’t mean that the Canvas provides a simple API for every shape that you might want to draw. In fact, the Canvas API provides almost no simple shape drawing outside of rectangles. Rather the Canvas API provides a set of very powerful and flexible basic drawing functions based on the path abstraction that can be used to draw just about anything. But in order to wield the Canvas properly, you have to have a good understanding of the APIs and sometimes a tad bit of trigonometry.
In this article, I’m going to show you how to not only draw an arbitrary regular polygon, but we’ll also be delving deeper to understand the algorithm and the math behind the code and hopefully in the process providing a better understanding of how to use the HTML5 Canvas API.