SVG Polygon Generator: Coding Tutorial for Custom Shapes

Faraz

By Faraz -

Learn how to build an SVG Polygon Generator using HTML, CSS, and JavaScript. Customize and generate dynamic polygon shapes for your web projects.


Create Your Own SVG Polygon Generator using HTML, CSS, and JavaScript.jpg

Table of Contents

  1. Project Introduction
  2. HTML Code
  3. CSS Code
  4. JavaScript Code
  5. Preview
  6. Conclusion

In the rapidly evolving landscape of web design and development, graphic elements play a pivotal role in captivating users and delivering seamless user experiences. Scalable Vector Graphics (SVG) have emerged as a powerhouse, enabling developers to craft intricate graphics that adapt flawlessly to various screen sizes. Within the realm of SVG, polygons stand out as versatile shapes that find applications in everything from decorative designs to data visualization. In this comprehensive tutorial, we will embark on a journey to demystify the creation of an SVG Polygon Generator using the foundational trio of web technologies: HTML, CSS, and JavaScript.

This tutorial is designed to guide you through the process of conceiving, coding, and perfecting an SVG Polygon Generator. We'll delve into each facet of the development process, ensuring that you not only grasp the how but also the why. By the end of this journey, you'll be equipped not only with a functional generator but also with a deeper understanding of SVGs and the collaborative power of HTML, CSS, and JavaScript.

In the subsequent sections, we will walk through the practical steps, code snippets, and conceptual insights that constitute the creation of an SVG Polygon Generator. From setting up the initial HTML structure to crafting intricate polygons through code, we'll leave no stone unturned. Additionally, we'll explore strategies to elevate user experience by allowing customization and real-time updates.

Are you ready to embark on this voyage into the realm of SVG, where shapes come alive through code and creativity knows no bounds? Let's dive in!

Source Code

Step 1 (HTML Code):

To get started, we will first need to create a basic HTML file. In this file, we will include the main structure for our polygon generator.

After creating the files just paste the following codes into your file. Make sure to save your HTML document with a .html extension, so that it can be properly viewed in a web browser.

Let's break down the code step by step to understand its structure and purpose:

1. <!DOCTYPE html>: This declaration specifies that the document is an HTML5 document.

2. <html lang="en">: The opening tag for the HTML document. The lang attribute indicates that the content is in English.

3. <head>: This section contains meta-information and links to external resources used in the document.

  • <title>: Sets the title of the web page to "SVG Polygon Generator".
  • <meta charset="UTF-8" />: Declares the character encoding for the document as UTF-8, which supports a wide range of characters.
  • <meta name="viewport" content="width=device-width" />: Specifies how the content should be displayed on different devices, adapting to their screen widths.
  • <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/tachyons/4.6.2/tachyons.min.css">: This links to an external CSS file (Tachyons CSS library) that provides pre-styled classes for consistent and responsive design.
  • <link rel="stylesheet" href="styles.css" />: Another link to an external CSS file named "styles.css" (assumed to be in the same directory as the HTML file).

4. <body>: The main content of the web page resides within this tag.

5. <main class="...">: This is the main content area of the page, with various CSS classes that style and position its contents.

  • pa4 dark-gray mw7 center sans-serif min-vh-100 flex flex-column flex-row-ns items-center: These are Tachyons CSS classes that control padding, colors, flex layout, and responsiveness of the main content area.

6. <form class="...">: A form element that allows users to input parameters for generating a polygon.

  • measure-wide mr4-ns mb4 mb0-ns f5: Tachyons classes defining the width, margins, and font size of the form.

7. <fieldset class="...">: A fieldset that groups related form elements together.

  • ba b--transparent pa0 mh0: Tachyons classes for styling the fieldset without borders and adjusting padding/margin.
  • <legend>: Defines a title for the fieldset.
  • Various form elements for setting the number of sides, radius, and center coordinates of the polygon.

8. <div>: A div containing a button to generate the polygon.

  • <input class="..." id="js-generate" type="button" value="Generate">: A button with Tachyons classes and an ID attribute "js-generate" that is used to trigger polygon generation.

9. <div class="...">: A div that holds the generated SVG polygon and its corresponding data.

  • <svg>: An SVG element for displaying scalable vector graphics.
  • Various attributes and styles defining the SVG's size, stroke color, fill, and other properties.
  • <polygon>: An SVG polygon element that will represent the generated polygon. The "points" attribute will be populated dynamically using JavaScript.

10. <pre id="js-result" class="..."></pre>: A preformatted text element (typically used to display code) where the generated polygon data will be shown.

11. <script src="script.js"></script>: A reference to an external JavaScript file named "script.js" for handling the logic of the SVG Polygon Generator.

This is the basic structure of our polygon generator using HTML, and now we can move on to styling it using CSS.

Step 2 (CSS Code):

Once the basic HTML structure of the generator is in place, the next step is to add styling to the generator using CSS.

Let me break down what it does:

1. pre: This is a CSS selector targeting the HTML "pre" element. The "pre" element is used to define preformatted text, such as code or other content that should be displayed in a fixed-width font and maintain its whitespace formatting.

2. overflow-wrap: break-word;: This is a CSS property that is being applied to the targeted "pre" element. The overflow-wrap property controls how text should be wrapped when it overflows the boundaries of its container. In this case, it is set to break-word, which means that if a single word is too long to fit within the container's width, it will be broken into multiple lines so that it fits without causing horizontal scrolling. This helps to prevent the word from overflowing the container and potentially disrupting the layout.

pre { 
  overflow-wrap: break-word;
} 

Step 3 (JavaScript Code):

Finally, we need to create a function in JavaScript.

Let's break down the code step by step:

1. The code starts by selecting various HTML elements using the document.querySelector method. These elements are identified by their respective IDs and will be used to interact with the user interface:

  • sideCountEl, radiusEl, cxEl, cyEl: Input elements for the number of sides, radius, x-coordinate, and y-coordinate of the polygon.
  • generateEl: A button element that triggers the polygon generation.
  • polygonEl: An SVG polygon element to visualize the generated polygon.
  • resultEl: A DOM element that displays the generated SVG polygon tag as text.
  • svgEl: The SVG container element.

2. The pts function calculates the vertex coordinates of a regular polygon given its number of sides and radius. It calculates the angle between each vertex based on the number of sides, and then uses trigonometry to find the Cartesian coordinates of each vertex.

3. The range function generates an array of indices from 0 to count - 1. This function is a simple utility used in the pts function.

4. The degreesToRadians function converts an angle from degrees to radians, which is necessary for trigonometric calculations.

5. The polygon function takes the center coordinates (cx and cy), the number of sides (sideCount), and the radius of the polygon. It generates the vertex coordinates using the pts function, and then maps them to Cartesian coordinates relative to the center of the polygon.

6. The generatePolygon function is the main logic behind generating and displaying the polygons. It extracts values from the input fields (side count, radius, center coordinates), calculates a suitable SVG container size (s), generates vertex coordinates for both the actual polygon and the visualization polygon, sets the SVG container's viewbox, updates the polygonEl to visualize the polygon, and updates the resultEl with the SVG polygon tag.

7. The generateEl.onclick and window.onload event handlers ensure that the generatePolygon function is called both when the "Generate" button is clicked and when the window (web page) finishes loading.

Create a JavaScript file with the name script.js and paste the given codes into your JavaScript file and make sure it's linked properly to your HTML document so that the scripts are executed on the page. Remember, you’ve to create a file with .js extension.

const sideCountEl = document.querySelector('#js-side-count');
const radiusEl = document.querySelector('#js-radius');
const cxEl = document.querySelector('#js-cx');
const cyEl = document.querySelector('#js-cy');
const generateEl = document.querySelector('#js-generate');
const polygonEl = document.querySelector('#js-polygon');
const resultEl = document.querySelector('#js-result');
const svgEl = document.querySelector('#js-svg');

function pts(sideCount, radius) {
  const angle = 360 / sideCount;
  const vertexIndices = range(sideCount);
  const offsetDeg = 90 - (180 - angle) / 2;
  const offset = degreesToRadians(offsetDeg);

  return vertexIndices.map(index => {
    return {
      theta: offset + degreesToRadians(angle * index),
      r: radius };

  });
}

function range(count) {
  return Array.from(Array(count).keys());
}

function degreesToRadians(angleInDegrees) {
  return Math.PI * angleInDegrees / 180;
}


function polygon([cx, cy], sideCount, radius) {
  return pts(sideCount, radius).
  map(({ r, theta }) => [
  cx + r * Math.cos(theta),
  cy + r * Math.sin(theta)]).

  join(' ');
}

function generatePolygon() {
  const sideCount = +sideCountEl.value;
  const radius = +radiusEl.value;
  const cx = +cxEl.value;
  const cy = +cyEl.value;
  const s = 2 * radius + 50;

  const res = polygon([cx, cy], sideCount, radius);
  const viz = polygon([s / 2, s / 2], sideCount, radius);

  svgEl.setAttribute('viewBox', `0 0 ${s} ${s}`);
  polygonEl.setAttribute('points', viz);
  resultEl.innerText = `<polygon points="${res}" />`;
}

generateEl.onclick = generatePolygon;
window.onload = generatePolygon;

Final Output:

Create Your Own SVG Polygon Generator using HTML, CSS, and JavaScript.gif

Conclusion:

Congratulations! You've unlocked the potential of SVG polygons using HTML, CSS, and JavaScript. Armed with this newfound knowledge, you can embark on a creative journey to design visually striking shapes that enrich your web projects.

Remember, the SVG Polygon Generator you've built is just the tip of the iceberg. Explore further, experiment with various parameters, and watch your designs come to life in the browser!

Credit: Varun Vachhar

That’s a wrap!

I hope you enjoyed this post. Now, with these examples, you can create your own amazing page.

Did you like it? Let me know in the comments below 🔥 and you can support me by buying me a coffee.

And don’t forget to sign up to our email newsletter so you can get useful content like this sent right to your inbox!

Thanks!
Faraz 😊

End of the article

Subscribe to my Newsletter

Get the latest posts delivered right to your inbox


Latest Post