Skip to content

Instantly share code, notes, and snippets.

@bohnacker
Created January 24, 2024 12:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bohnacker/164d51190fceadf87da8ec5101c61366 to your computer and use it in GitHub Desktop.
Save bohnacker/164d51190fceadf87da8ec5101c61366 to your computer and use it in GitHub Desktop.
Calculate positions of dots to draw a filled circle made of dots. This version creates simple rings. The outer ring will be partially filled most of the time.
// Calling this function will return a function that gives you the position of the dot at an index.
// This version creates rings of dots. The outer ring will be partially filled most of the time.
// This is made as a closure so that the array of positions is only calculated once.
//
// Usage:
// let getDotPosition = initCircleOfDots_SimpleRings();
// let p = getDotPosition(50);
//
// This will return a point in the format { x: 1.4724, y: 3.7191 }
// The distance between the dots is approximately 1, so you probably have to scale the positions.
function initCircleOfDots_SimpleRings(n) {
let arr = [{ x: 0, y: 0 }];
let r = 1;
function getDotPosition(index) {
if (index < arr.length) {
return arr[index];
}
while (arr.length <= index) {
let dotsOnRing = Math.round(2 * Math.PI * r);
let angle = Math.PI;
let angleInc = (-Math.PI * 2) / dotsOnRing;
for (let j = 0; j < dotsOnRing; j++) {
let x = Math.sin(angle) * r;
let y = Math.cos(angle) * r;
arr.push({ x, y });
angle += angleInc;
}
r++;
}
return arr[index];
}
return getDotPosition;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment