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

Эффекты и шейдерыСветлыйЯркийРетро и пиксельБесплатно

Бумажный коллаж, который клеится при прокрутке

Бумажные вырезки приклеиваются по одной при прокрутке, рывками stop-motion 10 кадров в секунду. Фон меняется по главам.

Бумажный коллаж, который клеится при прокрутке
Промпт
Добавь на мою страницу эффект «Бумажный коллаж, который клеится при прокрутке» (Сергей Дургалян, MIT). Ниже готовая страница без библиотек. Сначала перенеси её как есть и проверь: при прокрутке вокруг вывески «каникулы» по одной приклеиваются бумажные вырезки с белым краем и тенью, движение рваное (10 кадров в секунду), фон и подпись меняются по главам (утро, пляж, ночь), солнце и чайки к ночи отклеиваются, при прокрутке назад всё разбирается, без ввода история проигрывается сама. Потом меняй.

Как устроен код. Страница прокручивается внутри `.scroller`, в нём высокий `.track` (400vh) и прилипающая сцена `.stage` (`position: sticky`). Прогресс `0…1` = `scrollTop` / максимальная прокрутка. Вырезки описаны в `SHAPES` (SVG-разметка в квадрате 100×100), раскладка — в `PIECES`: фигура, x и y в процентах, размер в vmin, поворот, момент появления и момент, когда она отклеивается. Фильтр `#paper` делает «вырезку»: `feMorphology dilate` расширяет силуэт, его заливают белым (край бумаги), размытая копия со сдвигом даёт тень. Фильтр стоит на группе, поэтому белый край обходит фигуру целиком, без швов внутри. `render()` вызывается 10 раз в секунду: каждая вырезка проигрывает кадры `STICK` (приклеивание: масштаб, поворот, сдвиг) или `PEEL` (отклеивание), а потом слегка «кипит» — смещается на доли градуса каждый кадр. Главы (`CHAPTERS`) меняют фон и подпись жёстко, без плавного перехода. Автодемо считает прогресс по времени (`SWEEP`, `HOLD`) и продолжает с того места, где посетитель остановился.

Что менять: фигуры в `SHAPES` (любая SVG-разметка в квадрате 100×100), их места и порядок в `PIECES`, главы и цвета фона в `CHAPTERS`, частоту кадров `FPS` (8–12 — заметный stop-motion), кадры `STICK` и `PEEL`, толщину белого края (`radius` у `feMorphology`), длину прокрутки (высота `.track`), вывеску в `.logo`. Море растянуто полосой на всю ширину (класс `band`). На вертикальных экранах вырезки крупнее (`--u`). При `prefers-reduced-motion` вырезки появляются без анимации и не дрожат, автодемо выключено.

Если проект на React: держи `PIECES` как массив данных, рендери вырезки через `map` с `ref` на каждый элемент, а цикл с `requestAnimationFrame` и пересчётом 10 раз в секунду запускай в `useEffect` и меняй `style.transform` напрямую через ref, без state. Фильтр `#paper` положи один раз в корень страницы. Если в проекте уже есть GSAP ScrollTrigger, прогресс можно брать из него.
Предложи сюжет из 3 глав и набор вырезок под мой продукт.

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

В центре экрана небольшая бумажная вывеска продукта, а вокруг неё при прокрутке по одному «приклеиваются» вырезки: холмы, облака, солнце-цветок, пальма, потом море, зонтик, лодка, чайки, мяч, а ночью луна, планета и звёзды. Каждая вырезка влетает как в stop-motion мультфильме: несколько рваных кадров с поворотом и пружинкой, а приклеившись, продолжает чуть подрагивать. Фон меняется по главам (утро, пляж, ночь), солнце и чайки к ночи отклеиваются и улетают. При прокрутке назад коллаж разбирается. Без ввода история прокручивается сама за 6 секунд.

Все вырезки — встроенные SVG, нарисованные кодом, а белый край вырезки и тень даёт один SVG-фильтр. Сцена нарочно обновляется 10 раз в секунду, а не 60: так и получается рывок, как у покадровой анимации. Приём подсмотрен на amo.co, фигуры, сцена и тексты здесь свои. Подходит для лендинга детского или туристического продукта, промо-страницы, сторителлинга «как это работает» по главам.

Код
<!-- 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>Paper Cutout Collage</title>
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Unbounded:wght@900&family=Inter:wght@500;700&display=swap">
<style>
*, *::before, *::after { box-sizing: border-box; }
html, body { margin: 0; height: 100%; }
body { overflow: hidden; font-family: "Inter", sans-serif; color: #1c1a2e; background: #8fd3ff; }
.scroller { position: fixed; inset: 0; overflow-y: auto; overscroll-behavior: contain; }
.track { height: 400vh; }
/* the scene stays pinned while the track scrolls under it */
.stage { position: sticky; top: 0; height: 100vh; height: 100dvh; overflow: hidden; background: var(--bg, #8fd3ff);
  --u: 1vmin; }
@media (orientation: portrait) { .stage { --u: 1.35vmin; } }   /* tall phones: bigger pieces */
/* paper grain over everything */
.stage::after { content: ""; position: absolute; inset: 0; pointer-events: none; opacity: .18; mix-blend-mode: multiply;
  background: repeating-linear-gradient(115deg, #0000 0 3px, #0002 3px 4px), radial-gradient(#0003 1px, #0000 1.5px) 0 0 / 7px 7px; }
.cut { position: absolute; left: var(--x); top: var(--y); width: calc(var(--s) * var(--u)); aspect-ratio: 1; will-change: transform;
  transform: translate(-50%, -50%) scale(0); }
/* the sea is a stretched strip across the whole bottom edge */
.cut.band { width: 120vw; height: 24vh; aspect-ratio: auto; top: auto; bottom: -14vh; }
.cut svg { width: 100%; height: 100%; overflow: visible; display: block; }
.logo { position: absolute; left: 50%; top: 47%; z-index: 5; padding: .5em .9em .6em; background: #fff8ec; color: #ff4d2e;
  font: 900 clamp(1.6rem, 6vw, 4.4rem)/1 "Unbounded", sans-serif; letter-spacing: -.02em; border-radius: 6px;
  box-shadow: 0 0 0 5px #fff, 3px 6px 0 5px #0003; transform: translate(-50%, -50%) rotate(-3deg); }
.logo small { display: block; margin-top: .45em; font: 700 clamp(.6rem, 1.3vw, .85rem)/1.2 "Inter", sans-serif; letter-spacing: .14em;
  text-transform: uppercase; color: #1c1a2e; }
.chapter { position: absolute; top: 20px; left: clamp(16px, 4vw, 48px); z-index: 6; font-weight: 700; letter-spacing: .14em; text-transform: uppercase; font-size: .8rem; }
.dots { position: absolute; top: 20px; right: clamp(16px, 4vw, 48px); z-index: 6; display: flex; gap: 8px; }
.dots i { width: 10px; height: 10px; border-radius: 50%; border: 2px solid currentColor; }
.dots i.on { background: currentColor; }
.hint { position: absolute; bottom: 18px; left: 50%; z-index: 6; transform: translateX(-50%); white-space: nowrap; padding: 6px 14px;
  background: #fff8ec; color: #1c1a2e; border-radius: 999px; font-size: .8rem; letter-spacing: .14em; text-transform: uppercase; font-weight: 700; }
</style>
</head>
<body>
<svg width="0" height="0" aria-hidden="true" style="position:absolute">
  <!-- paper cutout: white margin around the union of the shape (dilate) + a soft offset shadow -->
  <filter id="paper" x="-25%" y="-25%" width="150%" height="150%">
    <feMorphology in="SourceAlpha" operator="dilate" radius="2.6" result="edge"/>
    <feFlood flood-color="#fff"/><feComposite in2="edge" operator="in" result="white"/>
    <feOffset in="edge" dx="1.6" dy="2.8"/><feGaussianBlur stdDeviation="1.6" result="blur"/>
    <feFlood flood-color="#000" flood-opacity=".32"/><feComposite in2="blur" operator="in" result="shadow"/>
    <feMerge><feMergeNode in="shadow"/><feMergeNode in="white"/><feMergeNode in="SourceGraphic"/></feMerge>
  </filter>
</svg>
<div class="scroller" id="scroller">
  <div class="track">
    <div class="stage" id="stage">
      <div class="chapter" id="chapter">Глава 1 · Утро</div>
      <div class="dots" aria-hidden="true"><i class="on"></i><i></i><i></i></div>
      <div class="logo">каникулы<small>отпуск, собранный по кусочкам</small></div>
      <div class="hint">Прокрутите вниз</div>
    </div>
  </div>
</div>

<script type="module">
// A paper collage that glues itself together while you scroll.
// Every piece is an inline SVG with a "paper" filter (white cut margin + shadow). The scene is redrawn
// at 10 fps only: pieces jump in with a few hand-made keyframes and keep "boiling" slightly, like stop-motion.
const FPS = 10;
const CHAPTERS = [
  { at: 0, name: 'Глава 1 · Утро', bg: '#8fd3ff', fg: '#1c1a2e' },
  { at: 0.34, name: 'Глава 2 · Пляж', bg: '#ffcf3f', fg: '#1c1a2e' },
  { at: 0.68, name: 'Глава 3 · Ночь', bg: '#33237a', fg: '#fff8ec' },
];
const reduce = matchMedia('(prefers-reduced-motion: reduce)').matches;

// --- procedural cutouts, all in a 100×100 box ---
const petals = (n, r, rx, ry, fill) => Array.from({ length: n }, (_, i) =>
  `<ellipse cx="50" cy="${50 - r}" rx="${rx}" ry="${ry}" fill="${fill}" transform="rotate(${(360 / n) * i} 50 50)"/>`).join('');
const SHAPES = {
  sun: petals(12, 30, 9, 16, '#ffb000') + petals(12, 27, 6, 12, '#ffe14d') + '<circle cx="50" cy="50" r="22" fill="#ff6b2e"/>' +
    '<circle cx="43" cy="46" r="3" fill="#1c1a2e"/><circle cx="57" cy="46" r="3" fill="#1c1a2e"/><path d="M41 56q9 8 18 0" stroke="#1c1a2e" stroke-width="3" fill="none" stroke-linecap="round"/>',
  cloud: '<g fill="#f4f9ff"><circle cx="32" cy="58" r="18"/><circle cx="52" cy="46" r="24"/><circle cx="72" cy="58" r="16"/><rect x="20" y="56" width="62" height="20" rx="10"/></g>',
  palm: '<path d="M48 96 C50 74 54 56 52 38" stroke="#9a5b2c" stroke-width="9" fill="none" stroke-linecap="round"/>' +
    '<g fill="#27b36a"><path d="M52 38 C38 20 16 24 8 36 C24 30 38 32 52 38z"/><path d="M52 38 C66 18 88 22 94 36 C80 30 66 32 52 38z"/>' +
    '<path d="M52 38 C44 26 34 8 46 4 C46 18 50 28 52 38z"/><path d="M52 38 C64 30 84 40 86 58 C74 46 64 42 52 38z"/><path d="M52 38 C40 34 20 44 18 60 C30 48 40 42 52 38z"/></g>' +
    '<circle cx="50" cy="42" r="4" fill="#7a3e1a"/><circle cx="57" cy="41" r="4" fill="#7a3e1a"/>',
  hill: '<path d="M0 100 C10 58 40 40 60 52 C76 60 90 70 100 100z" fill="#3fbf6b"/><path d="M22 100 C34 76 52 70 70 100z" fill="#2a9d55"/>',
  wave: '<path d="M0 70 q12.5 -16 25 0 t25 0 t25 0 t25 0 V100 H0z" fill="#2f7cf6"/><path d="M0 84 q12.5 -12 25 0 t25 0 t25 0 t25 0 V100 H0z" fill="#1e5bd0"/>',
  umbrella: '<path d="M50 30 V96" stroke="#5a3b22" stroke-width="5" stroke-linecap="round"/><path d="M8 46 Q50 -4 92 46z" fill="#ff4d6d"/>' +
    '<path d="M36 46 Q50 4 50 21 Q50 4 64 46z" fill="#fff8ec"/><path d="M8 46 q7 -7 14 0 t14 0 t14 0 t14 0 t14 0 t14 0" fill="#ff4d6d"/>',
  boat: '<path d="M12 66 H88 L76 84 H24z" fill="#ff6b2e"/><path d="M50 10 V64 H18z" fill="#fff8ec"/><path d="M54 18 V64 H82z" fill="#2f7cf6"/>',
  gull: '<path d="M8 56 Q28 30 50 54 Q72 30 92 56" stroke="#1c1a2e" stroke-width="8" fill="none" stroke-linecap="round" stroke-linejoin="round"/>',
  ball: '<circle cx="50" cy="50" r="40" fill="#fff8ec"/><path d="M50 10 A40 40 0 0 1 90 50 L50 50z" fill="#ff4d6d"/><path d="M50 90 A40 40 0 0 1 10 50 L50 50z" fill="#2f7cf6"/><circle cx="50" cy="50" r="8" fill="#ffcf3f"/>',
  moon: '<path d="M64 10 A42 42 0 1 0 90 72 A34 34 0 1 1 64 10z" fill="#fff1a8"/>',
  planet: '<ellipse cx="50" cy="54" rx="46" ry="13" fill="#ff9a3d" transform="rotate(-14 50 54)"/><circle cx="50" cy="50" r="26" fill="#a06bff"/>' +
    '<path d="M24 50 A26 26 0 0 0 76 50" fill="#7f48e8"/><path d="M7 64 Q50 72 93 44" stroke="#ff9a3d" stroke-width="7" fill="none" stroke-linecap="round"/>',
  star: '<path d="M50 6 L61 38 L95 38 L67 58 L78 92 L50 72 L22 92 L33 58 L5 38 L39 38z" fill="#ffe14d"/>',
};
// [shape, x%, y%, size vmin, base rotation, appears at, peels off at]
const PIECES = [
  ['hill', 24, 90, 70, 0, 0.02], ['hill', 82, 92, 62, 0, 0.06], ['cloud', 20, 18, 24, -6, 0.1], ['sun', 80, 22, 28, 8, 0.14, 0.66],
  ['cloud', 58, 11, 17, 5, 0.19, 0.7], ['palm', 10, 60, 34, -4, 0.24],
  ['wave', 50, 80, 66, 0, 0.36], ['umbrella', 72, 68, 28, 10, 0.4], ['boat', 34, 80, 18, -8, 0.45], ['gull', 34, 30, 11, -10, 0.5, 0.7],
  ['gull', 44, 23, 8, 12, 0.53, 0.72], ['palm', 90, 58, 30, 6, 0.57], ['ball', 58, 86, 10, 0, 0.61],
  ['moon', 80, 20, 22, -12, 0.72], ['planet', 26, 16, 22, 10, 0.77], ['star', 54, 24, 8, 0, 0.82], ['star', 92, 40, 7, 14, 0.86], ['star', 8, 10, 7, -8, 0.9],
];

// stop-motion keyframes for "glue on": [scale, extra rotation°, dy in vmin]
const STICK = [[1.45, 18, -6], [1.2, -9, -2], [0.92, 5, 0.6], [1.04, -2, 0], [1, 0, 0]];
const PEEL = [[1.06, -6, -1], [1.14, -16, 4], [1.0, -30, 16], [0.8, -48, 40], [0, -60, 60]];

const stage = document.getElementById('stage');
const scroller = document.getElementById('scroller');
const pieces = PIECES.map(([shape, x, y, s, rot, at, until = 2], i) => {
  const el = document.createElement('div'); el.className = 'cut';
  el.style.cssText = `--x:${x}%;--y:${y}%;--s:${s};z-index:${i < 2 ? 1 : 2}`;
  const band = shape === 'wave';
  if (band) el.classList.add('band');
  el.innerHTML = `<svg viewBox="${band ? '0 60 100 40' : '0 0 100 100'}" preserveAspectRatio="${band ? 'none' : 'xMidYMid meet'}" aria-hidden="true"><g filter="url(#paper)">${SHAPES[shape]}</g></svg>`;
  stage.insertBefore(el, stage.querySelector('.logo'));
  return { el, rot, at, until, on: false, step: STICK.length - 1, seed: i * 7.13 };
});
pieces.forEach((p) => { p.step = PEEL.length - 1; });   // everything starts "peeled off" (hidden)

// --- scroll progress, with an autodemo when nobody scrolls ---
const SWEEP = 9000, HOLD = 2600;            // autodemo: whole story in 9 s, then hold the finished collage
let lastInput = -1e9, autoStart = null, lastTick = 0, tick = 0, chapterIdx = -1;
['wheel', 'touchstart', 'keydown', 'pointerdown'].forEach((ev) => addEventListener(ev, () => { lastInput = performance.now(); autoStart = null; }, { passive: true }));
const maxScroll = () => scroller.scrollHeight - scroller.clientHeight;

function render() {
  const progress = Math.min(1, scroller.scrollTop / Math.max(1, maxScroll()));
  // chapters: background and caption switch in hard steps
  const c = CHAPTERS.reduce((acc, ch, i) => (progress >= ch.at ? i : acc), 0);
  if (c !== chapterIdx) {
    chapterIdx = c;
    stage.style.setProperty('--bg', CHAPTERS[c].bg); stage.style.color = CHAPTERS[c].fg;
    document.getElementById('chapter').textContent = CHAPTERS[c].name;
    stage.querySelectorAll('.dots i').forEach((d, i) => d.classList.toggle('on', i <= c));
  }
  for (const p of pieces) {
    const want = progress >= p.at && progress < p.until;
    if (want !== p.on) { p.on = want; p.step = reduce ? 99 : 0; }
    const frames = p.on ? STICK : PEEL;
    const [sc, r, dy] = frames[Math.min(p.step, frames.length - 1)];
    p.step++;
    // "boiling": once glued, each frame the piece twitches by a fraction of a degree, as if re-shot by hand
    const settled = p.on && p.step > frames.length;
    const wob = settled && !reduce ? Math.sin(tick * 2.3 + p.seed) * 1.2 : 0;
    const jx = settled && !reduce ? Math.sin(tick * 1.7 + p.seed * 3) * 0.15 : 0;
    p.el.style.transform = `translate(calc(-50% + ${jx}vmin), calc(-50% + ${dy}vmin)) rotate(${p.rot + r + wob}deg) scale(${sc})`;
  }
}

function loop(now) {
  if (!reduce && now - lastInput > 2500) {
    // autodemo: time-based, continues from wherever the visitor left the scroll
    const max = maxScroll();
    if (autoStart === null) autoStart = now - (scroller.scrollTop / Math.max(1, max)) * SWEEP;
    const t = now - autoStart;
    if (t > SWEEP + HOLD) autoStart = now;
    scroller.scrollTop = Math.min(1, t / SWEEP) * max;
  }
  if (now - lastTick >= 1000 / FPS) { lastTick = now; tick++; render(); }  // 10 fps on purpose
  requestAnimationFrame(loop);
}
render();
requestAnimationFrame(loop);
</script>
</body>
</html>

Похожие