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

Эффекты и шейдерыТёмныйТипографикаБесплатно

Заголовки, проступающие из тумана

Огромные слова при прокрутке собираются из размытой, рваной массы в чёткие буквы: три разных SVG-фильтра на тексте.

Заголовки, проступающие из тумана
Промпт
Добавь в мой проект эффект «Заголовки, проступающие из тумана» (Codrops, автор Manoela Ilic, лицензия MIT). Ниже HTML, CSS и JavaScript одним файлом. Слова это обычные заголовки `<h2 data-filter="goo-N">`, а в скрытом `<svg class="hidden">` лежат фильтры `goo-1`, `goo-2`, `goo-3`. В каждом фильтре цепочка: `feGaussianBlur` (размытие), `feColorMatrix` (матрица, которая «слипает» размытое обратно в чёткую форму, ключевое значение в последней строке, например `0 0 0 15 -8`), у двух последних ещё `feTurbulence` (шум) и `feDisplacementMap` (смещение пикселей по шуму), в конце `feComposite operator="atop"`. Атрибут `data-filter` у слова должен совпадать с `id` его фильтра.

Как это работает: для каждого слова создаётся GSAP-таймлайн с `scrollTrigger: { trigger: слово, start: 'center bottom' }`. Он анимирует не сам элемент, а объект `vals` (`stdDeviation`, `scale`, `baseFrequency`) от стартовых значений к нулю, а в `onUpdate` числа записываются в атрибуты фильтра через `setAttribute`. Заодно проявляется `opacity`. Стартовые значения лежат в объекте `filters`: чем больше `stdDeviation` и `scale`, тем сильнее «туман» в начале. Кнопка «Повторить» — следующий элемент после слова, она вызывает `tl.restart()`.

Что менять: слова и их размеры (`font-size` в `.word`), шрифт (в примере Playfair Display и Unbounded, нужны жирные начертания), цвета (`--c1`…`--c3`), длительность (`duration: 2`) и кривую (`ease`), стартовые значения размытия и смещения в `filters`, момент запуска (`start`). Если нужен ещё один вариант, добавь новый `<filter>` с другим `baseFrequency` в `feTurbulence` и новую запись в `filters`. Если проект на React: подключи `gsap` и `ScrollTrigger`, зарегистрируй плагин один раз, создавай таймлайны внутри `useEffect` (или `useGSAP`) в `gsap.context`, а при размонтировании вызывай `ctx.revert()`, чтобы снять ScrollTrigger; SVG с фильтрами положи в корень страницы один раз, а не в каждый компонент, и следи, чтобы `id` фильтров были уникальными. В JSX атрибуты пиши в camelCase: `stdDeviation`, `baseFrequency`, `numOctaves`. Не убирай `style.filter = url(#...)` у слова и обязательно оставь `.hidden` на SVG с фильтрами: если спрятать его через `display: none`, фильтры в части браузеров перестанут работать.
Покажи, где на моей странице использовать этот эффект, и подставь мои заголовки.

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

Тёмная страница с тремя огромными словами. Пока слово не показалось на экране, оно скрыто, а когда доезжает до нижнего края окна, начинается сборка: сначала это сильно размытая клякса, потом буквы стягиваются, шум рвёт их края и только в конце они становятся чёткими. Первое слово просто собирается из размытия, второе распадается на рваные «пиксельные» кромки, третье вытягивается, как будто на него смотрят через воду. Всё это обычный HTML-текст, к которому применён SVG-фильтр (размытие, матрица цвета, шум и карта смещения), а GSAP и ScrollTrigger на каждом кадре меняют параметры фильтра. Подходит для заголовков на лендингах, манифестов, первых экранов с крупной типографикой. Рядом с каждым словом есть кнопка «Повторить»: она нужна, чтобы эффект можно было пересмотреть без прокрутки.

Код
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>On-scroll SVG filter text</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=Playfair+Display:wght@900&family=Unbounded:wght@700&display=swap" rel="stylesheet">
<style>
  *, *::before, *::after { box-sizing: border-box; }
  :root { --bg: #282828; --text: #cfc9cb; --c1: #9dcbce; --c2: #d79fb0; --c3: #4fb3ad; }
  html, body { width: 100%; overflow-x: hidden; }
  body { margin: 0; background: var(--bg); color: var(--text); font-family: "Unbounded", sans-serif; }
  .hidden { position: absolute; width: 0; height: 0; pointer-events: none; }
  .section { min-height: 100vh; display: grid; place-items: center; padding: 2rem 3rem; overflow: hidden; }
  .word { margin: 0; line-height: 1; text-transform: uppercase; text-align: center;
          font-family: "Playfair Display", serif; font-weight: 900; font-size: clamp(3rem, 20vw, 17rem); }
  .word--1 { color: var(--c1); }
  .word--2 { color: var(--c2); mix-blend-mode: plus-lighter; }
  .word--3 { color: var(--c3); font-family: "Unbounded", sans-serif; font-size: clamp(2.5rem, 15vw, 12rem); }
  .replay { position: absolute; bottom: 2.5rem; background: none; border: 1px solid currentColor; color: var(--c1);
            font: inherit; font-size: 0.8rem; letter-spacing: 0.1em; text-transform: uppercase; padding: 0.8rem 1.4rem; cursor: pointer; }
  .replay:hover { color: var(--c2); }
  .section { position: relative; }
</style>
</head>
<body>
  <!-- SVG filters: blur + goo matrix (+ noise displacement). Attributes are animated from JS -->
  <svg class="hidden">
    <defs>
      <filter id="goo-1">
        <feGaussianBlur in="SourceGraphic" stdDeviation="0" result="blur"></feGaussianBlur>
        <feColorMatrix in="blur" mode="matrix" values="1 0 0 0 0  0 1 0 0 0  1 0 1 0 0  0 0 0 13 -6" result="goo"></feColorMatrix>
        <feComposite in="SourceGraphic" in2="goo" operator="atop"></feComposite>
      </filter>
      <filter id="goo-2">
        <feGaussianBlur in="SourceGraphic" stdDeviation="0" result="blur"></feGaussianBlur>
        <feColorMatrix in="blur" mode="matrix" values="1 0 0 0 0  0 1 0 0 0  1 0 1 0 0  0 0 0 12 -4" result="goo"></feColorMatrix>
        <feTurbulence type="turbulence" baseFrequency="1" numOctaves="1" seed="2" result="noise"></feTurbulence>
        <feDisplacementMap in="goo" in2="noise" scale="0" result="displacement"></feDisplacementMap>
        <feComposite in="SourceGraphic" in2="displacement" operator="atop"></feComposite>
      </filter>
      <filter id="goo-3">
        <feGaussianBlur in="SourceGraphic" stdDeviation="0" result="blur"></feGaussianBlur>
        <feColorMatrix in="blur" mode="matrix" values="1 0 0 0 0  0 1 0 0 0  1 0 1 0 0  0 0 0 15 -8" result="goo"></feColorMatrix>
        <feTurbulence type="fractalNoise" baseFrequency="0.1 0.5" numOctaves="5" seed="2" result="noise"></feTurbulence>
        <feDisplacementMap in="goo" in2="noise" scale="0" result="displacement"></feDisplacementMap>
        <feComposite in="SourceGraphic" in2="displacement" operator="atop"></feComposite>
      </filter>
    </defs>
  </svg>

  <section class="section">
    <h2 class="word word--1" data-filter="goo-1">Волна</h2>
    <button class="replay">Повторить</button>
  </section>
  <section class="section">
    <h2 class="word word--2" data-filter="goo-2">Туман</h2>
    <button class="replay">Повторить</button>
  </section>
  <section class="section">
    <h2 class="word word--3" data-filter="goo-3">Сон</h2>
    <button class="replay">Повторить</button>
  </section>

  <script src="https://cdn.jsdelivr.net/npm/gsap@3.13.0/dist/gsap.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/gsap@3.13.0/dist/ScrollTrigger.min.js"></script>
  <script>
    // Based on Codrops OnScrollSVGFilterText (MIT), https://github.com/codrops/OnScrollSVGFilterText
    gsap.registerPlugin(ScrollTrigger);

    // Start values of the filter primitives per filter (they animate to 0 / the end value)
    const filters = {
      'goo-1': { stdDeviation: 20 },
      'goo-2': { stdDeviation: 20, scale: 100, baseFrequency: [0.1, 0.05], ease: 'expo' },
      'goo-3': { stdDeviation: 40, scale: 150, ease: 'power4', zoom: true }
    };

    document.querySelectorAll('[data-filter]').forEach((text) => {
      const id = text.dataset.filter;
      const cfg = filters[id];
      const feBlur = document.querySelector(`#${id} feGaussianBlur`);
      const feDisp = document.querySelector(`#${id} feDisplacementMap`);
      const feTurb = document.querySelector(`#${id} feTurbulence`);
      const vals = { stdDeviation: 0, scale: 0, baseFrequency: 0 };

      text.style.filter = `url(#${id})`;
      gsap.set(text, { opacity: 0 });

      const tl = gsap.timeline({
        defaults: { duration: 2, ease: cfg.ease || 'expo' },
        // every frame the current numbers are written into the SVG filter
        onUpdate: () => {
          feBlur.setAttribute('stdDeviation', vals.stdDeviation);
          if (feDisp) feDisp.setAttribute('scale', vals.scale);
          if (cfg.baseFrequency) feTurb.setAttribute('baseFrequency', vals.baseFrequency);
        },
        scrollTrigger: { trigger: text, start: 'center bottom' }
      })
      .to(vals, {
        startAt: { stdDeviation: cfg.stdDeviation, scale: cfg.scale || 0, baseFrequency: cfg.baseFrequency ? cfg.baseFrequency[0] : 0 },
        stdDeviation: 0,
        scale: 0,
        baseFrequency: cfg.baseFrequency ? cfg.baseFrequency[1] : 0
      }, 0)
      .to(text, {
        startAt: { opacity: 0, scale: cfg.zoom ? 0.9 : 1 },
        opacity: 1,
        scale: 1
      }, 0);

      // "Replay" button right after the word
      text.nextElementSibling.addEventListener('click', () => tl.restart());
    });
  </script>
</body>
</html>

Похожие