How to draw polygons on an HTML5 canvas?
To draw polygons on an HTML5 canvas, start the path with beginPath()
, plot your polygon's vertices using an initial moveTo()
and subsequent lineTo()
calls. closePath()
completes the shape, then you render it with stroke()
or fill()
. Consider this basic triangle example:
Mix up these coordinates to sketch any polygon. Just mind the start and end points for a visually pleasing result.
Exploring the math behind polygons
Going beyond triangles, loops and math functions help us plot the vertices. Especially for regular polygons, we can plant vertices like seeds in an orange slice:
Using Math.cos()
and Math.sin()
, points are evenly spaced to create a perfect star. Tweak the size
, centerX
, centerY
, and sides
to customize your twinkling polygon.
Styling and interaction: The cool kids
A dab of style spruces up your polygons with a vibrant edge. ctx.strokeStyle
and ctx.lineWidth
mark the borders:
No more "still life" art. Let's animate those polygons with events like click
or mousemove
:
Going rogue with complex polygons
For more intricate polygons with custom sides, drop automatic loops. Instead, connect each vertex with utmost precision. Don't mix up the coordinates' order, else you'll get unintended abstract art.
Encapsulating the logic in a custom fillPolygon
CanvasRenderingContext2D
method simplifies your drawing:
Was this article helpful?