Categories
JavaScript Answers

How to draw polygons on an HTML5 canvas with JavaScript?

Spread the love

Drawing polygons on an HTML5 canvas with JavaScript involves a few steps. Here’s a basic example:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Draw Polygons</title>
    <style>
        canvas {
            border: 1px solid black;
        }
    </style>
</head>
<body>
    <canvas id="myCanvas" width="400" height="400"></canvas>
    <script>
        // Get the canvas element
        var canvas = document.getElementById('myCanvas');
        var ctx = canvas.getContext('2d');

        // Define a function to draw a polygon
        function drawPolygon(x, y, sides, radius) {
            ctx.beginPath();
            ctx.moveTo(x + radius * Math.cos(0), y + radius * Math.sin(0));

            for (var i = 1; i <= sides; i++) {
                ctx.lineTo(x + radius * Math.cos(i * 2 * Math.PI / sides),
                           y + radius * Math.sin(i * 2 * Math.PI / sides));
            }

            ctx.closePath();
            ctx.stroke();
        }

        // Example usage
        drawPolygon(200, 200, 6, 100); // Draw a hexagon at (200, 200) with a radius of 100
        drawPolygon(100, 100, 5, 50);  // Draw a pentagon at (100, 100) with a radius of 50
    </script>
</body>
</html>

This code defines an HTML page with a canvas element and JavaScript to draw polygons on it.

The drawPolygon function takes parameters for the position of the center (x and y), the number of sides, and the radius.

It then calculates the coordinates of each vertex of the polygon using trigonometry and draws lines between them using the canvas context’s lineTo method.

Finally, it closes the path and strokes it to draw the polygon.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *