Пример:
HTML:
1 |
<div id="circles"></div> |
CSS:
1 2 3 4 5 6 7 8 9 10 11 12 |
#circles { position: relative; height: 500px; overflow: hidden; margin: 20px 0; } .circle { box-shadow: 1px 3px 7px 0px rgba(0, 0, 0, 0.3); transition: all ease 0.2s; position: absolute; border-radius: 50%; } |
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 |
let limit = 50; function randomNumber(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } let art = document.getElementById("circles"); for (let i = 0; i < limit; i++) { let circle = document.createElement("div"); circle.classList.add("circle"); art.appendChild(circle); } let circles = document.getElementsByClassName("circle"); function randomCircle() { if (circles.length > 0) { for (let item of circles) { let zindex = randomNumber(0, limit); let color1 = randomNumber(0, 360); let color2 = randomNumber(50, 100); let color3 = randomNumber(50, 100); let top = randomNumber(-10, 90); let left = randomNumber(-10, 90); let size = randomNumber(10, 250); item.style.zIndex = zindex; item.style.width = size + "px"; item.style.height = size + "px"; item.style.top = top + "%"; item.style.left = left + "%"; item.style.backgroundColor = "hsl("+ color1 +", "+ color2 +"%, "+ color3 +"%)"; } } } randomCircle(); |
Где переменная limit
- количество окружностей, а функция randomCircle()
отвечает за их отрисовку, например: <button onclick="randomCircle()">Перерисовать</button>
В примере выше, цвет окружностей задается рандомно в формате hsl
. Если требуется использовать только конкретные оттенки, то в самом начале создаем с ними переменную:
let colors = ["#BFE2FF", "#59b4ff", "#78c2ff"];
В функции randomCircle()
заменяем color1
, color2
и color3
на одну:
let color = randomNumber(0, colors.length-1);
И заменяем:
item.style.backgroundColor = "hsl("+ color1 +", "+ color2 +"%, "+ color3 +"%)";
на item.style.backgroundColor = colors[color];
Добавить комментарий: