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

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

Слово, которое уходит за карточку-видео и выходит поверх неё

Рукописное слово переплетено с карточкой-видео: верх букв прячется за ней, низ идёт поверх. Прокрутка раскрывает карточку на весь экран.

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

Как устроен код. Слово лежит в двух одинаковых слоях `.w`: `.back` (тёмный, под карточкой) и `.front` (светлый, над карточкой, z-index 3). Оба на весь экран, поэтому буквы совпадают пиксель в пиксель, общее смещение задаёт переменная `--wy` на `body`. Каждый кадр функция `frame` считает прямоугольник карточки из прогресса `p` (интерполяция от маленькой карточки справа от центра до полного экрана) и ставит `.front` в `clip-path: inset(...)`: слева, справа и снизу по краям карточки, сверху по максимуму из верха карточки и «талии» слова (52% высоты букв из `getBoundingClientRect`). Прогресс двигают колесо, свайп и стрелки, сглаживание `p += (target − p) × 0.07`, автодемо — синус от времени с паузой в нулевом положении. Ролик рисует `reel(t)` на canvas 640×400. При `prefers-reduced-motion` карточка стоит на месте, ролик не анимируется.

Что менять: слово в обоих `.w span` и в скрытом `p`, шрифт (`Marck Script`, подойдёт любой крупный рукописный или жирный антиква), цвета копий (`.back span`, `.front span`), где проходит граница «за/поверх» (0.52 в `waist`), начальный размер и место карточки (`w0`, `x0`, `y0`), заголовок `.lead`. Чтобы поставить настоящее видео, замени canvas на `<video autoplay muted loop playsinline>` с `object-fit: cover` и убери `reel()`.

Если на странице есть обычная прокрутка, сделай блок высотой 250vh со sticky-сценой и считай `target` из прокрутки блока, обработчики `wheel` и `touchmove` убери. Если проект на React: слово рендери дважды из одной переменной, `ref` на карточку и светлую копию, расчёт `clip-path` делай в цикле `requestAnimationFrame` внутри `useEffect` и отменяй его в очистке.
Предложи слово и заголовок под мой продукт и что показать в карточке вместо процедурного ролика.

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

На светлом первом экране под заголовком лежит огромное рукописное слово, а прямо на нём — карточка с роликом. Слово и карточка переплетены: верхние части букв уходят за карточку, а нижние проходят поверх неё светлым цветом, как будто надпись продета сквозь картинку. При прокрутке карточка съезжает к центру и растёт до размеров экрана, слово поднимается вместе с ней и остаётся вплетённым. Прокрутили назад — карточка возвращается на место. Без ввода карточка сама раскрывается и сворачивается.

Без библиотек: слово нарисовано дважды, светлая копия обрезана clip-path по пересечению карточки и нижней половины букв, граница пересчитывается каждый кадр. «Видео» процедурное: canvas с фигурой, солнцем, движущейся тенью и зерном. Подходит для первого экрана студии, бренда, шоурила, портфолио. Приём подсмотрен на oddlymade.webflow.io.

Код
<!-- 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>Word Behind Card</title>
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Marck+Script&family=Playfair+Display:wght@500&family=Inter:wght@500;700&display=swap">
<style>
*, *::before, *::after { box-sizing: border-box; }
html, body { margin: 0; height: 100%; }
body { overflow: hidden; background: #f2efe9; color: #151412; font-family: "Inter", sans-serif; touch-action: none; }
.bar { position: fixed; top: 0; left: 0; right: 0; display: flex; justify-content: space-between; padding: 20px clamp(16px, 4vw, 48px);
  font-size: .9rem; font-weight: 700; z-index: 5; }
.lead { position: fixed; top: 12vh; left: 0; right: 0; margin: 0 auto; padding: 0 16px; max-width: 20ch; text-align: center;
  font: 500 clamp(1.7rem, 3.6vw, 3.2rem)/1.05 "Playfair Display", serif; letter-spacing: -.01em; }
/* the same word twice: .back sits under the card, .front sits over it and is clipped to (card ∩ lower half of the word) */
.w { position: fixed; inset: 0; display: grid; place-items: center; pointer-events: none; user-select: none; }
.w span { display: block; font: 400 clamp(8rem, 27vw, 24rem)/1 "Marck Script", cursive; white-space: nowrap; transform: translateY(var(--wy, 18vh)) rotate(-6deg); }
.back span { color: #151412; }
.front { z-index: 3; }
.front span { color: #f2efe9; text-shadow: 0 0 1px #f2efe9; }
.card { position: fixed; left: 0; top: 0; z-index: 2; overflow: hidden; border-radius: 6px; background: #8f1d10; will-change: transform, width, height; }
.card canvas { position: absolute; inset: 0; width: 100%; height: 100%; display: block; object-fit: cover; }
.play { position: absolute; right: 16px; top: 16px; width: 56px; height: 56px; border-radius: 50%; background: #f2efe9; border: 0; cursor: pointer;
  display: grid; place-items: center; z-index: 4; }
.play::before { content: ""; border-left: 14px solid #151412; border-top: 9px solid transparent; border-bottom: 9px solid transparent; margin-left: 4px; }
.play:focus-visible { outline: 3px solid #151412; outline-offset: 3px; }
.cap { position: fixed; bottom: 20px; left: clamp(16px, 4vw, 48px); right: clamp(16px, 4vw, 48px); display: flex; justify-content: space-between;
  font-size: 11px; letter-spacing: .12em; text-transform: uppercase; color: #6d665c; z-index: 1; }
.sr { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); }
@media (max-width: 600px) { .w span { font-size: 36vw; } .lead { top: 10vh; } }
</style>
</head>
<body>
<header class="bar"><span>Мастерская «Охра»</span><span>Связаться ↗</span></header>
<h1 class="lead">Делаем бренды, которые хочется трогать руками</h1>
<p class="sr">живое</p>
<div class="w back" aria-hidden="true"><span>живое</span></div>
<div class="card" id="card"><canvas id="reel" width="640" height="400" aria-hidden="true"></canvas><button class="play" type="button" aria-label="Смотреть шоурил"></button></div>
<div class="w front" id="front" aria-hidden="true"><span>живое</span></div>
<div class="cap"><span>Шоурил 2026</span><span>Колесо или свайп</span></div>

<script>
// Layered type: one word is drawn twice. The dark copy lies under the card, the light copy lies over it and is
// clipped to the intersection of the card and the lower part of the word: the upper strokes hide behind the card,
// the lower ones run across it. Progress (wheel / swipe / autodemo) moves the card and grows it to full screen.
const reduce = matchMedia('(prefers-reduced-motion: reduce)').matches;
const card = document.getElementById('card'), front = document.getElementById('front');
const word = front.querySelector('span');
const lerp = (a, b, t) => a + (b - a) * t;
const ease = (t) => t < 0.5 ? 4 * t * t * t : 1 - (-2 * t + 2) ** 3 / 2;

// --- progress: wheel and swipe move target, an autodemo ping-pongs it when idle ---
let p = 0, target = 0, lastInput = -1e9;
const nudge = (d) => { target = Math.max(0, Math.min(1, target + d)); lastInput = performance.now(); };
addEventListener('wheel', (e) => { e.preventDefault(); nudge(e.deltaY / 1600); }, { passive: false });
let ty = null;
addEventListener('touchstart', (e) => (ty = e.touches[0].clientY), { passive: true });
addEventListener('touchmove', (e) => { if (ty !== null) { nudge((ty - e.touches[0].clientY) / 700); ty = e.touches[0].clientY; } }, { passive: true });
addEventListener('keydown', (e) => { if (e.key === 'ArrowDown') nudge(0.1); if (e.key === 'ArrowUp') nudge(-0.1); });

// --- the "video": a procedural reel (sun, figure, moving shadow, grain) drawn on a 640×400 canvas ---
const rc = document.getElementById('reel').getContext('2d');
function reel(t) {
  const W = 640, H = 400;
  const g = rc.createLinearGradient(0, 0, W, H); g.addColorStop(0, '#b3261a'); g.addColorStop(1, '#5e1109');
  rc.fillStyle = g; rc.fillRect(0, 0, W, H);
  const sx = 420 + Math.sin(t * 0.6) * 60;
  rc.fillStyle = '#e8b04a'; rc.beginPath(); rc.arc(sx, 120, 70, 0, 7); rc.fill();                       // sun
  rc.fillStyle = 'rgba(0,0,0,.28)'; rc.beginPath();                                                      // shadow on the wall
  rc.ellipse(260 - (sx - 420) * 0.6, 230, 70, 150, 0.25, 0, 7); rc.fill();
  rc.fillStyle = '#f2efe9'; rc.beginPath(); rc.ellipse(300, 150, 26, 32, 0, 0, 7); rc.fill();            // figure: head
  rc.beginPath(); rc.moveTo(262, 400); rc.quadraticCurveTo(268, 210, 300, 196); rc.quadraticCurveTo(334, 210, 340, 400); rc.fill(); // body
  rc.fillStyle = '#151412'; rc.fillRect(272, 300, 56, 100);                                               // trousers
  for (let i = 0; i < 900; i++) { rc.fillStyle = Math.random() < 0.5 ? 'rgba(255,255,255,.05)' : 'rgba(0,0,0,.07)'; rc.fillRect(Math.random() * W, Math.random() * H, 2, 2); } // grain
}

function frame(now) {
  frame.t0 ??= now; const t = (now - frame.t0) / 1000;   // time since the first frame
  if (now - lastInput > 2500) target = reduce ? 0 : Math.max(0, Math.sin(t * 0.8 - 2)); // idle: rest, grow to full screen, come back
  p += (target - p) * (reduce ? 1 : 0.07);
  const W = innerWidth, H = innerHeight, mobile = W < 600, k = ease(p);

  // card: small and off-centre → full screen
  const w0 = mobile ? W * 0.62 : W * 0.3, h0 = w0 * (mobile ? 1.15 : 0.62);
  const x0 = mobile ? W * 0.5 : W * 0.56, y0 = H * (mobile ? 0.6 : 0.64);
  const w = lerp(w0, W, k), h = lerp(h0, H, k), cx = lerp(x0, W / 2, k), cy = lerp(y0, H / 2, k);
  const L = cx - w / 2, T = cy - h / 2;
  Object.assign(card.style, { width: `${w}px`, height: `${h}px`, transform: `translate(${L}px, ${T}px)`, borderRadius: `${lerp(6, 0, k)}px` });

  // the word floats up a little as the card grows (same value for both copies so they stay in register)
  const wy = lerp(mobile ? 14 : 18, 4, k);
  document.body.style.setProperty('--wy', `${wy}vh`);

  // clip the light copy to: card rectangle ∩ everything below the word's waist line
  const r = word.getBoundingClientRect();
  const waist = r.top + r.height * 0.52;
  const top = Math.max(T, waist);
  front.style.clipPath = `inset(${top}px ${W - (L + w)}px ${H - (T + h)}px ${L}px)`;

  if (!reduce || !frame.drawn) { reel(t); frame.drawn = true; }
  requestAnimationFrame(frame);
}
requestAnimationFrame(frame);
</script>
</body>
</html>

Похожие