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

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

Гигантское слово-окно в стену поп-арт отпечатков

Слово во весь экран, сквозь буквы видна стена поп-арт отпечатков. От движения курсора палитры перещёлкиваются, как в шелкографии.

Гигантское слово-окно в стену поп-арт отпечатков
Промпт
Добавь на мою страницу эффект «Слово-окно в стену поп-арт отпечатков» (Сергей Дургалян, MIT). Ниже готовая страница на чистом canvas без библиотек. Сначала перенеси её как есть и проверь: слово «ЯРКО» во весь экран с чёрной обводкой и тенью, внутри букв ползёт сетка лампочек в разных палитрах, от движения мыши палитры перещёлкиваются, без мыши перещёлкиваются сами примерно раз в 0,7 секунды, на телефоне слово разбито на две строки. Потом меняй.

Как устроен код. Один отпечаток (лампочка) рисуется один раз на маленький canvas 256×256 под каждую палитру из `PALETTES`: заливка бумаги, фоновые растровые точки, тело лампочки и растровая тень (`dots()` рисует сетку точек под 45°, радиус точки зависит от расстояния до блика). Чёрный контур (`keyPlate`) — отдельный общий слой, чтобы его можно было сдвигать отдельно от цвета. Слово один раз рисуется в canvas-маску при `resize`; шрифт перед этим грузится через `document.fonts.load(шрифт, WORD)` (текст передавать обязательно, иначе загрузится только латиница). Каждый кадр стена собирается из готовых спрайтов (`drawImage`, это дёшево), потом `destination-in` с маской оставляет её только внутри букв. Обводку дают 12 копий маски по кругу (`strokeText` нарисовал бы и внутренние стыки контуров шрифта), тень — копия маски со сдвигом. Маска рисуется один раз, а не через `fillText` на каждую строку: при `destination-in` вторая строка стёрла бы первую.

Что менять: слово в `WORD`, шрифт в `FONT` (нужен жирный с кириллицей), палитры в `PALETTES` (бумага, объект, тень, фоновые точки), сам объект в `bulbPath` и `keyPlate`, шаг перещёлкивания (90 px пути курсора), интервал автодемо (700 мс), размер отпечатков (`fontSize * 0.5`), силу сдвига контура (`S * 0.06`), тексты шапки и кнопки. При `prefers-reduced-motion` стена не ползёт, контур не сдвигается, автодемо выключено.

Если проект на React: вынеси canvas в компонент `<PopWord word="..." />` с `useRef`, спрайты и маску создавай в `useEffect` после `document.fonts.load`, цикл `requestAnimationFrame` и слушатели снимай в функции очистки. Текст для экранных дикторов держи в скрытом `<h1>`, сам canvas — с `aria-hidden`.
Предложи 2–3 слова и палитры под мой продукт и чем заменить лампочку, чтобы объект был про мой продукт.

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

Первый экран занимает одно огромное слово с чёрной обводкой и жёсткой тенью, как на плакате. Буквы работают как окна: сквозь них видна стена одинаковых отпечатков (лампочка с растровой тенью), и каждый отпечаток напечатан в своей яркой палитре. Стена медленно ползёт. Каждые ~90 пикселей движения курсора все отпечатки «перепечатываются» следующей палитрой, а чёрный контур на долю секунды съезжает, как при неаккуратном проходе ракеля. Под курсором отпечаток получает свою палитру. Без мыши палитры перещёлкиваются сами.

Всё нарисовано на одном canvas без библиотек и без картинок: отпечаток процедурный, растровая точка считается в коде. Приём подсмотрен на warhol-arts.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>Pop Art Window Word</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: #141414; background: #f3ead8; }
/* paper texture: faint halftone dots */
body::before { content: ""; position: fixed; inset: 0; pointer-events: none; opacity: .35;
  background: radial-gradient(circle, #d9c9a8 1.2px, transparent 1.6px) 0 0 / 9px 9px; }
canvas#art { position: fixed; inset: 0; width: 100%; height: 100%; display: block; }
.bar { position: fixed; top: 0; left: 0; right: 0; display: flex; justify-content: space-between; align-items: center;
  padding: 22px clamp(16px, 4vw, 48px); font-weight: 700; font-size: .85rem; letter-spacing: .14em; text-transform: uppercase; }
.bar b { font-family: "Unbounded", sans-serif; letter-spacing: .02em; font-size: 1rem; }
.copy { position: fixed; left: 0; right: 0; bottom: clamp(20px, 6vh, 56px); display: flex; flex-wrap: wrap; gap: 14px 28px;
  justify-content: center; align-items: center; padding: 0 16px; text-align: center; }
.copy p { margin: 0; font-size: clamp(.95rem, 1.6vw, 1.15rem); font-weight: 500; max-width: 34ch; }
.copy a { display: inline-block; padding: 14px 26px; background: #141414; color: #ffe600; font-weight: 700; text-decoration: none;
  border-radius: 999px; box-shadow: 4px 4px 0 #ff2e88; transition: transform .15s; }
.copy a:hover, .copy a:focus-visible { transform: translate(-2px, -2px); }
.sr { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); }
</style>
</head>
<body>
<header class="bar"><b>Оттиск</b><span>мастерская шелкографии</span></header>
<h1 class="sr">Ярко</h1>
<canvas id="art" aria-hidden="true"></canvas>
<div class="copy"><p>Печатаем мерч тиражом от 30 штук — в любой палитре.</p><a href="#">Рассчитать тираж</a></div>

<script type="module">
// A giant word whose letters are windows into a wall of screen prints.
// One procedural print (a light bulb) is pre-rendered once per palette; every frame the wall
// is tiled from those sprites, masked by the word (destination-in) and outlined in ink.
const WORD = 'ЯРКО';
const FONT = 'Unbounded';
// [paper, object, halftone shade, background dots]
const PALETTES = [
  ['#ff2e88', '#ffe600', '#ff7a00', '#ff8fc4'],
  ['#00b3ff', '#ff2e88', '#7a1fff', '#7fdcff'],
  ['#ffe600', '#00c27a', '#006b5a', '#fff38a'],
  ['#7a1fff', '#ff9a1f', '#ff2e88', '#b58cff'],
  ['#00c27a', '#ffffff', '#00b3ff', '#7fe8bd'],
  ['#ff5a1f', '#00b3ff', '#1f3dff', '#ffa37f'],
];
const INK = '#141414';
const reduce = matchMedia('(prefers-reduced-motion: reduce)').matches;
const SP = 256;                      // sprite size, px

await document.fonts.load(`900 200px ${FONT}`, WORD); // pass the text: otherwise only the Latin subset loads

// --- 1) Sprites: a colour plate per palette + one shared black key plate ---
function bulbPath(c) {
  c.beginPath();
  c.arc(128, 104, 64, Math.PI * 0.75, Math.PI * 2.25); // bulb, open at the bottom
  c.lineTo(156, 186); c.lineTo(100, 186); c.closePath();
}
function dots(c, step, radius) {    // halftone grid rotated 45° (every other row shifted)
  c.beginPath();
  for (let y = 0, row = 0; y < SP + step; y += step * 0.5, row++) {
    for (let x = (row % 2) * step * 0.5; x < SP + step; x += step) {
      const r = radius(x, y); if (r < 0.4) continue;
      c.moveTo(x + r, y); c.arc(x, y, r, 0, Math.PI * 2);
    }
  }
  c.fill();
}
function colorPlate([paper, body, shade, bgDots]) {
  const cv = document.createElement('canvas'); cv.width = cv.height = SP;
  const c = cv.getContext('2d');
  c.fillStyle = paper; c.fillRect(0, 0, SP, SP);
  c.fillStyle = bgDots; dots(c, 14, (x, y) => 1 + 5 * ((x + y) / (SP * 2))); // dots grow toward a corner
  bulbPath(c); c.fillStyle = body; c.fill();
  c.save(); bulbPath(c); c.clip();
  c.fillStyle = shade; dots(c, 9, (x, y) => Math.max(0, Math.min(1, (Math.hypot(x - 104, y - 78) - 22) / 90)) * 5.2);
  c.restore();
  c.fillStyle = '#fff'; c.beginPath(); c.ellipse(104, 80, 13, 20, -0.6, 0, Math.PI * 2); c.fill(); // highlight
  c.fillStyle = shade; c.fillRect(96, 190, 64, 34);                                              // screw base
  return cv;
}
function keyPlate() {
  const cv = document.createElement('canvas'); cv.width = cv.height = SP;
  const c = cv.getContext('2d');
  c.strokeStyle = INK; c.fillStyle = INK; c.lineWidth = 7; c.lineJoin = 'round'; c.lineCap = 'round';
  bulbPath(c); c.stroke();
  c.lineWidth = 5; c.beginPath(); c.moveTo(114, 186); c.lineTo(114, 140); c.lineTo(128, 124); c.lineTo(142, 140); c.lineTo(142, 186); c.stroke(); // filament
  for (let i = 0; i < 3; i++) { c.fillRect(92, 192 + i * 12, 72, 6); }                       // base threads
  c.beginPath(); c.moveTo(110, 232); c.lineTo(146, 232); c.stroke();
  for (let i = 0; i < 7; i++) {                                                               // rays
    const a = Math.PI * (1.05 + i * 0.15), r1 = 80, r2 = 104;
    c.moveTo(128 + Math.cos(a) * r1, 104 + Math.sin(a) * r1); c.lineTo(128 + Math.cos(a) * r2, 104 + Math.sin(a) * r2);
  }
  c.stroke();
  return cv;
}
const plates = PALETTES.map(colorPlate);
const key = keyPlate();

// --- 2) Canvases: visible art, the wall of prints and a mask with the word in ink ---
const canvas = document.getElementById('art'), ctx = canvas.getContext('2d');
const wall = document.createElement('canvas'), wctx = wall.getContext('2d');
const mask = document.createElement('canvas'), mctx = mask.getContext('2d');
let W = 0, H = 0, dpr = 1, fontSize = 100;

function resize() {
  dpr = Math.min(devicePixelRatio || 1, 2);
  W = innerWidth; H = innerHeight;
  for (const c of [canvas, wall, mask]) { c.width = W * dpr; c.height = H * dpr; }
  // portrait screens: split the word into two lines so it stays huge
  const half = Math.ceil(WORD.length / 2);
  const lines = W / H < 0.8 && WORD.length > 3 ? [WORD.slice(0, half), WORD.slice(half)] : [WORD];
  mctx.font = `900 100px ${FONT}`;
  const widest = Math.max(...lines.map((l) => mctx.measureText(l).width));
  fontSize = Math.min((W * 0.92) / widest * 100, (H * 0.56) / lines.length / 0.9);
  // the word is drawn once into the mask; every frame reuses it (destination-in needs a single draw)
  mctx.setTransform(dpr, 0, 0, dpr, 0, 0);
  mctx.font = `900 ${fontSize}px ${FONT}`; mctx.textAlign = 'center'; mctx.textBaseline = 'middle'; mctx.fillStyle = INK;
  const lineH = fontSize * 0.9, top = H * 0.5 - (lines.length - 1) * lineH / 2;
  lines.forEach((l, i) => mctx.fillText(l, W / 2, top + i * lineH));
}
addEventListener('resize', resize); resize();

// --- 3) Interaction: each ~90px of pointer travel "re-pulls" the prints in the next palette ---
let shift = 0, kick = 0, travel = 0, px = -1, py = -1, hx = -1, hy = -1, lastInput = -1e9, nextAuto = 0;
function flip() { shift++; kick = 1; }
addEventListener('pointermove', (e) => {
  if (px >= 0) travel += Math.hypot(e.clientX - px, e.clientY - py);
  px = hx = e.clientX; py = hy = e.clientY; lastInput = performance.now();
  if (travel > 90) { travel = 0; flip(); }
}, { passive: true });
addEventListener('pointerdown', () => { flip(); lastInput = performance.now(); });
addEventListener('pointerleave', () => { hx = hy = -1; });

const hash = (i, j) => { const s = Math.sin(i * 127.1 + j * 311.7) * 43758.5453; return s - Math.floor(s); };

function frame(now) {
  const t = now / 1000;
  // autodemo: without input the prints flip by themselves
  if (!reduce && now - lastInput > 2500 && now > nextAuto) { flip(); nextAuto = now + 700; }
  kick *= 0.86;

  // wall of prints, slowly panning
  const S = Math.max(70, fontSize * 0.5);
  const ox = reduce ? 0 : (t * 14) % S, oy = reduce ? 0 : (t * 6) % S;
  const hc = Math.floor((hx + ox) / S), hr = Math.floor((hy + oy) / S);
  wctx.setTransform(dpr, 0, 0, dpr, 0, 0);
  wctx.globalCompositeOperation = 'source-over';
  wctx.clearRect(0, 0, W, H);
  for (let j = -1; j * S < H + S; j++) {
    for (let i = -1; i * S < W + S; i++) {
      const under = i === hc && j === hr;                       // the print under the cursor gets its own palette
      const p = (((i + j * 2 + shift + (under ? 3 : 0)) % plates.length) + plates.length) % plates.length;
      const x = i * S - ox, y = j * S - oy;
      // misregistration: the key plate slips a little after every flip, like a careless squeegee pull
      const a = hash(i, j) * Math.PI * 2, m = kick * S * 0.06;
      wctx.drawImage(plates[p], x, y, S, S);
      wctx.drawImage(key, x + Math.cos(a) * m, y + Math.sin(a) * m, S, S);
    }
  }
  wctx.globalCompositeOperation = 'destination-in';             // keep the wall only inside the letters
  wctx.drawImage(mask, 0, 0, W, H);

  ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
  ctx.clearRect(0, 0, W, H);
  // ink outline = the mask stamped around a circle (strokeText would also draw the glyphs' inner overlaps)
  const o = Math.max(3, fontSize * 0.022);
  for (let k = 0; k < 12; k++) ctx.drawImage(mask, Math.cos(k * Math.PI / 6) * o, Math.sin(k * Math.PI / 6) * o, W, H);
  ctx.drawImage(mask, fontSize * 0.05, fontSize * 0.05, W, H);   // hard pop-art shadow
  ctx.drawImage(wall, 0, 0, W, H);
  requestAnimationFrame(frame);
}
requestAnimationFrame(frame);
</script>
</body>
</html>

Похожие