-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
89 lines (70 loc) · 2.32 KB
/
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
const main = document.getElementsByTagName("main")[0];
const circles = [];
create();
function create() {
// to adjust for screen size change while running
const mainWidth = main.offsetWidth;
const mainHeight = main.offsetHeight;
const maxSize = Math.floor(Math.random() * 500);
const x = Math.floor(Math.random() * mainWidth);
const y = Math.floor(Math.random() * mainHeight);
//stop creating circles inside other circles
for (let i = 0; i < circles.length; i++) {
if (
x > circles[i].offsetLeft &&
x < circles[i].offsetLeft + circles[i].offsetWidth &&
y > circles[i].offsetTop &&
y < circles[i].offsetTop + circles[i].offsetHeight
) {
create();
return;
}
}
const circle = document.createElement("div");
circle.classList.add("circle");
circle.style.left = `${x}px`;
circle.style.top = `${y}px`;
circles.push(circle);
grow(circle, mainHeight, mainWidth, maxSize);
}
async function grow(circle, mainHeight, mainWidth, maxSize) {
let currentSize = 0;
while (currentSize < maxSize) {
currentSize += 1;
circle.style.width = `${currentSize}px`;
circle.style.height = `${currentSize}px`;
circle.style.opacity = `${currentSize / maxSize}`;
await new Promise((resolve) => setTimeout(resolve, 3));
if (circle.offsetLeft + circle.offsetWidth >= mainWidth) {
break;
}
if (circle.offsetTop + circle.offsetHeight >= mainHeight) {
break;
}
// Check if circle touches another circle's border
for (let i = 0; i < circles.length; i++) {
if (circle !== circles[i] && doCirclesCollide(circle, circles[i])) {
circle.style.width = `${currentSize - 1}px`;
circle.style.height = `${currentSize - 1}px`;
create();
return;
}
}
main.appendChild(circle);
}
create();
}
// check if two circles collide
function doCirclesCollide(c1, c2) {
const distance = getDistance(c1, c2);
const minDistance = c1.offsetWidth / 2 + c2.offsetWidth / 2;
return distance < minDistance;
}
// get distance between two circles
function getDistance(c1, c2) {
const x1 = c1.offsetLeft + c1.offsetWidth / 2;
const y1 = c1.offsetTop + c1.offsetHeight / 2;
const x2 = c2.offsetLeft + c2.offsetWidth / 2;
const y2 = c2.offsetTop + c2.offsetHeight / 2;
return Math.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2);
}