Created
January 24, 2024 12:01
-
-
Save bohnacker/f6f8b083a99a7e2b777a2bc237b3f098 to your computer and use it in GitHub Desktop.
Calculate positions of dots to draw a filled circle made of dots.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Calling this function will return a function that gives you the position of the dot at an index. | |
// This version uses the golden angle to create a tightly packed spiral. | |
// This is made as a closure so that the array of positions is only calculated once. | |
// | |
// Usage: | |
// let getDotPosition = initCircleOfDots_Spiral(); | |
// let p = getDotPosition(50); | |
// | |
// This will return a point in the format { x: 2.9227, y: 1.9894 } | |
// The distance between the dots is approximately 1, so you probably have to scale the positions. | |
function initCircleOfDots_Spiral() { | |
// move the center point a little bit to the left to make it look better | |
const arr = [{ x: 0.35, y: -0.05 }]; | |
let gAngle = Math.PI * (3 - Math.sqrt(5)); | |
let radius = 0.5; | |
let t = -0.02; | |
// scale the dots a little bit to make the distance approximately 1 | |
let adjustmentFactor = 1.1; | |
function getDotPosition(index) { | |
if (index < arr.length) { | |
return arr[index]; | |
} | |
for (let i = arr.length; i <= index; i++) { | |
let theta = gAngle * i; | |
let r = radius * Math.sqrt(i); | |
let x = r * Math.cos(theta + t); | |
let y = r * Math.sin(theta + t); | |
arr.push({ x: x * adjustmentFactor, y: y * adjustmentFactor }); | |
} | |
return arr[index]; | |
} | |
return getDotPosition; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment