How to draw a hexagon using HTML5 and the canvas tag
If you want to draw a hexagonal shape in a web page, HTML5 provides a slick way to do so
Building on the previous example drawing a hexagon
we find the process is considerably easier using vectors and lines as a part of the HTML 5 canvas.
Here's an example showing how to draw a hexagonal shape using HTML5 and the canvas tag.
This example doesn't provide the CSS styling options from the previous hexagon drawing example, but
it is easier to use with regard to other programming operations you'll need to do if you are scripting
it for a game. For example, its logical to assume that something is supposed to be placed "inside" of the
shape, which is demonstrated here.
Tag and Code Example
The code used to create the example can be seen below.
The canvas tag is created on the DOM first.
There are some CSS style rules applied here using a class "my_canvas" simply to make it
match the color scheme here, but also to show that you can apply CSS styling to the canvas via the class or style html attributes.
The button uses a toggle state to keep track of whether the click should "clear" the canvas, or "draw" in the canvas.
I thought it might be helpful to see the context done here as well, but in hindsight I'm not a huge fan of doing the toggle here because
it pollutes the interaction with the canvas--your example probably doesn't need to draw or clear with a button.
My apologies for any confusion, I hope to re-factor this in the future to better isolate those two aspects.
Here's what this example does
- Create a canvas tag
- Set up a drawing context ("2D" meaning two dimensional)
- Set x and y variables
- Move through the changes to x and y needed to trace the shape of a hexagon
- Draw lines for any of the legs we need to show
- Set the drawing style characteristics such as color and line thickness
- Trigger the drawing to occur
- Add some text