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

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

Фиксированный логотип, который уступает место тексту, проезжающему под ним

Логотип закреплён в углу и каждый раз по-разному исчезает, когда под него заезжает блок текста, а потом возвращается.

Фиксированный логотип, который уступает место тексту, проезжающему под ним
Промпт
Добавь на мою страницу эффект «Фиксированный логотип уступает место тексту, проезжающему под ним» (по мотивам Codrops ContextAwareLogoAnimationScroll, MIT). Ниже готовая страница на GSAP 3.13.0 и ScrollTrigger (jsdelivr), без других библиотек: буквы режет простая функция. Сначала перенеси её как есть и проверь: при скролле логотип в углу по-разному исчезает, когда под него заезжает текстовый блок, и возвращается, когда блок уехал. Потом меняй.

Как устроен код. Логотип `[data-fixed]` закреплён через `position: fixed`. Массив `effects` содержит шесть пар функций `onEnter` и `onLeave`: сжатие, размытие, подъём за маску (`.oh`), разлёт букв, исчезновение с конца и возврат через случайные буквы, поворот на углу. Перед каждым эффектом `reset` возвращает исходный HTML и стили, поэтому эффекты не накапливаются, а текущая анимация убивается (`stop`). Для каждого блока `.inner` создаётся свой ScrollTrigger; его старт считается от текущего верха логотипа (`top + 30px`), так что срабатывание привязано к самому логотипу, а не к размеру окна. Эффект выбирается по номеру блока по кругу.

Что менять: сам логотип (текст или SVG, для эффектов с буквами нужен текст), порядок и набор эффектов в `effects`, смещения `+30` и `-10`, `duration` и `ease` в `P`, положение и цвет логотипа в `.logo`.

Если проект на React: логотип держи отдельным компонентом с `ref`, эффекты запускай в `useEffect` после `load`, при размонтировании убей триггеры. Если у логотипа есть ссылка, оставь её внутри `html0`: `reset` вернёт её на место.
Покажи, где на моём сайте такой логотип будет работать лучше всего.

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

Логотип закреплён в углу страницы и не мешает чтению: стоит абзацу доехать до него, как он уходит с дороги. Способов шесть, и они чередуются от блока к блоку: логотип сжимается и тает, размывается, уезжает вверх за маску, рассыпается по буквам, пропадает с конца и возвращается через случайные буквы, поворачивается на углу и падает вниз. Когда текст проехал, логотип возвращается.

Анимацию запускают ScrollTrigger'ы, привязанные не к началу страницы, а к положению самого логотипа на экране, поэтому реакция всегда точно в тот момент, когда текст его касается. Годится для лонгридов, сайтов студий, редакционных страниц с фиксированной шапкой.

Код
<!-- Pictures come from picsum.photos as placeholders: replace the URLs with your own images. -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Context-Aware Logo Scroll</title>
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Instrument+Serif:ital@0;1&family=Inter:wght@400;600&display=swap">
<style>
*, *::before, *::after { box-sizing: border-box; }
html, body { margin: 0; }
body { background: #f3efe6; color: #17150f; font-family: "Inter", sans-serif; }
/* the logo is fixed in the corner; the animation reacts to what scrolls underneath it */
.logo { position: fixed; top: 1.5rem; left: 2rem; z-index: 5; font: 400 clamp(2rem, 5vw, 3.4rem) "Instrument Serif", serif; line-height: 1; mix-blend-mode: difference; color: #fff; }
.logo span { display: inline-block; }
.oh { overflow: hidden; }
.oh__inner { display: inline-block; }
.char { display: inline-block; white-space: pre; }
.block { min-height: 70vh; padding: 14vh 2rem 14vh min(14vw, 12rem); display: flex; align-items: center; }
.block p, .block h2 { max-width: 26em; margin: 0; font: 400 clamp(1.3rem, 2.4vw, 2rem)/1.35 "Instrument Serif", serif; }
.block h2 { font-size: clamp(2.4rem, 6vw, 5rem); line-height: 1; }
.block em { font-style: italic; }
.photo { height: 60vh; background: center / cover url(https://picsum.photos/id/1039/1600/900); }
</style>
</head>
<body>
<div class="logo" data-fixed><span>Weltseele</span></div>
<div class="block"><p class="inner">Ah, the <em>Weltseele</em>. The world soul. That presence rippling beneath the surface of reality, reminding us that we are not separate from the cosmic dance, but participants in it.</p></div>
<div class="block"><p class="inner">This concept isn't mumbo-jumbo; it's a reminder that our destinies are not isolated threads but luminous strands in one web of being. The real trick is to step beyond language, which carves distinctions and draws lines in the sand.</p></div>
<div class="photo"></div>
<div class="block"><p class="inner">It's the vast, shimmering other just beyond the reach of syntax. Imagine <em>shedding</em> your conditioning like a snake sheds its skin, only to find that beneath it we are the same pulsating life force.</p></div>
<div class="block"><h2 class="inner">Breaking through the thin membrane of ordinary consciousness</h2></div>
<div class="block"><p class="inner">The <em>Weltseele</em> is what hums at the core of your being when you sit in silence. It's the light in a lover's eyes, the rustling of trees, the resonance of a singing bowl. It's both the source and the destination.</p></div>
<div class="block"><p class="inner">But let's not get too serious: the <em>Weltseele</em> has a sense of humor. The universe loves <em>paradox</em>. It wears masks upon masks, just to see if you notice. And when you do, it is a cosmic wink that says: you are finally in on it.</p></div>
<div class="block"><p class="inner">Scroll back up to see every effect again.</p></div>

<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 ContextAwareLogoAnimationScroll (MIT), https://github.com/codrops/ContextAwareLogoAnimationScroll
gsap.registerPlugin(ScrollTrigger);

const logo = document.querySelector('[data-fixed]');
const blocks = document.querySelectorAll('.inner');
const html0 = logo.innerHTML;   // original markup, so we can always restore it
const P = { duration: 0.6, ease: 'power4' };

const reset = () => { logo.innerHTML = html0; logo.classList.remove('oh'); gsap.set(logo, { clearProps: 'all' }); };
const splitChars = () => {      // wrap every letter in a span
  const text = logo.textContent;
  logo.innerHTML = [...text].map((c) => `<span class="char">${c}</span>`).join('');
  return logo.querySelectorAll('.char');
};
const stop = () => { logo.tween && logo.tween.kill(); };
const done = () => (logo.tween = null);

// Every effect: onEnter = the logo reacts when a text block reaches it, onLeave = it recovers
const effects = [
  { // shrink and fade
    onEnter() { stop(); reset(); gsap.set(logo, { transformOrigin: '0% 50%' }); logo.tween = gsap.to(logo, { scale: 0, autoAlpha: 0, ...P, onComplete: done }); },
    onLeave() { stop(); logo.tween = gsap.to(logo, { scale: 1, autoAlpha: 1, ...P, onComplete: () => { reset(); done(); } }); }
  },
  { // blur and step back
    onEnter() { stop(); reset(); gsap.set(logo, { transformOrigin: '0% 50%' }); logo.tween = gsap.to(logo, { startAt: { filter: 'blur(0px)' }, filter: 'blur(5px)', scale: 0.9, duration: 0.2, ease: 'sine', onComplete: done }); },
    onLeave() { stop(); logo.tween = gsap.to(logo, { filter: 'blur(0px)', scale: 1, duration: 0.6, ease: 'expo', onComplete: () => { reset(); done(); } }); }
  },
  { // slide up behind a mask
    onEnter() { stop(); reset(); logo.innerHTML = `<div class="oh__inner">${html0}</div>`; logo.classList.add('oh');
      logo.tween = gsap.to('.oh__inner', { yPercent: -102, ...P, onComplete: done }); },
    onLeave() { stop(); logo.tween = gsap.to('.oh__inner', { startAt: { yPercent: 102 }, yPercent: 0, ...P, onComplete: () => { reset(); done(); } }); }
  },
  { // letters scatter and fade
    onEnter() { stop(); reset(); const c = splitChars();
      logo.tween = gsap.to(c, { x: () => gsap.utils.random(-50, 50), y: () => gsap.utils.random(-40, 0), autoAlpha: 0, stagger: { amount: 0.03, from: 'random' }, ...P, onComplete: done }); },
    onLeave() { stop(); logo.tween = gsap.to(logo.querySelectorAll('.char'), { x: 0, y: 0, autoAlpha: 1, stagger: { amount: 0.03, from: 'random' }, ...P, onComplete: () => { reset(); done(); } }); }
  },
  { // letters vanish from the end, then come back through random letters
    onEnter() { stop(); reset(); const c = splitChars();
      logo.tween = gsap.to(c, { duration: 0.02, ease: 'none', autoAlpha: 0, stagger: { amount: 0.25, from: 'end' }, onComplete: done }); },
    onLeave() { stop(); const chars = logo.querySelectorAll('.char'); const abc = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
      const tl = gsap.timeline({ onComplete: () => { reset(); done(); } });
      chars.forEach((ch, i) => { const orig = ch.textContent;
        tl.to(ch, { duration: 0.03, textContent: abc[Math.floor(Math.random() * 52)], autoAlpha: 1, ease: 'none' }, i * 0.05)
          .to(ch, { duration: 0.03, textContent: orig, autoAlpha: 1, ease: 'none' }, i * 0.05 + 0.04); });
      logo.tween = tl; }
  },
  { // turn on the corner and drop down
    onEnter() { stop(); reset(); gsap.set(logo, { transformOrigin: '0% 100%' });
      logo.tween = gsap.to(logo, { xPercent: -5, rotation: -90, y: () => logo.offsetWidth - logo.offsetHeight, duration: 0.6, ease: 'power4', onComplete: done }); },
    onLeave() { stop(); logo.tween = gsap.to(logo, { rotation: 0, xPercent: 0, y: 0, ...P, onComplete: () => { reset(); done(); } }); }
  }
];

// One trigger per text block: the logo's own position on the screen decides when the block "touches" it
window.addEventListener('load', () => {
  const top = logo.getBoundingClientRect().top;
  blocks.forEach((block, i) => {
    const fx = effects[i % effects.length];
    ScrollTrigger.create({
      trigger: block, start: () => `top ${top + 30}px`, end: () => `bottom ${top - 10}px`,
      onEnter: fx.onEnter, onEnterBack: fx.onEnter, onLeave: fx.onLeave, onLeaveBack: fx.onLeave
    });
  });
});
</script>
</body>
</html>

Похожие