Creating figures within an elliptical boundary

While this could be phrased as a mathematical problem, I am dealing with a programming challenge.

In my case, I am working with a List containing an unknown number of elements (cluster nodes) that is only revealed once I receive the JSON data from the server. My task is to display these nodes in a circular pattern, which requires me to calculate the values for x and y for each iteration of the loop based on the total number of elements.

I can determine the position of the i-th element along the circle using the formula theta=2*pi*i/(n). To successfully arrange the elements around a circle, I need to find the coordinates by calculating:

x = r*cos(theta)
y = r*sin(theta)

In this scenario, where I must maximize elements within a landscape layout on a computer screen, the nodes are positioned around an ellipse with a radius r that falls between two specific radii, r1 and r2.

The question then becomes: How do I calculate the coordinates when given the angle theta, and the radii r1 and r2?

Answer №1

Here's a slight modification to my previous response on Positioning divs in a circular pattern.

The formula for calculating the coordinates on an ellipse is:

(x, y) = (r<sub>x</sub> * cos(θ), r<sub>y</sub> * sin(θ))

where r<sub>x</sub> represents the radius along the X-axis and r<sub>y</sub> represents the radius along the Y-axis.


The function generate(n, rx, ry, id) accepts four parameters: n - number of divs, rx and ry - radii along the X and Y axes respectively, and id - the ID of the target div where you want your elliptically arranged divs to be appended.

Check out the demo on Fiddle

HTML Code:

<div id="main"></div>

JavaScript Code:

var theta = [];

var setup = function (n, rx, ry, id) {
    var main = document.getElementById(id);
    var mainHeight = parseInt(window.getComputedStyle(main).height.slice(0, -2));
    var circleArray = [];
    var colors = ['red', 'green', 'purple', 'black', 'orange', 'yellow', 'maroon', 'grey'];
    for (var i = 0; i < n; i++) {
        var circle = document.createElement('div');
        circle.className = 'circle number' + i;
        circleArray.push(circle);
        circleArray[i].posx = Math.round(rx * (Math.cos(theta[i]))) + 'px';
        circleArray[i].posy = Math.round(ry * (Math.sin(theta[i]))) + 'px';
        circleArray[i].style.position = "absolute";
        circleArray[i].style.backgroundColor = colors[i];
        circleArray[i].style.top = ((mainHeight / 2) - parseInt(circleArray[i].posy.slice(0, -2))) + 'px';
        circleArray[i].style.left = ((mainHeight/ 2 ) + parseInt(circleArray[i].posx.slice(0, -2))) + 'px';
        main.appendChild(circleArray[i]);
    }
};

var generate = function(n, rx, ry, id) {
    var frags = 360 / n;
    for (var i = 0; i <= n; i++) {
        theta.push((frags / 180) * i * Math.PI);
    }
    setup(n, rx, ry, id)
}
generate(16, 150, 50, 'main');

CSS Styling:

div {
  box-sizing: border-box;
}

div#main {
  height: 500px;
  width: 500px;
  position: absolute;
  left: 0%;
  top: 0%;
}

div.circle {
  position: absolute;
  width: 20px;
  height: 20px;
  border: 2px solid black;
  border-radius: 10px;
  -webkit-border-radius: 10px;
  -moz-border-radius: 10px;
}

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

Leveraging Socket.IO server and client on separate subdomains

I currently have two subdomains set up for my domain: socket.mydomain.com - This is where the Socket.IO server is located app.mydomain.com - A web application that I want to connect to my WebSocket server. On the landing page of app.mydomain.com, I have ...

How can I generate spheres in threejs with varying radii while all passing through the shared point located at coordinates (0,0,200)?

Is there a way to generate spheres in threejs where the radius increases while always passing through a single point at 0,0,200? This would allow the origin of each new sphere to move along the z-axis. Appreciate any help, AriemWebgl ...

The newly added radio button does not function as a separate group as expected

I currently have a set of radio buttons: <input type="radio" class='form-control' name="progress_type[]" value="Journal Papers"><span class='radio-label'>Journal Paper</span> <input type="radio" class='form-co ...

Uncover the secrets of HTML with JavaScript

I'm facing an issue with extracting data from a link's data attribute and trying to decode the HTML within it, but unfortunately, it's not functioning as expected. Check out my code on JSFiddle: http://jsfiddle.net/Kd25m/1/ Here's the ...

Issues have been identified with the capabilities of Vue's Mutations and Actions

My Index.js from the Store Folder import Vue from "vue"; import Vuex from "vuex"; import state from "../store/state"; import mutations from "../store/mutations"; import actions from "../store/actions"; Vu ...

The addEventListener function seems to encounter issues in IE11

There is a javascript function below that uploads the selected file and updates the grid. It works perfectly in Firefox, but there seems to be an issue with IE11. The "ESignature/Registration" function within the addEventListener does not seem to execute ...

Utilizing the .finally method on a promise that is already being handled with try/catch statements elsewhere may lead to an UnhandledPromiseRejection

Recently, I've come across an unexpected behavior while working with nodejs. To illustrate this strange occurrence, let's consider the following example: Imagine we have two functions, foo and bar. The foo function creates a promise, attaches a ...

Is there a way to retrieve the previous value in an input field's onChange event?

I am working with inputs in a React project and have assigned a function to their onChange event. While I have been able to access the current value, I am now looking for a way to retrieve the previous value as well. The reason I need the old value is bec ...

I'm always puzzled when the 'if' statement is triggered, regardless of whether

I've encountered an issue with my code where, despite the if statement at the end evaluating to false, the code continues to run and data is still being added to MongoDB. This behavior has left me puzzled as to why it's happening... Even when I ...

Encountering the "Unexpected token SyntaxError" message is a common issue that arises while trying to import express-handlebars

Whenever I include this specific line, an error shows up. But as soon as I remove it, the error disappears. const expressHandleBars = require('express-handlebars'); The error message goes something like this: C:\Users\Hp\sample- ...

The completion event for Ajax and Json does not activate Google Maps

I'm currently facing an issue with my Google Maps functionality. Despite trying various solutions that involve hidden tabs, the problem persists. The trouble lies in the fact that my ajax function successfully posts and retrieves data, but fails to tr ...

What is the reason behind the browser not reusing the authorization headers following an authenticated XMLHttpRequest?

As I work on developing a Single Page Application using Angular, I have encountered an interesting challenge. The backend system exposes REST services that require Basic authentication. Surprisingly, while obtaining index.html or any of the scripts does no ...

The Render function in ReactJS is not getting refreshed

My goal is to implement a chat feature using material UI. I have set up a function where users can submit new chat messages, which then go through the reducer and are stored in the redux store. The process seems to be working fine, except for the fact that ...

Guide to successfully downloading an xlsx file in angular through express

I am creating an xlsx file based on user input within the express framework. The data is sent via a post request and I intend to send back the file content using res.download(...). However, when I do this, the data field in my ajax response ends up contai ...

What is the best way to display a header element in front of an article element?

I'm struggling with making my header element sticky and appear in front of my article. Modifying the z-index hasn't given me the desired result so far. Is the z-index ineffective when dealing with floating elements? Or is there a workaround to m ...

Challenge with Deploying VueJs: Chrome is stuck on the previous version and not refreshing the application

Having issues with deploying my VueJs project, a web application built on the Metronic template and utilizes Vuetify components. When publishing, I use Visual Studio Code with npm run build and upload the contents of the dist folder to my server. Encoun ...

Triggering an event from a component to its parent module resulting in an exception situation

Here is my app.component.ts code: import { Component, Input, OnInit, OnChanges, SimpleChanges} from '@angular/core'; import {Counter } from './counter' @Component({ selector: 'my-app', template: ` <custom-counter [ ...

Tips for organizing data when parsing JSON in Javascript

I am facing a challenge with maintaining the order of JSON data that I am parsing using Javascript and displaying in an HTML SELECT element. The incoming data is already sorted, but I am encountering issues sustaining this order after decoding the JSON str ...

When a promise is executed, it runs the code synchronously regardless of the promise

Essentially, I have a web application that fetches data from Firebase. Due to the time it takes to retrieve this data, I've implemented promises in JavaScript to ensure my code executes at the appropriate times. Within the function getDataFirebase, in ...

Methods for transferring data from an AJAX function

I have a database containing various links that I would like to retrieve and store within an array. I attempted to achieve this using the following code: var amz = new Array(); function CreateAmazonArray() { $.ajax({ url: "php/amazon_affilia ...