Creating a polygon with N equal sides and angles: A step-by-step guide

Has anyone found a solution for determining the SVG path of a regular polygon based on the number of sides, as well as the width and height of the wrapper-container?

Any guidance would be greatly appreciated!

Thank you, Best.

Note: The number of sides (N) can be either even or odd.

Answer №1

Guide on Creating SVG

 const $svg = document.createElementNS("http://www.w3.org/2000/svg", "svg")
 $svg.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xlink", "http://www.w3.org/1999/xlink")
 $svg.setAttribute('width', 500)
 $svg.setAttribute('height', 500)
 $svg.setAttribute('viewBox', '0 0 500 500')
 document.body.appendChild($svg)

Steps to Develop Line

const $el= document.createElementNS("http://www.w3.org/2000/svg", "line")
$el.setAttribute('x1', 0)
$el.setAttribute('y1', 0)
$el.setAttribute('x2', 100) // not real
$el.setAttribute('y2', 100) // not real
$svg.appendChild($el)

Creating an Accurate Line

function (sides, width) {
    const angle = 360 / sides

    const $el1= document.createElementNS("http://www.w3.org/2000/svg", "line")
    $el1.setAttribute('x1', 0)
    $el1.setAttribute('y1', 0)
    $el1.setAttribute('x2', width)
    $el1.setAttribute('y2', 0)
    $svg.appendChild($el1)

    // Starting from the second side
    for (var i = 1; i < sides.length; i++) { 
        const $el= document.createElementNS("http://www.w3.org/2000/svg", "line")     
        const offsetX_angle = 180 - angle
        const hypotenuse = width / Math.sin(90)
        const offsetX = Math.sin(90 - offsetX_angle) * hypotenuse
        const offsetY = Math.sin(offsetX_angle) * hypotenuse

        // Calculate coordinates using offsets
        const x1 = width
        const y1 = 0
        const x2 = width + offsetX
        const y2 = 0 + offsetY

        // Adjust angles based on side number
    }
}

This guide provides steps towards a solution

https://i.sstatic.net/fK6XS.jpg

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide to utilizing geolocation to determine a visitor's location, specifically their country

I am exploring ways to enhance the native geolocation function if(navigator.geolocation) { navigator.geolocation.getCurrentPosition(function(position) { var latitude = position.coords.latitude; var longitude = position.coords.longitude ...

Can regex matching characters be made easier to understand?

I am working on creating an ECMAScript (JavaScript) flavored regex to evaluate the complexity of my password based on specific criteria: Characters Used Password Strength Length ABC abc 123 #$& WEAK ... 1 x ...

The JQuery error encountered was due to a missing colon after the property ID

I'm currently working on some jQuery code that is supposed to hide one paragraph and show another when a specific action is triggered. I have created a class called "showp" which displays the targeted paragraph while ensuring that other paragraphs are ...

Validation of the length for masked input fields

Below is an example of a masked field: <input id="phone1" placeholder="(___) ___-____"/> The masking is achieved using the code snippet below: <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.inputmask/3.3.4/jq ...

Trouble Displaying DHtmlX Scheduler Events on Safari and Internet Explorer

I have recently embarked on the journey of building a nodejs application and decided to incorporate DHtmlX Scheduler as my calendar. To my dismay, I encountered an issue where the events are not displaying on Safari or IE, despite working perfectly fine on ...

What modifications need to be made to the MEAN app before it can be deployed on the server?

Following a tutorial on Coursetro, I was able to successfully build an Angular 4 MEAN stack application. However, when it comes to deploying the app on a server running on Debian-based OS, I am facing some challenges. The application should be accessible o ...

Exploring Enumerations in Vue.js and Javascript

Is there a way to implement enums in a Vue file? I start by creating my enums in a JavaScript file const Status= Object.freeze({ Normal: "normal", Loading: "loading", Error: "error", Done: "done", }) ...

Styling JSON format in Node.js

I have a code snippet that queries a database and outputs the information in JSON format: connectionpool.getConnection(function(err, connection) { if (err) { console.error('CONNECTION error: ',err); res.statusCode = 503; ...

Setting up SSL/TLS certificates with Axios and Nest JS

I have a Nest JS application set up to send data from a local service to an online service. However, the requests are not working because we do not have an SSL certificate at the moment. Can anyone provide guidance on configuring Axios in Nest JS to accept ...

Get rid of the folder from the URL using an <a> tag

I have both an English and French version of my website located at: *website.com/fr/index.php *website.com/index.php Currently, I have a direct link to switch between the two versions: -website.com/fr/index.php -website.com/index.php. However, I ...

What could be causing three.js to not function properly for me within the NetBeans IDE?

I have recently been experimenting with the three.js library in Notepad+ and Chrome, but now I want to transition to using it within NetBeans IDE. My attempt to import it into NetBeans by adding <script type="text/javascript" src="js/three.js"></ ...

Automatically insert a new row upon loading in a material-table using programming techniques

Is it possible to automatically trigger the Add Row function which displays a new row form with inputs based on a certain condition? How can this be achieved? An example of the desired behavior can be seen in the documentation under "Editable Example - Ed ...

Include the button beneath the Rating section using JQuery or AJAX

I am having trouble adding buttons after the result.date in my code. Placing the buttons between td tags is causing an [object Object] error to show up. $.ajax({ type: 'GET', url: 'someUrl.php', data: {op : "demo"}, da ...

Tips for utilizing the data retrieved from a successful Ajax request

My goal is to extract a value from an Ajax success response and utilize it in another function; Below is the code snippet: Code: let requiredValue; $(function(callback){ $.ajax({ type:'GET', url: 'getfile.php', data:{ ' ...

Employing jQuery to display or conceal an element based on a specific value within the document

I'm attempting to hide an element if a specific value of input is not located on the site. Hide the element by: $(document).ready(function() { $("#someid").hide(); }); But how do I display it if the value is found? My attempt looks like this: $(doc ...

Retrieve a specific object element in Javascript using its unique id

Presenting this specific item : const list = { id: 5, name: "customer name", projects: [ { id:2, title: "My project One", studies: [] }, { ...

Prevent ModalPopupExtender from displaying using JavaScript actions

In my ASP.net project, I am using Ajax with .Net 2.0. One of the challenges I am facing is related to a ModalPopupExtender that is linked to an image button: <asp:ImageButton ID="ibStartNow" runat="server" ImageUrl="images/StartNow.gif" ToolTip="S ...

Is it appropriate for HTML5 Web Workers to utilize CORS for cross-origin requests?

As I was creating a hosted API that relies on web workers, I encountered an intriguing issue. I am looking for feedback from the community to help me with this. Even though my server has the necessary CORS headers in place to serve the worker JS files and ...

Tips for retrieving arguments within a method called from a template in vue.js?

Here is an example where I am attempting to call a method from the template and pass in some arguments. How can I access those arguments from within the method? Snippet from script: methods: { showBinaries(job, id) { let test_url = process.en ...

Creating an Android game with the utilization of HTML5 and Javascript involves the adaptation of images to various screen resolutions

Currently, I am working on creating a basic game for android devices by utilizing HTML5, javascript, and cordova for wrapping it up. One of the key features of my game will involve using an image as a background and animating it to create a dynamic visua ...