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

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

Почтовые марки с глубиной резкости

Работы лежат почтовыми марками с зубчатым краем: прокрутка ведёт по ленте, в фокусе одна марка, остальные размыты как в объективе.

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

Как устроен код. Марка — SVG 300×380: контур из `perforated(w, h, r, step)` (прямоугольник с полукруглыми вырезами по краям, дуги `A r r 0 0 0`), внутри картинка из функции `art(id)` в массиве `STAMPS`. Тень — CSS `drop-shadow` на svg. Сцена — `perspective` на контейнере; каждый кадр для марки считается расстояние `d` до фокуса и ставится `translate3d(d * ширина * SPACING, a² * 6, -a * DEPTH)`, `rotateY(-d * TURN)`, наклон и `blur(min(MAX_BLUR, a * BLUR))`, `zIndex` и прозрачность. `current` плавно догоняет `target`; колесо и перетаскивание двигают `target`, через 160 мс он округляется до ближайшей марки. Без ввода 4 секунды лента сама ездит туда-обратно; `?auto=1` включает это сразу. При `prefers-reduced-motion` покачивания нет.

Что менять: работы в `STAMPS` (плашка, рубрика, картинка — можно `<image href>` с превью), шаг, глубину, поворот и силу размытия в настройках сверху, рубрики справа, заголовок.

Если проект на React: держи разметку в компоненте, а запуск анимации и подписки на события — в `useEffect` с очисткой (`cancelAnimationFrame`, снять слушатели).
Подскажи, какие из моих работ лучше показать марками и какие плашки им дать.

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

Проекты разложены как марки в альбоме: зубчатый перфорированный край, белое поле, своя картинка у каждой. Колесо мыши, свайп или стрелки ведут ленту вбок, марка в фокусе встаёт прямо и чётко, соседние разворачиваются, уходят вглубь и размываются, как будто их сняли на объектив с малой глубиной резкости. Над маркой в фокусе появляется плашка с названием, справа подсвечивается рубрика, внизу — счётчик.

Подойдёт портфолио иллюстратора или студии, каталогу коллекции, витрине тарифов или курсов — везде, где работ немного и каждую хочется показать отдельно.

Как это устроено

  • Каждая марка — SVG: контур с полукруглыми «укусами» по краям строит функция perforated(), внутри — процедурная картинка (градиенты, шум feTurbulence, точки, крупные буквы), без файлов.
  • Лента — CSS 3D: у каждой марки свой translate3d, rotateY и blur() в зависимости от расстояния до фокуса. Тень — drop-shadow, она повторяет зубчики.
  • Прокрутка плавно догоняет цель и через 160 мс после последнего движения встаёт ровно на марку. Клик по соседней марке подвозит её в фокус.
  • Без ввода лента сама ездит туда-обратно. При «уменьшении движения» марки не покачиваются и перескакивают быстрее.

Код наш (MIT), идея подсмотрена в рилсе с подборкой личных сайтов (работы в виде марок с размытием по глубине): взят только приём, картинки и тексты свои.

Как получить такой же результат

  • Промпт содержит страницу одним файлом, она работает и двойным щелчком, без сервера.
  • Свои работы — в массиве STAMPS: плашка, рубрика и функция art, которая возвращает SVG-разметку. Вместо процедурной картинки вставьте <image href="..."> с вашим превью размером 248×300 в точке 26, 26.
  • Размытие на слабых телефонах дорогое: если лагает, уменьшите MAX_BLUR или число марок.
Код
<!-- 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>Марки с глубиной резкости</title>
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@500&family=Unbounded:wght@700;900&display=swap">
<style>
*, *::before, *::after { box-sizing: border-box; }
html, body { margin: 0; height: 100%; }
body {
  background: radial-gradient(120% 90% at 50% 45%, #f7f6f2 0%, #ecebe6 60%, #dfded8 100%);
  color: #1b1b1b; font-family: "JetBrains Mono", monospace; overflow: hidden; user-select: none;
}
.stage { position: fixed; inset: 0; perspective: 1400px; touch-action: none; cursor: grab; }
.stage.drag { cursor: grabbing; }
.stamp {
  position: absolute; left: 50%; top: 50%; width: var(--w); aspect-ratio: 300 / 380;
  margin: calc(var(--w) * -0.633) 0 0 calc(var(--w) / -2);
  will-change: transform, filter; transform-style: preserve-3d;
}
.stamp svg { display: block; width: 100%; height: 100%; filter: drop-shadow(0 14px 22px rgba(0,0,0,.16)) drop-shadow(0 2px 3px rgba(0,0,0,.12)); }
.chip {
  position: absolute; left: 50%; top: -34px; transform: translateX(-50%); white-space: nowrap;
  background: #151515; color: #f2f2ee; font-size: 11px; letter-spacing: .08em; padding: 5px 10px; border-radius: 999px;
  opacity: 0; transition: opacity .35s;
}
.stamp.on .chip { opacity: 1; }
:root { --w: clamp(170px, 22vw, 300px); }
.head { position: fixed; left: clamp(16px, 4vw, 48px); top: 28px; font-size: 12px; letter-spacing: .08em; text-transform: uppercase; }
.head b { display: block; font: 900 22px/1 "Unbounded", sans-serif; letter-spacing: -.02em; text-transform: none; margin-bottom: 6px; }
.cats { position: fixed; right: clamp(16px, 4vw, 48px); top: 50%; transform: translateY(-50%); list-style: none; margin: 0; padding: 0; font-size: 11px; letter-spacing: .14em; text-align: right; }
.cats li { padding: 14px 0; opacity: .35; transition: opacity .3s; }
.cats li.on { opacity: 1; }
.count { position: fixed; left: clamp(16px, 4vw, 48px); bottom: 26px; font-size: 12px; letter-spacing: .1em; }
.hint { position: fixed; right: clamp(16px, 4vw, 48px); bottom: 26px; font-size: 11px; letter-spacing: .14em; opacity: .5; }
@media (max-width: 640px) { .cats { display: none; } :root { --w: 58vw; } }
</style>
</head>
<body>
<div class="head"><b>Марочный альбом</b>работы студии · 2019—2026</div>
<ul class="cats"><li data-cat="ПРОДУКТ">ПРОДУКТ</li><li data-cat="ВИЗУАЛ">ВИЗУАЛ</li><li data-cat="ИГРЫ">ИГРЫ</li><li data-cat="ПЕЧАТЬ">ПЕЧАТЬ</li></ul>
<div class="stage" id="stage"></div>
<div class="count" id="count">04 / 07</div>
<div class="hint">ЛИСТАТЬ ↕</div>

<script>
// ---- settings ----
const SPACING = 0.78;   // gap between stamps, in stamp widths
const DEPTH = 260;      // px each step goes back in z
const TURN = 14;        // deg of y-rotation per step
const BLUR = 7;         // px of blur per step away from focus
const MAX_BLUR = 16;

const AUTO = new URLSearchParams(location.search).has('auto');
const reduce = matchMedia('(prefers-reduced-motion: reduce)').matches;

// Stamp art: procedural SVG, no images. Each item: label chip, category, art(id) → svg markup.
const STAMPS = [
  { chip: 'ОБРАЗЕЦ (СКОРО)', cat: 'ПРОДУКТ', art: (id) => `
    <defs><linearGradient id="g${id}" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="#e9f7c4"/><stop offset="1" stop-color="#9ccc3c"/></linearGradient>
    <filter id="n${id}"><feTurbulence type="fractalNoise" baseFrequency=".9" numOctaves="2"/><feColorMatrix values="0 0 0 0 0  0 0 0 0 .2  0 0 0 0 0  0 0 0 .35 0"/><feComposite in2="SourceGraphic" operator="in"/></filter></defs>
    <rect x="26" y="26" width="248" height="300" fill="url(#g${id})"/><rect x="26" y="26" width="248" height="300" filter="url(#n${id})" fill="#000"/>
    <text x="40" y="306" font-size="13" font-family="JetBrains Mono" fill="#2c3d0a">ТИШИНА · 01/2026</text>` },
  { chip: 'АРХИВ 2019', cat: 'ВИЗУАЛ', art: (id) => `
    <rect x="26" y="26" width="248" height="300" fill="#ddd9d0"/>
    ${Array.from({ length: 14 }, (_, i) => `<circle cx="150" cy="190" r="${12 + i * 11}" fill="none" stroke="#2a2a2a" stroke-width="${4 - i * 0.22}" opacity="${1 - i * 0.05}"/>`).join('')}
    <text x="40" y="58" font-size="15" font-family="Unbounded" font-weight="700" fill="#2a2a2a">АРХИВ</text>` },
  { chip: 'НОВОЕ РЕМЕСЛО', cat: 'ПЕЧАТЬ', art: (id) => `
    <rect x="26" y="26" width="248" height="300" fill="#f4f1e8"/>
    <text x="150" y="150" text-anchor="middle" font-size="110" font-family="Unbounded" font-weight="900" fill="#151515">ДО</text>
    <text x="150" y="270" text-anchor="middle" font-size="110" font-family="Unbounded" font-weight="900" fill="#151515">М</text>
    <text x="40" y="312" font-size="12" font-family="JetBrains Mono" fill="#151515">№ 3 · 24 ₽</text>` },
  { chip: 'ЗАКАТ', cat: 'ВИЗУАЛ', art: (id) => `
    <defs><linearGradient id="s${id}" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="#ffcf8a"/><stop offset=".6" stop-color="#ff7a59"/><stop offset="1" stop-color="#7d3d6b"/></linearGradient></defs>
    <rect x="26" y="26" width="248" height="300" fill="url(#s${id})"/><circle cx="150" cy="170" r="52" fill="#fff3d6"/>
    <path d="M26 250 L90 190 L130 225 L190 160 L274 240 L274 326 L26 326 Z" fill="#41203a"/>
    <path d="M26 285 L110 245 L170 280 L274 255 L274 326 L26 326 Z" fill="#2a1427"/>` },
  { chip: 'ИГРА «ТОЧКИ»', cat: 'ИГРЫ', art: (id) => `
    <rect x="26" y="26" width="248" height="300" fill="#1f3fbf"/>
    ${Array.from({ length: 12 * 15 }, (_, k) => { const x = k % 12, y = Math.floor(k / 12); const r = 2 + 6 * Math.abs(Math.sin(x * 0.55 + y * 0.35)); return `<circle cx="${40 + x * 20}" cy="${42 + y * 19}" r="${r.toFixed(1)}" fill="#e8ecff"/>`; }).join('')}` },
  { chip: 'ГЕРБАРИЙ', cat: 'ПЕЧАТЬ', art: (id) => `
    <rect x="26" y="26" width="248" height="300" fill="#efe9d8"/>
    <path d="M150 310 C150 230 150 150 150 70" stroke="#3f5a2c" stroke-width="3" fill="none"/>
    ${[90, 130, 170, 210, 250].map((y, i) => `<path d="M150 ${y} C${i % 2 ? 210 : 90} ${y - 30} ${i % 2 ? 230 : 70} ${y + 10} 150 ${y + 18}" fill="#6f8f4a" opacity=".85"/>`).join('')}
    <text x="40" y="58" font-size="12" font-family="JetBrains Mono" fill="#3f5a2c">Mentha · 1/7</text>` },
  { chip: 'ПРИЛОЖЕНИЕ «37»', cat: 'ПРОДУКТ', art: (id) => `
    <rect x="26" y="26" width="248" height="300" fill="#f2efe9"/>
    <text x="150" y="250" text-anchor="middle" font-size="200" font-family="Unbounded" font-weight="900" fill="#e0412c">37</text>
    <rect x="40" y="40" width="64" height="8" fill="#151515"/>` },
];

// Perforated outline: rectangle with semicircular bites along every edge
function perforated(w, h, r, step) {
  const along = (len) => { const n = Math.floor((len - 2 * r) / step); const pad = (len - n * step) / 2; return Array.from({ length: n + 1 }, (_, i) => pad + i * step); };
  const xs = along(w), ys = along(h);
  let d = `M0 0`;
  for (const x of xs) d += ` L${x - r} 0 A${r} ${r} 0 0 0 ${x + r} 0`;
  d += ` L${w} 0`;
  for (const y of ys) d += ` L${w} ${y - r} A${r} ${r} 0 0 0 ${w} ${y + r}`;
  d += ` L${w} ${h}`;
  for (const x of [...xs].reverse()) d += ` L${x + r} ${h} A${r} ${r} 0 0 0 ${x - r} ${h}`;
  d += ` L0 ${h}`;
  for (const y of [...ys].reverse()) d += ` L0 ${y + r} A${r} ${r} 0 0 0 0 ${y - r}`;
  return d + ' Z';
}
const OUTLINE = perforated(300, 380, 7, 21);

const stage = document.getElementById('stage');
const els = STAMPS.map((s, i) => {
  const el = document.createElement('div'); el.className = 'stamp';
  el.innerHTML = `<span class="chip">${s.chip}</span>
    <svg viewBox="0 0 300 380" aria-hidden="true"><path d="${OUTLINE}" fill="#fbfaf6"/>${s.art(i)}
    <rect x="26" y="26" width="248" height="300" fill="none" stroke="rgba(0,0,0,.08)"/></svg>`;
  el.dataset.i = i; el.tilt = (Math.sin(i * 12.9) * 9).toFixed(1) * 1;
  stage.appendChild(el); return el;
});

// ---- scroll state ----
let current = 3, target = 3, lastInput = -1e9, snapTimer = 0;
const clamp = (v) => Math.max(0, Math.min(STAMPS.length - 1, v));
function nudge(delta) { target = clamp(target + delta); lastInput = performance.now(); clearTimeout(snapTimer); snapTimer = setTimeout(() => { target = Math.round(target); }, 160); }
addEventListener('wheel', (e) => { e.preventDefault(); nudge((e.deltaY + e.deltaX) * 0.0028); }, { passive: false });
addEventListener('keydown', (e) => {
  if (['ArrowRight', 'ArrowDown', 'PageDown'].includes(e.key)) { target = clamp(Math.round(target) + 1); lastInput = performance.now(); }
  if (['ArrowLeft', 'ArrowUp', 'PageUp'].includes(e.key)) { target = clamp(Math.round(target) - 1); lastInput = performance.now(); }
});
let drag = null;
stage.addEventListener('pointerdown', (e) => { drag = { x: e.clientX, y: e.clientY, moved: 0 }; stage.setPointerCapture(e.pointerId); stage.classList.add('drag'); });
stage.addEventListener('pointermove', (e) => {
  if (!drag) return;
  const dx = e.clientX - drag.x, dy = e.clientY - drag.y; drag.x = e.clientX; drag.y = e.clientY; drag.moved += Math.abs(dx) + Math.abs(dy);
  const w = els[0].offsetWidth * SPACING;
  nudge(-(Math.abs(dx) > Math.abs(dy) ? dx : dy) / w);
});
stage.addEventListener('pointerup', (e) => {
  stage.classList.remove('drag');
  if (drag && drag.moved < 6) { // click: jump to the stamp under the pointer
    const hit = document.elementsFromPoint(e.clientX, e.clientY).find((n) => n.classList && n.classList.contains('stamp'));
    if (hit) { target = +hit.dataset.i; lastInput = performance.now(); }
  }
  drag = null;
});

// ---- render ----
const count = document.getElementById('count');
const cats = [...document.querySelectorAll('.cats li')];
let focused = -1;
function frame(t) {
  // idle demo: step forward, bounce at the ends
  if ((AUTO || (!reduce && t - lastInput > 4000)) && !drag) {
    const step = AUTO ? 1400 : 2200;
    const k = (Math.floor(t / step) + 3) % (2 * (STAMPS.length - 1));
    target = k < STAMPS.length ? k : 2 * (STAMPS.length - 1) - k;
  }
  current += (target - current) * (reduce ? 0.35 : 0.085);
  const w = els[0].offsetWidth;
  els.forEach((el, i) => {
    const d = i - current, a = Math.abs(d);
    const sway = reduce ? 0 : Math.sin(t / 1300 + i) * 1.5;
    el.style.transform = `translate3d(${d * w * SPACING}px, ${a * a * 6}px, ${-a * DEPTH}px) rotateY(${-d * TURN}deg) rotateZ(${el.tilt * Math.min(1, a) + sway}deg)`;
    el.style.filter = `blur(${Math.min(MAX_BLUR, a * BLUR).toFixed(2)}px)`;
    el.style.zIndex = 100 - Math.round(a * 10);
    el.style.opacity = Math.max(0, 1 - a * 0.16);
  });
  const f = Math.round(clamp(current));
  if (f !== focused) {
    focused = f;
    els.forEach((el, i) => el.classList.toggle('on', i === f));
    count.textContent = `${String(f + 1).padStart(2, '0')} / ${String(STAMPS.length).padStart(2, '0')}`;
    cats.forEach((li) => li.classList.toggle('on', li.dataset.cat === STAMPS[f].cat));
  }
  requestAnimationFrame(frame);
}
requestAnimationFrame(frame);
</script>
</body>
</html>

Похожие