Библиотека дизайна / Эффекты и шейдеры

Эффекты и шейдерыСветлый3DГрадиентыБесплатно

Прелоадер: кольцо карточек, внутрь которого ныряет камера

Пока идёт загрузка, карточки собираются в маленькое наклонённое кольцо. На 100% камера ныряет внутрь, и кольцо становится панорамой.

Прелоадер: кольцо карточек, внутрь которого ныряет камера
Промпт
Сделай мне прелоадер «Кольцо карточек, внутрь которого ныряет камера» (Сергей Дургалян, MIT). Ниже один HTML-файл: HTML, CSS и чистый JavaScript, без библиотек и картинок. Сначала перенеси его как есть и проверь: на светлом экране логотип «Мира.» слева вверху и счётчик 000→100 справа внизу; карточки по одной вылетают снизу и встают в маленькое наклонённое вращающееся кольцо; на 100% камера ныряет внутрь, кольцо раскрывается в панораму вокруг зрителя, экран сжимается в окно с закатным небом, появляются шапка и строка про автора. Перетаскивание, колесо мыши и стрелки крутят панораму с инерцией, кнопка «Повторить» запускает заставку заново. Потом меняй.

Как устроен код:
- Вся заставка — одна шкала времени `T` в миллисекундах: `COUNT` (бег счётчика), `DEAL0`, `GAP`, `DEAL_D` (карта `i` прилетает в `DEAL0 + i * GAP`), `DIVE0`, `DIVE_D` (нырок). `render(dt)` двигает `T` каждый кадр, на скрытой вкладке всё встаёт на паузу.
- Карточка стоит на кольце через `rotateY(угол) translateZ(радиус)`. Мир `.world` наклонён (`TILT`, `ROLL`), сцена задаёт `perspective: var(--p)` — это расстояние до камеры `P`.
- Нырок — одна переменная `k` от 0 до 1 (плавная кривая `inOut`): радиус растёт от маленького `r0` до `R = P * 1.6`, масштаб карточек от `cw0 / cw1` до 1, наклон уходит в ноль, камера чуть отъезжает назад (`CAM_BACK`). Как только радиус больше `P`, зритель оказывается внутри кольца.
- Карточки, которые уходят за камеру, плавно гаснут (`vis`): CSS 3D рисует такие точки вывернутыми, поэтому их нужно прятать. Дальние карточки получают дымку `--haze` цвета неба.
- У каждой карточки две одинаковые стороны `.face` (вторая повёрнута на 180°), поэтому и снаружи, и изнутри видна надпись, а не изнанка.
- Счётчик — три колонки цифр, неровный прогресс задаёт `makeSteps()`, 100 всегда наступает в конце `COUNT`. Окно — `clip-path` на `.stage` по классу `open`.
- Небо — функция `createSky()`: градиент, облака-спрайты из мягких кругов со светом и тенью, дрейф, параллакс за курсором, лепестки.
- При `prefers-reduced-motion` сразу показана панорама, облака стоят, поворот только по команде без инерции.

Что заменить: тексты в `TITLES` и `VIEWS`, палитры в `PAL`, число карточек `N` (12–20), логотип и строки в шапке и подвале, шрифты (`Cormorant` и `JetBrains Mono`, оба с кириллицей), длительности фаз, угол обзора (меньше `P` — шире «объектив», больше `R / P` — сильнее эффект «вокруг меня»), дымку в `haze`, цвета неба в `build()` и облаков в `TONE`. Вместо нарисованных карточек можно поставить картинки фоном в `.face`.

Чтобы счётчик показывал реальную загрузку, считай готовые ресурсы (`document.fonts.ready`, `img.decode()`) и передавай процент в `showCount`, а прилёт карточек привяжи к проценту. Если проект на React: вынеси сцену в компонент, карточки строй из массива один раз, позиции обновляй в `requestAnimationFrame` через `ref` и отменяй цикл в очистке `useEffect`. На телефоне проверь плавность: если карточек больше 20 или на них фото, уменьши `N`.
Предложи тексты карточек, палитру и подпись про автора под мой продукт.

Код скопируется вместе с промптом

На светлом экране слева вверху логотип, справа внизу крупный счётчик процентов с прокручивающимися цифрами. Пока он неровно бежит к 100, снизу по одной вылетают карточки и встают в маленькое кольцо в центре. Кольцо наклонено и медленно вращается, его видно снаружи и чуть сверху. На 100% камера ныряет внутрь: кольцо разрастается, ближние карточки проносятся мимо зрителя и тают, наклон выпрямляется, и то же кольцо становится панорамной каруселью, которая окружает зрителя. Экран превращается в окно со скруглёнными углами, за карточками проявляется закатное небо с облаками и лепестками. Дальние карточки в центре маленькие и чуть дымчатые, ближние по краям крупные и яркие. Панораму можно крутить перетаскиванием, колесом мыши или стрелками, она вращается с инерцией.

Всё сделано на CSS 3D без three.js и WebGL: «камера» — это perspective сцены, а нырок — рост радиуса кольца, пока он не станет больше расстояния до камеры. Чтобы карточки читались и снаружи, и изнутри, у каждой две одинаковые стороны. Карточки в формате 9:16 и облака на canvas нарисованы кодом, файлов-картинок нет. Подходит для портфолио, блога с рилсами, студии, онлайн-школы, где хочется открыть сайт эффектным «входом» в мир работ. Приём подсмотрен в рилсе @avi_vashishta29 (портфолио на CSS 3D): оттуда взята только механика, код, тексты и графика свои.

Код
<!-- MIT License. Copyright (c) 2026 Sergei Durgalian, learn.create-products.com/design. Free to use, copy and modify with this notice kept. -->
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Ring Dive Carousel</title>
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Cormorant:ital,wght@0,500;0,600;1,500&family=JetBrains+Mono:wght@300&family=Manrope:wght@500;700&display=swap">
<style>
*, *::before, *::after { box-sizing: border-box; }
html, body { margin: 0; height: 100%; }
body { overflow: hidden; background: #f1eee8; color: #1b1a22; font-family: "Manrope", sans-serif; --t: 64px; --b: 86px; }
a { color: inherit; }
a:focus-visible, button:focus-visible, .stage:focus-visible { outline: 2px solid #1b1a22; outline-offset: 3px; }

/* ---------- Site chrome around the "window" (fades in after the preloader) ---------- */
.bar, .about { position: fixed; left: 0; right: 0; display: flex; align-items: center; gap: 16px;
  padding: 0 clamp(16px, 2.4vw, 32px); opacity: 0; transition: opacity .8s .6s; }
.bar { top: 0; height: 64px; padding-right: 150px; }
.bar .logo { font: 600 1.7rem/1 "Cormorant", serif; text-decoration: none; }
.bar nav { font: 500 1.25rem/1 "Cormorant", serif; color: #8b8794; }
.bar nav a { text-decoration: none; }
.about { bottom: 0; padding-top: 16px; padding-bottom: 18px; }
.about p { margin: 0; max-width: 62ch; font: 500 clamp(1.05rem, 1.6vw, 1.35rem)/1.3 "Cormorant", serif; }
body.open .bar, body.open .about { opacity: 1; }

/* ---------- The window: full screen during the preloader, framed afterwards ---------- */
.stage { position: fixed; inset: 0; overflow: hidden; background: #faf8f4; touch-action: none; cursor: grab;
  clip-path: inset(0 0 0 0 round 0); transition: clip-path 1.25s cubic-bezier(.7, 0, .2, 1); }
body.open .stage { clip-path: inset(var(--t) 12px var(--b) 12px round 22px); }
#sky { position: absolute; inset: 0; width: 100%; height: 100%; display: block; opacity: 0; transition: opacity 1.1s .1s; }
body.open #sky { opacity: 1; }
.scene { position: absolute; inset: 0; perspective: var(--p); }
.world { position: absolute; left: 50%; top: 50%; transform-style: preserve-3d; }

/* ---------- Cards: 9:16, drawn with CSS only, same art on both sides ---------- */
.card { position: absolute; left: 0; top: 0; width: var(--cw); height: calc(var(--cw) * 16 / 9); margin: calc(var(--cw) * -8 / 9) 0 0 calc(var(--cw) / -2); transform-style: preserve-3d; }
.face { position: absolute; inset: 0; border-radius: calc(var(--cw) * .07); overflow: hidden; backface-visibility: hidden; -webkit-backface-visibility: hidden;
  display: flex; flex-direction: column; padding: 9%; background: var(--bg); color: var(--ink); }
.face + .face { transform: rotateY(180deg); }
.face::before { content: ""; position: absolute; inset: 34% 0 16%; opacity: .85; }
.face::after { content: ""; position: absolute; inset: 0; background: #ffe9df; opacity: var(--haze, 0); }  /* far cards melt into the sky */
.face > * { position: relative; }
.cap { font: 700 calc(var(--cw) * .058)/1 "Manrope", sans-serif; letter-spacing: .06em; text-transform: uppercase; opacity: .7; }
.t { margin-top: 8%; font: 600 calc(var(--cw) * .165)/.95 "Cormorant", serif; }
.v { margin-top: auto; font: 700 calc(var(--cw) * .062)/1 "Manrope", sans-serif; }
.p0::before { background: repeating-linear-gradient(-40deg, var(--ac) 0 calc(var(--cw) * .045), transparent 0 calc(var(--cw) * .11)); -webkit-mask: linear-gradient(transparent, #000 60%); mask: linear-gradient(transparent, #000 60%); }
.p1::before { background: radial-gradient(circle at 64% 55%, var(--ac) 0 17%, transparent 17.5%), repeating-radial-gradient(circle at 64% 55%, transparent 0 calc(var(--cw) * .07), var(--ac) 0 calc(var(--cw) * .085)); opacity: .7; }
.p2::before { background: linear-gradient(var(--ac) 1px, transparent 1px) 0 0 / calc(var(--cw) * .16) calc(var(--cw) * .16), linear-gradient(90deg, var(--ac) 1px, transparent 1px) 0 0 / calc(var(--cw) * .16) calc(var(--cw) * .16); opacity: .5; }
.p3::before { inset: auto 14% 22% auto; width: 72%; aspect-ratio: 1; border-radius: 50%; background: repeating-linear-gradient(0deg, var(--ac) 0 calc(var(--cw) * .04), transparent 0 calc(var(--cw) * .075)); }
.p4::before { background: repeating-radial-gradient(circle at 50% 120%, var(--ac) 0 calc(var(--cw) * .03), transparent 0 calc(var(--cw) * .09)); opacity: .75; }

/* ---------- Preloader: logo top left, rolling counter bottom right ---------- */
.splash { position: fixed; inset: 0; pointer-events: none; z-index: 2; }
.splash > * { position: absolute; transition: opacity .6s, transform .8s cubic-bezier(.7, 0, .2, 1); }
.mark { left: clamp(16px, 2.4vw, 32px); top: 18px; font: 600 clamp(2.2rem, 4vw, 3.6rem)/1 "Cormorant", serif; }
.counter { right: clamp(16px, 2.4vw, 32px); bottom: 14px; display: flex; font: 300 clamp(3.6rem, 9vw, 8.6rem)/1 "JetBrains Mono", monospace; letter-spacing: -.04em; }
.slot { height: 1em; overflow: hidden; }
.strip { display: flex; flex-direction: column; transition: transform .45s cubic-bezier(.3, 1.35, .5, 1); }
.strip span { height: 1em; }
.counter small { font-size: .16em; letter-spacing: 0; margin: .5em 0 0 .3em; }
.splash.in > * { animation: rise .8s cubic-bezier(.2, .8, .2, 1) backwards; }
@keyframes rise { from { opacity: 0; transform: translateY(30px); } }
body.open .splash > * { opacity: 0; transform: translateY(40px); }
body.open .splash .mark { transform: translateY(-40px); }

.again { position: fixed; right: clamp(16px, 2.4vw, 32px); top: 15px; z-index: 3; font: 700 .8rem "Manrope", sans-serif; padding: 9px 14px;
  border: 1px solid rgba(27, 26, 34, .2); border-radius: 999px; background: rgba(255, 255, 255, .7); color: inherit; cursor: pointer; }
.again:hover { background: #fff; }
.snap, .snap *, .snap #sky { transition: none; }

@media (max-width: 700px) { .bar nav { display: none; } }
@media (prefers-reduced-motion: reduce) { .stage, #sky, .bar, .about, .splash > *, .strip { transition: none; } .splash.in > * { animation: none; } }
</style>
</head>
<body>
<header class="bar">
  <a class="logo" href="#">Мира Ланская.</a>
  <nav>/ <a href="#">Сайты</a> / <a href="#">Бренды</a> / <a href="#">Курсы</a></nav>
</header>

<main class="stage" id="stage" tabindex="0" aria-label="Панорама работ: перетаскивайте, крутите колесом мыши или стрелками">
  <canvas id="sky" aria-hidden="true"></canvas>
  <div class="scene" id="scene"><div class="world" id="world"></div></div>
</main>

<footer class="about">
  <p>Делаю <a href="#">сайты</a> для основателей, <a href="#">бренды</a> для компаний и бесплатные <a href="#">разборы</a> для студентов. Или просто <a href="#">напишите мне</a>.</p>
</footer>

<div class="splash" id="splash" role="progressbar" aria-label="Загрузка" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0">
  <div class="mark">Мира.</div>
  <div class="counter" id="counter" aria-hidden="true"></div>
</div>
<button class="again" id="again" type="button">↻ Повторить</button>

<script>
// Ring Dive Carousel preloader. While the counter rolls 000 -> 100, cards are dealt one by one into a small
// tilted ring (seen from outside). At 100% the camera dives in: the ring radius grows past the camera,
// the tilt flattens, and the same ring becomes a panorama around the viewer (seen from inside).
// Cards have the same art on both sides, so they read correctly from outside and from inside.
const reduce = matchMedia('(prefers-reduced-motion: reduce)').matches;
const $ = (id) => document.getElementById(id);
const stage = $('stage'), scene = $('scene'), world = $('world'), counter = $('counter'), splash = $('splash');

const N = 16;                                    // cards in the ring
const COUNT = [900, 4600];                       // counter run (ms)
const DEAL0 = 1000, GAP = 190, DEAL_D = 650;     // card i flies into the ring at DEAL0 + i * GAP
const DIVE0 = 4750, DIVE_D = 1700;               // the camera dive
const TILT = -22, ROLL = 8;                      // ring tilt while seen from outside (deg)
const SPIN_RING = 26, SPIN_PANO = 4;             // idle spin (deg/s) before and after the dive
const CAM_BACK = .2;                             // final camera offset back from the centre (of R): big cards at the edges

const PAL = [ // background, ink, accent
  ['linear-gradient(160deg,#2b1d3a,#7a2e4f)', '#ffe9d6', '#ff8a5b'], ['linear-gradient(160deg,#f4e3c9,#e9b48a)', '#3a1f14', '#c2452d'],
  ['linear-gradient(170deg,#0f2b3d,#1f6f78)', '#e8fff8', '#7ee0c3'], ['linear-gradient(160deg,#c8102e,#5c0a1a)', '#fff2e6', '#ffcf6b'],
  ['linear-gradient(165deg,#f6efe4,#d9d0c0)', '#1b1b1b', '#2f5bd3'], ['linear-gradient(160deg,#1b1b1f,#3b3b45)', '#f3f0ea', '#c6ff4a'],
  ['linear-gradient(160deg,#ffd6c9,#f48fb1)', '#3b1030', '#7a1f5c'], ['linear-gradient(165deg,#25417a,#5b8bd6)', '#fff8ec', '#ffd166'],
  ['linear-gradient(160deg,#e9f1d8,#a7c48a)', '#1f2d16', '#3d6b2b'], ['linear-gradient(160deg,#3d2416,#a0582c)', '#fff1e2', '#ffc38a'],
];
const TITLES = ['Сайт за выходные', 'Бренд с нуля', 'Как найти свой стиль', 'Курс за 30 дней', 'Лендинг, который продаёт',
  'Три шрифта на всё', 'Цвет решает', 'Разбор портфолио', 'Мой рабочий стол', 'Сетка без боли', 'Первый клиент', 'Ошибки новичка',
  'Логотип за час', 'Тексты для сайта', 'Анимация без кода', 'Фото для бренда'];
const VIEWS = ['12,4', '8,1', '31', '5,7', '19,2', '44', '9,8', '27,5', '6,3', '15', '72', '11,6', '23', '4,9', '38', '13,1'];

const cards = TITLES.slice(0, N).map((title, i) => {
  const [bg, ink, ac] = PAL[i % PAL.length];
  const face = `<div class="face p${(i + (i >= 10 ? 2 : 0)) % 5}"><span class="cap">Рилс · 0:${String(18 + (i * 7) % 41).padStart(2, '0')}</span>`
    + `<b class="t">${title}</b><span class="v">▶ ${VIEWS[i]} тыс.</span></div>`;
  const el = document.createElement('div'); el.className = 'card'; el.innerHTML = face + face;
  el.style.setProperty('--bg', bg); el.style.setProperty('--ink', ink); el.style.setProperty('--ac', ac);
  world.append(el);
  return { el, haze: -1 };
});

// counter: three rolling strips (hundreds only need 0 and 1)
const strips = [2, 10, 10].map((n) => {
  const slot = document.createElement('div'); slot.className = 'slot';
  const strip = document.createElement('div'); strip.className = 'strip';
  for (let d = 0; d < n; d++) strip.insertAdjacentHTML('beforeend', `<span>${d}</span>`);
  slot.append(strip); counter.append(slot); return strip;
});
counter.insertAdjacentHTML('beforeend', '<small>%</small>');
let shown = -1;
function showCount(v) {
  if (v === shown) return; shown = v;
  String(v).padStart(3, '0').split('').forEach((d, i) => (strips[i].style.transform = `translateY(${-d}em)`));
  splash.setAttribute('aria-valuenow', v);
}

// uneven fake progress: random chunks + a couple of stalls, always finishing exactly at COUNT[1]
let steps = [];
function makeSteps() {
  const vals = []; let v = 0;
  while (v < 100) vals.push(v = Math.min(100, v + 1 + (Math.random() * 9 | 0)));
  const w = vals.map(() => .4 + Math.random());
  for (let k = 0; k < 2; k++) w[1 + (Math.random() * (w.length - 2) | 0)] += 3;
  const sum = w.reduce((a, b) => a + b, 0); let t = COUNT[0];
  steps = vals.map((val, i) => ({ t: (t += w[i] / sum * (COUNT[1] - COUNT[0])), val }));
}

const clamp = (x) => Math.max(0, Math.min(1, x));
const lerp = (a, b, k) => a + (b - a) * k;
const inOut = (x) => (x < .5 ? 8 * x ** 4 : 1 - (-2 * x + 2) ** 4 / 2);
const outBack = (x) => 1 + 2.2 * (x - 1) ** 3 + 1.2 * (x - 1) ** 2;
const RAD = Math.PI / 180;

let W, H, P, R, cw1, cw0, r0, oy;
function layout() {
  W = innerWidth; H = innerHeight;
  const t = document.querySelector('.bar').offsetHeight, b = document.querySelector('.about').offsetHeight;
  document.body.style.setProperty('--t', t + 'px'); document.body.style.setProperty('--b', b + 'px');
  P = Math.max(300, W * .4, (H - t - b) * .55);                  // perspective = camera distance (small = wide angle)
  R = P * 1.6;                                   // panorama radius: bigger than P, so the camera is inside
  cw1 = Math.min(2 * Math.PI * R / N * .86, (H - t - b) * .62 * 9 / 16 / (P / (P + R)) );   // final card width
  cw0 = Math.max(30, Math.min(W, H) * .055);     // card width inside the small ring
  r0 = N * cw0 * 1.2 / (2 * Math.PI);            // small ring radius
  oy = (t - b) / 2;                              // panorama centred in the framed window
  scene.style.setProperty('--p', P + 'px');
  world.style.setProperty('--cw', cw1 + 'px');   // cards are built at final size and scaled down in the ring
}

let T = 0, last = 0, spin = 0, vel = 0, opened = false, raf = 0;
function open(on) { opened = on; document.body.classList.toggle('open', on); }

function render(dt) {
  T += dt;
  if (T >= COUNT[0]) { let v = 0; for (const s of steps) if (s.t <= T) v = s.val; showCount(v); }
  const k = inOut(clamp((T - DIVE0) / DIVE_D));
  if (T >= DIVE0 && !opened) open(true);
  if (!reduce) spin += (lerp(SPIN_RING, SPIN_PANO, k) + vel) * dt / 1000;
  vel *= Math.exp(-dt / 1000 * 2);
  const r = lerp(r0, R, k), s = lerp(cw0 / cw1, 1, k), tilt = lerp(TILT, 0, k), roll = lerp(ROLL, 0, k);
  world.style.transform = `translate3d(0,${oy * k}px,${-R * CAM_BACK * k}px) rotateX(${tilt}deg) rotateZ(${roll}deg)`;
  cards.forEach((c, i) => {
    const u = clamp((T - DEAL0 - i * GAP) / DEAL_D), e = outBack(u);
    const th = i * 360 / N + spin;
    const z = r * Math.cos(th * RAD) * Math.cos(tilt * RAD) - R * CAM_BACK * k;   // depth towards the camera
    // cards that pass behind the camera fade out (CSS 3D would draw them inverted)
    const vis = u === 0 ? 0 : Math.min(u * 3, clamp((P * .9 - z) / (P * .3)));
    c.el.style.opacity = vis.toFixed(3);
    c.el.style.visibility = vis < .01 ? 'hidden' : 'visible';
    if (vis < .01) return;
    const haze = Math.round(clamp((r - z) / (2 * r)) * (k > .5 ? .14 : .45) * 100) / 100;   // far = hazier
    if (haze !== c.haze) { c.haze = haze; c.el.style.setProperty('--haze', haze); }
    c.el.style.transform = `translate3d(0,${(1 - e) * H * .6}px,0) rotateY(${th}deg) translateZ(${r}px) rotateX(${(1 - e) * -70}deg) scale(${s})`;
  });
}

function loop(now) { render(Math.min(50, now - last)); last = now; raf = requestAnimationFrame(loop); }
function start() { if (!raf && !reduce && !document.hidden) { last = performance.now(); raf = requestAnimationFrame(loop); } }
function stop() { cancelAnimationFrame(raf); raf = 0; }
document.addEventListener('visibilitychange', () => (document.hidden ? stop() : start()));   // timeline pauses with the tab

function play() {
  document.body.classList.add('snap'); open(false); T = 0; spin = 0; vel = 0; shown = -1; makeSteps(); showCount(0);
  splash.classList.remove('in'); void splash.offsetWidth; splash.classList.add('in');
  void document.body.offsetWidth; document.body.classList.remove('snap');
  if (reduce) { T = DIVE0 + DIVE_D; spin = 180; showCount(100); }
  render(0);
}

// input: drag / wheel / arrows turn the panorama with inertia (in reduced motion: step without inertia)
const nudge = (deg) => { if (!opened) return; if (reduce) { spin += deg; render(0); } else vel += deg * 3; };
addEventListener('wheel', (e) => nudge(Math.max(-30, Math.min(30, (e.deltaY || e.deltaX) * .1))), { passive: true });
let drag = null;
stage.addEventListener('pointerdown', (e) => { drag = { x: e.clientX, t: performance.now() }; stage.setPointerCapture(e.pointerId); });
stage.addEventListener('pointermove', (e) => {
  if (!drag || !opened) return;
  const now = performance.now(), deg = -(e.clientX - drag.x) * 90 / W;    // drag right = the panorama follows the finger
  spin += deg; if (!reduce) vel = lerp(vel, deg / Math.max(8, now - drag.t) * 1000 - SPIN_PANO, .5); else render(0);
  drag = { x: e.clientX, t: now };
});
addEventListener('pointerup', () => (drag = null));
stage.addEventListener('keydown', (e) => {
  if (e.key === 'ArrowRight') { nudge(-10); e.preventDefault(); }
  if (e.key === 'ArrowLeft') { nudge(10); e.preventDefault(); }
});
$('again').addEventListener('click', play);
let rt; addEventListener('resize', () => { clearTimeout(rt); rt = setTimeout(() => { layout(); render(0); }, 120); });

function createSky(cv, opt = {}) {
  const ctx = cv.getContext('2d');
  const PETAL_COLORS = ['#ff6b4a', '#ffb347', '#ffd166', '#f78fb3', '#e8505b', '#ff9f68'];
  // cloud tones: light top, body, lobe rim, bottom shade (rgb)
  const TONE = {
    near: [[255, 249, 240], [255, 217, 190], [242, 160, 160], [150, 112, 170]],
    mid:  [[255, 240, 226], [252, 200, 180], [236, 150, 162], [140, 112, 176]],
    far:  [[255, 228, 220], [246, 186, 184], [226, 150, 176], [128, 120, 190]],
  };
  // layout: kind, centre x (of width), bottom y (of height), width, height (of cloud unit), depth, tone
  const LAYOUT = [
    ['wisp', .22, .24, .55, .12, .15, 'far'], ['wisp', .82, .17, .5, .1, .15, 'far'], ['wisp', .56, .36, .45, .08, .2, 'far'],
    ['cloud', .5, .8, 1.15, .3, .25, 'far'],
    ['cloud', .12, .9, .55, .42, .5, 'mid'], ['cloud', .8, .74, .52, .46, .5, 'mid'],
    ['cloud', .95, 1.06, .72, .64, 1, 'near'], ['cloud', .04, 1.1, .6, .48, 1, 'near'], ['cloud', .5, 1.16, .72, .36, 1, 'near'],
  ];
  let W = 0, H = 0, D = 1, sprites = [], petals = [], grad, sun, raf = 0, last = 0;
  let px = 0, py = 0, tx = 0, ty = 0;

  // small seeded random, so the sky looks the same on every load
  const rng = (a) => () => { a = a + 0x6d2b79f5 | 0; let t = Math.imul(a ^ a >>> 15, 1 | a); t = t + Math.imul(t ^ t >>> 7, 61 | t) ^ t; return ((t ^ t >>> 14) >>> 0) / 4294967296; };
  const rgba = (c, a) => `rgba(${c[0]},${c[1]},${c[2]},${a})`;

  const mk = (w, h) => { const c = document.createElement('canvas'); c.width = w; c.height = h; return c; };
  // paint `mask` in `color` minus the same mask shifted by dx/dy: the light (or shadow) rim of every lobe
  function rimLayer(g, mask, color, dx, dy, soft, alpha) {
    const t = mk(mask.width, mask.height), tg = t.getContext('2d');
    tg.drawImage(mask, 0, 0); tg.globalCompositeOperation = 'source-in'; tg.fillStyle = color; tg.fillRect(0, 0, t.width, t.height);
    if (dx || dy) { tg.globalCompositeOperation = 'destination-out'; tg.filter = `blur(${soft}px)`; tg.drawImage(mask, dx, dy); }
    g.globalAlpha = alpha; g.drawImage(t, 0, 0); g.globalAlpha = 1;
  }

  function cloud(w, h, tone, r) {
    const c = mk(w, h), g = c.getContext('2d'), [hi, body, rim, shade] = TONE[tone].map((v) => rgba(v, 1));
    // silhouette = a few gaussian "towers" over a low base
    const towers = Array.from({ length: 4 + (r() * 4 | 0) }, () => ({ x: .2 + r() * .6, w: .06 + r() * .13, h: .35 + r() * .65 }));
    const top = (u) => { let v = .2 * Math.exp(-(((u - .5) / .38) ** 2)); for (const t of towers) v = Math.max(v, t.h * Math.exp(-(((u - t.x) / t.w) ** 2))); return v; };
    const base = h * .8, pad = h * .05, puffs = [];
    const count = Math.round(150 * Math.min(1.8, w / h / 1.5));
    for (let k = 0; k < count; k++) {
      const u = .05 + r() * .9, t = top(u);
      if (t < .07) continue;
      const edge = base - t * (base - pad);                       // top of the cloud at this x
      const rad = h * (.05 + .09 * Math.sqrt(t)) * (.6 + r() * .6);
      const y = Math.min(base - rad * .4, edge + rad * .9 + r() * Math.max(0, base - edge - rad * 1.3));
      puffs.push({ x: u * w, y, r: rad });
    }
    puffs.sort((a, b) => a.y - b.y);
    // three depth bands, back (upper) to front (lower): front lobes overlap the back ones,
    // and the rim light of each band draws the inner "cauliflower" edges
    const bands = [[], [], []];
    puffs.forEach((p, i) => bands[Math.min(2, (i * 3 / puffs.length) | 0)].push(p));
    const soft = Math.max(1, h / 150);
    for (const band of bands) {
      if (!band.length) continue;
      const m = mk(w, h), mg = m.getContext('2d'), R = band.reduce((s, p) => s + p.r, 0) / band.length;
      mg.filter = `blur(${soft}px)`; mg.fillStyle = '#fff';
      for (const p of band) {
        mg.beginPath(); mg.arc(p.x, p.y, p.r, 0, 7); mg.fill();
        for (let j = 0; j < 3; j++) {                              // fluff on the upper edge of each puff
          const a = -Math.PI * (.1 + r() * .8), rr = p.r * (.25 + r() * .2);
          mg.beginPath(); mg.arc(p.x + Math.cos(a) * p.r * .85, p.y + Math.sin(a) * p.r * .85, rr, 0, 7); mg.fill();
        }
      }
      rimLayer(g, m, body, 0, 0, 0, 1);
      rimLayer(g, m, shade, -R * .06, -R * .4, R * .25, .6);     // underside of the lobes
      rimLayer(g, m, rim, R * .04, R * .12, R * .12, .35);         // warm edge
      rimLayer(g, m, hi, R * .12, R * .38, R * .3, .95);           // sunlit tops
      rimLayer(g, m, 'rgba(255,253,244,1)', R * .05, R * .14, R * .1, .7); // crisp rim
    }
    g.globalCompositeOperation = 'source-atop';                   // overall light only where the cloud is
    let lg = g.createLinearGradient(0, pad, 0, base);
    lg.addColorStop(0, 'rgba(255,252,240,.35)'); lg.addColorStop(.5, 'rgba(255,240,225,0)'); lg.addColorStop(1, rgba(TONE[tone][3], .35));
    g.fillStyle = lg; g.fillRect(0, 0, w, h);
    const rg = g.createRadialGradient(w * .7, base, 0, w * .7, base, w * .55);   // warm sunset light from below
    rg.addColorStop(0, 'rgba(255,170,110,.35)'); rg.addColorStop(1, 'rgba(255,170,110,0)');
    g.fillStyle = rg; g.fillRect(0, 0, w, h);
    g.globalCompositeOperation = 'destination-in';                // soft flat bottom
    lg = g.createLinearGradient(0, base - h * .1, 0, base + h * .04);
    lg.addColorStop(0, '#000'); lg.addColorStop(1, 'rgba(0,0,0,0)');
    g.fillStyle = lg; g.fillRect(0, 0, w, h);
    return c;
  }

  function wisp(w, h, r) {
    const c = mk(w, h), g = c.getContext('2d');
    g.filter = 'blur(' + Math.max(2, h / 14) + 'px)';
    for (let k = 0; k < 46; k++) {
      const ry = h * (.07 + r() * .1), sx = Math.min(3 + r() * 6, w * .12 / ry);
      const x = w * (.18 + r() * .64), y = h * (.5 + (r() - .5) * .35);
      g.save(); g.translate(x, y); g.scale(sx, 1);
      const gr = g.createRadialGradient(0, -ry * .3, 0, 0, 0, ry);
      gr.addColorStop(0, `rgba(255,${222 + (r() * 20 | 0)},${214 + (r() * 20 | 0)},${.35 + r() * .3})`); gr.addColorStop(1, 'rgba(246,170,180,0)');
      g.fillStyle = gr; g.beginPath(); g.arc(0, 0, ry, 0, 7); g.fill(); g.restore();
    }
    return c;
  }

  function build() {
    const r = rng(opt.seed || 7);
    const cw = Math.max(W, H * .9), ch = Math.min(H, cw * .62);   // cloud unit keeps proportions on tall phones
    const q = Math.min(D, 1.25);                                  // sprites are soft: no need for full DPR
    sprites = LAYOUT.map(([kind, x, y, w, h, d, tone]) => {
      const sw = w * cw, sh = h * ch;
      const c = kind === 'wisp' ? wisp(sw * q | 0, sh * q | 0, r) : cloud(sw * q | 0, sh * q | 0, tone, r);
      return { c, x: x * W, y: y * H, w: sw, h: sh, d, v: (3 + d * 6) * (r() < .5 ? 1 : .7) };
    });
    grad = ctx.createLinearGradient(0, 0, 0, H);
    grad.addColorStop(0, '#4f86d6'); grad.addColorStop(.38, '#8ab3e8'); grad.addColorStop(.62, '#e9c6c6');
    grad.addColorStop(.8, '#f7b9a4'); grad.addColorStop(1, '#f093a0');
    sun = ctx.createRadialGradient(W * .7, H * .78, 0, W * .7, H * .78, Math.max(W, H) * .6);
    sun.addColorStop(0, 'rgba(255,214,160,.75)'); sun.addColorStop(.4, 'rgba(255,190,160,.25)'); sun.addColorStop(1, 'rgba(255,190,160,0)');
    const n = Math.round(Math.min(64, Math.max(18, W * H / 26000)) * (opt.petals ?? 1));
    petals = Array.from({ length: n }, () => ({
      x: Math.random() * W, y: Math.random() * H, s: 4 + Math.random() * 6, d: .4 + Math.random() * .6,
      vy: 16 + Math.random() * 34, sw: 12 + Math.random() * 30, ph: Math.random() * 6.3, fr: .6 + Math.random() * 1.2,
      rot: Math.random() * 6.3, vr: (Math.random() - .5) * 3, fl: Math.random() * 6.3, vf: 2 + Math.random() * 4,
      col: PETAL_COLORS[(Math.random() * PETAL_COLORS.length) | 0],
    }));
  }

  function resize() {
    const box = cv.getBoundingClientRect();
    W = Math.max(1, box.width); H = Math.max(1, box.height); D = Math.min(devicePixelRatio || 1, 1.5);
    cv.width = W * D | 0; cv.height = H * D | 0;
    build(); draw(0, 0);
  }

  function draw(dt, t) {
    px += (tx - px) * Math.min(1, dt * 3); py += (ty - py) * Math.min(1, dt * 3);
    ctx.setTransform(D, 0, 0, D, 0, 0);
    ctx.fillStyle = grad; ctx.fillRect(0, 0, W, H);
    ctx.fillStyle = sun; ctx.fillRect(0, 0, W, H);
    for (const s of sprites) {
      s.x += s.v * dt;
      if (s.x - s.w / 2 > W) s.x -= W + s.w;                    // wrap around when it drifts away
      ctx.drawImage(s.c, s.x - s.w / 2 - px * s.d * 36, s.y - s.h - py * s.d * 18, s.w, s.h);
    }
    for (const p of petals) {
      p.y += p.vy * dt * p.d; p.x += (Math.sin(t * p.fr + p.ph) * p.sw + 8) * dt * p.d;
      p.rot += p.vr * dt; p.fl += p.vf * dt;
      if (p.y > H + 12) { p.y = -12; p.x = Math.random() * W; }
      if (p.x > W + 12) p.x = -12;
      const f = Math.cos(p.fl);
      ctx.setTransform(D, 0, 0, D, (p.x - px * p.d * 50) * D, (p.y - py * p.d * 25) * D);
      ctx.rotate(p.rot); ctx.scale(1, Math.abs(f) < .12 ? .12 : f);
      ctx.globalAlpha = .55 + p.d * .45;
      ctx.fillStyle = p.col; ctx.beginPath(); ctx.ellipse(0, 0, p.s * p.d * 1.3, p.s * p.d * .7, 0, 0, 7); ctx.fill();
      if (f < 0) { ctx.fillStyle = 'rgba(120,40,40,.25)'; ctx.fill(); }   // darker back side of the petal
      ctx.globalAlpha = 1;
    }
  }

  function loop(now) {
    const dt = Math.min(.05, (now - last) / 1000 || 0); last = now;
    draw(dt, now / 1000);
    raf = requestAnimationFrame(loop);
  }
  function start() { if (!raf && !opt.reduce && !document.hidden) { last = performance.now(); raf = requestAnimationFrame(loop); } }
  function stop() { cancelAnimationFrame(raf); raf = 0; }

  addEventListener('pointermove', (e) => { tx = e.clientX / innerWidth - .5; ty = e.clientY / innerHeight - .5; }, { passive: true });
  document.addEventListener('visibilitychange', () => (document.hidden ? stop() : start()));   // pause on a hidden tab
  let rt; addEventListener('resize', () => { clearTimeout(rt); rt = setTimeout(resize, 120); });
  resize(); start();
  return { resize, start, stop };
}

createSky($('sky'), { reduce, petals: .8 });
layout(); play(); start();
</script>
</body>
</html>

Похожие