Explain Codes LogoExplain Codes Logo

How to draw polygons on an HTML5 canvas?

html
canvas
javascript
math-functions
Anton ShumikhinbyAnton Shumikhin·Dec 31, 2024
TLDR

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:

let canvas = document.getElementById('myCanvas'); let ctx = canvas.getContext('2d'); ctx.beginPath(); ctx.moveTo(50, 50); // Ascending to the peak ctx.lineTo(100, 150); // Uh-oh, slippery slope! ctx.lineTo(0, 150); // Pulling a 180! ctx.closePath(); // Safe! We're back where we started. ctx.stroke(); // Got the outline, just like a cartoon character!

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:

function drawRegularPolygon(ctx, centerX, centerY, sides, size) { ctx.beginPath(); const angleStep = (2 * Math.PI) / sides; // Starting point: License to chill at center. ctx.moveTo( centerX + size * Math.cos(0), centerY + size * Math.sin(0) ); // The rest: Around we go, better not puke! for (let i = 1; i <= sides; i++) { ctx.lineTo( centerX + size * Math.cos(angleStep * i), centerY + size * Math.sin(angleStep * i) ); } ctx.closePath(); ctx.fill(); }

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:

ctx.strokeStyle = 'blue'; ctx.lineWidth = 3; ctx.stroke();

No more "still life" art. Let's animate those polygons with events like click or mousemove:

canvas.addEventListener('mousemove', function(event) { // Redraw polygon: Following the mouse like a stalker! });

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:

CanvasRenderingContext2D.prototype.fillPolygon = function(vertices) { this.beginPath(); this.moveTo(vertices[0].x, vertices[0].y); vertices.slice(1).forEach(vertex => { this.lineTo(vertex.x, vertex.y); }); this.closePath(); this.fill(); };