Context & History of Canvas Shape Drawing
The HTML <canvas> element was introduced in 2004 to give web pages a low‑level drawing surface. Early tutorials focused on static shapes such as rectangles and circles, but developers quickly discovered that the same API can generate any regular polygon by applying basic trigonometry. Over the years, the canvas has become a common playground for visual experiments, games, and data visualisation.
Implementation & Best Practices
Before writing code, outline the steps you need to follow: choose a centre point, decide on a radius, compute the angular step for the desired number of sides, and finally trace the path on the canvas. This roadmap keeps the function small and easy to test.
Calculating Vertex Positions
Each vertex lies at a distance r from the centre. The angle between consecutive vertices is (2π / sides). For a given index i, the rotation angle is ((Math.PI 2) / sides) i. Using Math.cos for the x‑offset and Math.sin for the y‑offset converts the polar coordinates to canvas coordinates.
Reusable drawShape Function
The following function accepts the centre coordinates (x, y), a radius (r) and the number of sides (sides). It translates the context, builds the path, strokes it, and then restores the original transform.
function drawShape(x, y, r, sides) {
ctx.translate(x, y)
for (let i = 0 i < sides i++) {
const angle = ((Math.PI 2) / sides) i
const px = r Math.cos(angle)
const py = r Math.sin(angle)
if (i === 0) ctx.moveTo(px, py)
else ctx.lineTo(px, py)
}
ctx.closePath()
ctx.stroke()
ctx.resetTransform()
}
Use the function to draw a triangle, a hexagon, or an octagon with a single call:
drawShape(100, 100, 50, 3) // triangle
drawShape(200, 100, 50, 6) // hexagon
drawShape(300, 100, 50, 8) // octagon
Extending the Core Idea
Once the basic polygon works, you can add an inner radius to create stars or diamonds, or replace lineTo with quadraticCurveTo for smoother edges. For large projects, keep the drawing logic separate from UI code and reuse the function across components.
For performance tips when working with many shapes, see the guide on accelerating JavaScript development with Bun. If you need to ensure the canvas works across browsers, consult the 2024 web interoperability report for up‑to‑date compatibility tables.