When working with the DOM, it's important to use the mounted
hook instead of the created
hook. This is because in the mounted
hook, the component has been added to the DOM, and you will need the available width for the next step.
Before translating your idea into code, make sure to logically define each step. To achieve the desired functionality, consider creating a function that calculates the minimum height of a box with a given width that can fit all the circles, regardless of their position. Trigonometry may be required to solve this. If you're stuck, you can seek help on a platform like mathematics.
Once you have the formula for the minimal height, your current approach should work, provided you correct the overlaps
function to accurately check for circle intersection based on the sum of their radiuses.
If you prefer a rough estimation without seeking help on a mathematics website, consider a pattern where circles are spaced out to avoid overlapping. The distance between centers is approximately 3.5 × r
, and each subsequent row has a height of around 3 × r
.
If solving this problem, I would estimate the minimum box height based on this pattern, simplifying the formula for the first row's height to ensure the circles fit even if positioned in a seemingly random pattern.
For a rough calculation of the minimum height, you can consider the following formula:
const height = Math.max(
(3 * radius) * (circles.length / (containerWidth / (3.5 * radius))),
radius * 3.5
)
Alternatively, you can simplify it to:
const height = Math.max(
10.5 * circles.length * radius ** 2 / containerWidth,
3.5 * radius
)
To prevent endless looping, you can set a counter on the while
loop. If it exceeds a certain value, consider recalculating the circles. However, the likelihood of freezing is minimal. The counter mechanism is not included in the provided code example.
Try the demo below utilizing this formula:
// Code demo here
// CSS demo styles here
// HTML structure for the demo
If you prefer using the Options API:
// Code snippet for Options API
// CSS style for Options API snippet
// HTML structure for Options API example
Note that on the resize
event, positions of circles outside the current container are recalculated to keep them within the visible area.