Blog post image

How to Draw Any Regular Shape with a Single JavaScript Function

Web Development

Interactive graphics are a powerful way to bring your website or web app to life. Whether you are building a small business landing page, a data visualization dashboard, or an educational tool, being able to draw shapes dynamically on an HTML canvas gives you a lot of creative flexibility. In this article, you’ll learn how to use one reusable JavaScript function to draw any regular polygon—triangles, squares, pentagons, hexagons, and more—and how to adapt it so you can render multiple shapes with minimal code.


Key Takeaways

  • You can draw any regular polygon on an HTML5 <canvas> element with a single, parameter-driven JavaScript function.
  • A regular polygon is defined by its center point, radius, number of sides, rotation, and style (stroke/fill).
  • Using angles and trigonometry (Math.cos and Math.sin) lets you calculate each vertex of the shape.
  • Encapsulating this logic in a function makes your code easier to maintain, reuse, and extend.
  • You can loop over configuration objects to draw multiple shapes in a clean, scalable way.

Understanding the Building Blocks: Canvas and Regular Polygons

What Is a Regular Polygon?

A regular polygon is a shape where:

  • All sides are the same length.
  • All interior angles are equal.

Common examples include:

  • 3 sides: equilateral triangle
  • 4 sides: square
  • 5 sides: regular pentagon
  • 6 sides: regular hexagon

To draw any of these shapes programmatically, you only need a few parameters:

  • Center point: (centerX, centerY)
  • Radius: distance from the center to each vertex
  • Number of sides: e.g., 3, 4, 5, 6…
  • Rotation (optional): how much to rotate the shape in radians or degrees

HTML Canvas Basics

The HTML5 <canvas> element provides a drawing surface in the browser. JavaScript can access its 2D context and issue drawing commands such as lines, arcs, and fills. A minimal setup looks like this:

<canvas id="myCanvas" width="500" height="500"></canvas>

<script>
  const canvas = document.getElementById('myCanvas');
  const ctx = canvas.getContext('2d');
</script>

Once you have the ctx context, you can begin drawing paths, strokes, and fills. That’s where your reusable regular-shape function will plug in.


Core Logic: One Function to Draw Any Regular Shape

The goal is to create one function that can draw any regular polygon by adjusting the parameters you pass to it. Conceptually, the function will:

  1. Start a new path.
  2. Compute the angle between each vertex.
  3. Loop through each vertex, using cosine and sine to get its position.
  4. Connect the vertices with lines.
  5. Optionally close and fill the shape, and/or stroke its outline.

The Shape-Drawing Function

Here is a clean, reusable function that implements this logic:

function drawRegularPolygon(ctx, centerX, centerY, radius, sides, options = {}) {
  if (sides < 3) return; // need at least a triangle

  const {
    rotation = 0,       // in radians
    strokeStyle = '#000',
    fillStyle = null,   // null means no fill
    lineWidth = 1
  } = options;

  const angleStep = (Math.PI * 2) / sides;

  ctx.save();
  ctx.beginPath();

  for (let i = 0; i < sides; i++) {
    const angle = rotation + i * angleStep;
    const x = centerX + radius * Math.cos(angle);
    const y = centerY + radius * Math.sin(angle);

    if (i === 0) {
      ctx.moveTo(x, y);
    } else {
      ctx.lineTo(x, y);
    }
  }

  ctx.closePath();

  ctx.lineWidth = lineWidth;
  ctx.strokeStyle = strokeStyle;
  if (fillStyle) {
    ctx.fillStyle = fillStyle;
    ctx.fill();
  }
  ctx.stroke();
  ctx.restore();
}

Key points about this implementation:

  • Parameter-driven: you can change the number of sides, color, rotation, and size without touching the function’s core logic.
  • Options object: using an options object keeps the function call readable and extendable.
  • Trigonometry: Math.cos and Math.sin convert an angle and radius into (x, y) coordinates.

Using the Function: Drawing a Single Shape

Once your function is defined, drawing a shape is straightforward. For example, to draw a blue hexagon in the center of a 500×500 canvas:

const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');

drawRegularPolygon(ctx, 250, 250, 100, 6, {
  strokeStyle: '#0044cc',
  fillStyle: '#66a3ff',
  lineWidth: 3,
  rotation: Math.PI / 6 // rotate 30 degrees
});

Change 6 to 3 for a triangle, 4 for a square, 5 for a pentagon, and so on. Adjust the radius to scale the shape, and the center coordinates to reposition it.


Scaling Up: Drawing Multiple Shapes with the Same Function

In real projects, you rarely draw just one shape. You might want a grid of icons, a background pattern, or interactive elements that respond to user input. Rather than copying and pasting draw calls everywhere, you can keep your code organized by iterating over a configuration array.

Multiple Shapes with a Configuration Array

Define your shapes as data, then loop through them:

const shapes = [
  {
    centerX: 100,
    centerY: 100,
    radius: 40,
    sides: 3,
    options: { strokeStyle: '#c0392b', fillStyle: '#e74c3c', rotation: 0 }
  },
  {
    centerX: 250,
    centerY: 100,
    radius: 50,
    sides: 4,
    options: { strokeStyle: '#16a085', fillStyle: '#1abc9c', rotation: Math.PI / 4 }
  },
  {
    centerX: 400,
    centerY: 100,
    radius: 60,
    sides: 5,
    options: { strokeStyle: '#8e44ad', fillStyle: '#9b59b6', rotation: 0 }
  },
  {
    centerX: 250,
    centerY: 250,
    radius: 80,
    sides: 6,
    options: { strokeStyle: '#f39c12', fillStyle: '#f1c40f', rotation: Math.PI / 6 }
  }
];

const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');

shapes.forEach(shape => {
  drawRegularPolygon(
    ctx,
    shape.centerX,
    shape.centerY,
    shape.radius,
    shape.sides,
    shape.options
  );
});

This approach has several benefits:

  • Maintainability: You can add, remove, or change shapes by editing data, not logic.
  • Reusability: The same function works across different modules and pages.
  • Extensibility: You can add more properties later (e.g., hover behavior, labels, or animation parameters).

Practical Enhancements for Real Projects

Once you have the basic function working, there are several ways to extend it for production use in small business or startup projects.

Handling Resize and Responsive Layouts

If your canvas needs to adapt to different screen sizes, you can:

  • Resize the canvas when the window resizes.
  • Recalculate the shape positions based on the new dimensions.
  • Use percentages or relative coordinates instead of fixed pixels when computing centers and radii.

Adding Interactivity

To make your shapes interactive (for example, as part of a custom chart or clickable UI element), you can:

  • Track shape configurations in an array.
  • Listen for mousedown or mousemove events on the canvas.
  • Convert mouse coordinates into canvas coordinates.
  • Implement hit detection (e.g., using the same geometry or ctx.isPointInPath).

Animating Shapes

You can animate rotation, size, or color using requestAnimationFrame:

  • Clear the canvas each frame with ctx.clearRect.
  • Update shape properties (e.g., rotation += 0.01).
  • Redraw all shapes using the same drawRegularPolygon function.

Common Pitfalls and How to Avoid Them

When you first start drawing shapes with canvas and JavaScript, a few issues can show up:

  • Forgetting to close the path: If your polygons look "open," ensure ctx.closePath() is called before filling or stroking.
  • Wrong angle units: Canvas trigonometry uses radians, not degrees. Convert degrees to radians with degrees * Math.PI / 180.
  • Overlapping or clipped shapes: Double-check canvas size versus positions and radii.
  • State leaking between drawings: Use ctx.save() and ctx.restore() to prevent style settings from unintentionally affecting other shapes.

Conclusion: Reusable Shape Drawing for Flexible Interfaces

By wrapping the geometry of regular polygons into a single, flexible JavaScript function, you can draw virtually any regular shape you need on an HTML canvas. This approach reduces duplication, centralizes your drawing logic, and makes it easier to scale from one shape to many without rewriting code.

Whether you are experimenting with custom icons, building interactive charts, or adding subtle motion graphics to your small business site, this simple pattern—"data in, shapes out"—is a solid foundation for more advanced canvas work.


Need Help Turning Canvas Demos into Production-Ready Features?

If you are looking to integrate dynamic graphics, interactive dashboards, or custom visual components into your web application and want clean, maintainable implementation, Izende Studio Web can help you plan and build it the right way.

Explore web development and application services at Izende Studio Web

Share this article:

support@izendestudioweb.com

About Izende Studio Web

Izende Studio Web provides website design, managed hosting, SEO, and digital support for small businesses in St. Louis and beyond.

Need Help With Your Website?

Explore website design, managed hosting, SEO, and practical digital support for your business.

Request a Quote