Под заголовком на верёвочках висят брелоки: качаются на ветру, отлетают от курсора, тянутся мышью и пальцем, стукаются друг о друга.
Промпт
Добавь на мою страницу эффект «Брелоки на верёвочках под заголовком» (Сергей Дургалян, MIT). Ниже готовая страница без библиотек: HTML-заголовок и canvas 2D с собственной физикой. Сначала перенеси её как есть и проверь: брелоки висят под последней строкой заголовка и качаются на ветру; движение курсора через брелок толкает его; брелок можно схватить мышью или пальцем, оттянуть и бросить; брелоки сталкиваются друг с другом; на телефоне всё помещается в 390 px. Потом меняй.
Как устроен код. Массив `CHARMS` описывает брелоки: точку крепления `at` (доля ширины строки), длину верёвки `len`, SVG-путь `path` в коробке 100×100 (или `pill` — таблетка с текстом), точку крепления кольца `top`, два цвета градиента. `build()` находит последнюю строку заголовка через `Range.getClientRects()` (а не всю ширину блока), ставит туда булавки и создаёт для каждой верёвки `SEGMENTS + 1` точек. На телефоне булавки распределяются по ширине экрана, а длина верёвок подстраивается под свободное место. Физика идёт фиксированным шагом 1/120 с: verlet (`DAMP` — сохранение скорости), сила тяжести `GRAVITY`, ветер `WIND` (сумма двух синусоид, сильнее, когда 3 секунды нет ввода), затем `ITER` проходов ограничений длины. Первая точка прибита, последняя тяжелее звеньев. Центр брелока считается в `charmFrame` вдоль последнего звена, по этим центрам брелоки расталкиваются как круги. Курсор раз в кадр даёт толчок брелокам и звеньям, через которые прошёл (`shove`, толчок ограничен по силе); схваченный брелок следует за указателем, но не дальше длины верёвки, а при отпускании получает скорость указателя. Рисование: верёвка — кривая через точки, у цепочек ещё серые шарики; брелок — кольцо и фигура `Path2D` с градиентом, толстым контуром и бликом. При `prefers-reduced-motion` ветра нет, перетаскивание и толчки работают.
Что менять: заголовок — в `h1`; брелоки, цвета, длины и надписи — в `CHARMS` (любую иконку можно вставить SVG-путём, подогнав её под коробку 100×100 и указав `top`); размер — `size` в `build()`; живость — `WIND`, `DAMP` (меньше — быстрее успокаиваются) и `GRAVITY`; жёсткость верёвок — `ITER` и `SEGMENTS`. Если нужен клик по брелоку (например, переход в раздел), в `pointerup` проверь, что указатель почти не сдвинулся с момента `pointerdown`, и выполни действие для `ptr.grab`.
Если проект на React: вынеси canvas в компонент `HangingCharms` с пропсами `titleRef` и `charms`; физику и точки держи в `useRef`, цикл `requestAnimationFrame`, слушатели и `resize` заводи в `useEffect` и снимай в очистке. Пересобирай верёвки (`build`) после загрузки шрифтов (`document.fonts.ready`) и при изменении размера заголовка через `ResizeObserver`.
Покажи, под каким заголовком на моём сайте брелоки будут уместны, и предложи 4–6 фигур и надписей под мой продукт.
Код скопируется вместе с промптом
С нижнего края крупного заголовка свисают пять брелоков-наклеек: сердце, звезда, таблетка с надписью «ЛАЙК», капля и смайлик. Одни висят на шнурках, другие на шариковых цепочках. Они покачиваются на лёгком ветру, отлетают, если провести по ним курсором, а если схватить, тянутся мышью или пальцем и после броска раскачиваются с инерцией. Соседние брелоки стукаются и расталкивают друг друга. Приём подсмотрен на butter.video.
Физика своя, без библиотек: каждая верёвка — цепочка точек с verlet-интегрированием и ограничениями длины, брелок висит на последней точке и поворачивается вдоль последнего звена. Фигуры заданы SVG-путями (Path2D) и рисуются на одном canvas поверх страницы, заголовок остаётся обычным HTML-текстом. Хорошо оживляет первый экран магазина, детского или креативного проекта, страницу «спасибо» и любой игривый лендинг.
Код
<!-- 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>Physics Charms Title</title>
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Unbounded:wght@900&family=Inter:wght@500;800&display=swap">
<style>
*, *::before, *::after { box-sizing: border-box; }
html, body { margin: 0; height: 100%; }
body { overflow: hidden; background: #fff1e6; color: #1a1a1a; font-family: "Inter", sans-serif; }
h1 { position: relative; z-index: 1; margin: 0 auto; padding: 12vh 16px 0; max-width: 1200px; text-align: center;
font: 900 clamp(44px, 9vw, 132px)/.92 "Unbounded", sans-serif; letter-spacing: -.04em; }
@media (max-width: 640px) { h1 { padding-top: 16vh; } }
p { position: fixed; z-index: 1; left: 0; right: 0; bottom: 22px; margin: 0; text-align: center; font-size: 13px; opacity: .55; }
canvas { position: fixed; inset: 0; z-index: 2; touch-action: none; }
</style>
</head>
<body>
<h1 id="title">Мелочи, которые цепляют</h1>
<p>Толкните брелок курсором или потяните его</p>
<canvas id="c" aria-label="Брелоки на верёвочках под заголовком" role="img"></canvas>
<script>
const GRAVITY = 1400; // px/s²
const DAMP = 0.985; // velocity kept per step
const ITER = 10; // constraint passes per step (stiffer rope)
const SEGMENTS = 9;
const WIND = 300; // idle breeze strength, px/s²
const IDLE_DEMO = 3000;
const reduced = matchMedia("(prefers-reduced-motion: reduce)").matches;
// shapes in a 100×100 box; `top` is where the key ring attaches
const star = (() => { let d = ""; for (let k = 0; k < 10; k++) { const r = k % 2 ? 20 : 46, a = -Math.PI / 2 + k * Math.PI / 5; d += (k ? "L" : "M") + (50 + r * Math.cos(a)).toFixed(1) + " " + (54 + r * Math.sin(a)).toFixed(1); } return d + "Z"; })();
const CHARMS = [
{ at: .12, len: 150, path: "M50 90C20 68 6 50 6 33 6 19 17 9 30 9c10 0 16 6 20 14 4-8 10-14 20-14 13 0 24 10 24 24 0 17-14 35-44 57Z", top: 23, colors: ["#ff8aa8", "#e8264f"] },
{ at: .31, len: 230, path: star, top: 8, colors: ["#ffe27a", "#ffae00"] },
{ at: .5, len: 120, pill: "ЛАЙК", top: 28, colors: ["#9ad8ff", "#2b6bff"] },
{ at: .69, len: 205, path: "M50 6C64 30 82 46 82 64 82 82 68 94 50 94S18 82 18 64C18 46 36 30 50 6Z", top: 6, colors: ["#8ff0c8", "#12a776"] },
{ at: .88, len: 165, path: "M50 6a44 44 0 1 0 .01 0Z", top: 6, smile: true, colors: ["#d7c2ff", "#7a4dff"] },
].map((c) => ({ ...c, shape: c.path ? new Path2D(c.path) : null }));
const cv = document.getElementById("c"), g = cv.getContext("2d"), title = document.getElementById("title");
let W = 0, H = 0, dpr = 1, ropes = [], size = 90, ring = 7;
const ptr = { x: -999, y: -999, vx: 0, vy: 0, down: false, grab: null };
let lastInput = -1e9;
function build() {
dpr = Math.min(devicePixelRatio, 2); W = innerWidth; H = innerHeight;
cv.width = W * dpr; cv.height = H * dpr; cv.style.width = W + "px"; cv.style.height = H + "px";
// hang from the real text lines, not the full-width heading box
const range = document.createRange(); range.selectNodeContents(title);
const lines = [...range.getClientRects()], lastLine = lines[lines.length - 1];
const left = Math.min(...lines.map((l) => l.left)), right = Math.max(...lines.map((l) => l.right));
const mobile = W < 640, r = mobile ? { left: 44, width: W - 88, bottom: lastLine.bottom } : { left, width: right - left, bottom: lastLine.bottom };
size = mobile ? 62 : 92; ring = mobile ? 5 : 7;
const room = H - r.bottom - size * 1.6, k = Math.max(.35, Math.min(mobile ? 1.35 : 1, room / 260));
ropes = CHARMS.map((c, i) => {
const ax = r.left + r.width * c.at, ay = r.bottom - (mobile ? 4 : 10), seg = c.len * k / SEGMENTS;
const pts = Array.from({ length: SEGMENTS + 1 }, (_, j) => ({ x: ax, y: ay + j * seg, px: ax - j * .25 * (i % 2 ? 1 : -1), py: ay + j * seg })); // tiny initial swing
return { c, pts, seg, ax, ay, angle: 0, cx: 0, cy: 0, rad: size * .42 };
});
}
// charm hangs along the last rope segment; its centre is used for collisions and picking
function charmFrame(rp) {
const a = rp.pts[SEGMENTS], b = rp.pts[SEGMENTS - 1];
const dx = a.x - b.x, dy = a.y - b.y, l = Math.hypot(dx, dy) || 1;
rp.angle = Math.atan2(dx, dy);
const off = ring * 2 + size * .5;
rp.cx = a.x + dx / l * off; rp.cy = a.y + dy / l * off;
}
function step(dt, t) {
const idle = performance.now() - lastInput > IDLE_DEMO;
const breeze = reduced ? 0 : WIND * (idle ? 1 : .25);
for (let ri = 0; ri < ropes.length; ri++) {
const rp = ropes[ri], gust = breeze * (Math.sin(t * .8 + ri * 1.3) * .7 + Math.sin(t * 2.3 + ri) * .3);
for (let j = 1; j <= SEGMENTS; j++) {
const p = rp.pts[j];
if (ptr.grab === rp && j === SEGMENTS) continue;
const vx = (p.x - p.px) * DAMP, vy = (p.y - p.py) * DAMP;
p.px = p.x; p.py = p.y;
p.x += vx + gust * (j / SEGMENTS) * dt * dt; p.y += vy + GRAVITY * dt * dt;
}
if (ptr.grab === rp) { // follow the pointer, but the rope cannot stretch past its length
const e = rp.pts[SEGMENTS], dx = ptr.x - rp.ax, dy = ptr.y - rp.ay, d = Math.hypot(dx, dy), max = rp.seg * SEGMENTS, k = d > max ? max / d : 1;
e.px = e.x; e.py = e.y; e.x = rp.ax + dx * k; e.y = rp.ay + dy * k;
}
}
for (let it = 0; it < ITER; it++) {
for (const rp of ropes) {
rp.pts[0].x = rp.ax; rp.pts[0].y = rp.ay;
for (let j = 0; j < SEGMENTS; j++) {
const a = rp.pts[j], b = rp.pts[j + 1], dx = b.x - a.x, dy = b.y - a.y, d = Math.hypot(dx, dy) || 1;
const diff = (d - rp.seg) / d;
// the anchor never moves; the heavy last point moves less than rope links
const wa = j === 0 ? 0 : j + 1 === SEGMENTS ? .75 : .5, wb = 1 - wa;
if (ptr.grab === rp && j + 1 === SEGMENTS) { a.x += dx * diff; a.y += dy * diff; continue; }
a.x += dx * diff * wa; a.y += dy * diff * wa; b.x -= dx * diff * wb; b.y -= dy * diff * wb;
}
}
// charms bump into each other
ropes.forEach(charmFrame);
for (let i = 0; i < ropes.length; i++) for (let j = i + 1; j < ropes.length; j++) {
const A = ropes[i], B = ropes[j], dx = B.cx - A.cx, dy = B.cy - A.cy, d = Math.hypot(dx, dy) || 1, min = A.rad + B.rad;
if (d >= min) continue;
const push = (min - d) / d * .5, ea = A.pts[SEGMENTS], eb = B.pts[SEGMENTS];
if (ptr.grab !== A) { ea.x -= dx * push; ea.y -= dy * push; }
if (ptr.grab !== B) { eb.x += dx * push; eb.y += dy * push; }
}
}
}
// once per frame: a moving cursor gives a velocity kick to charms and rope links it touches
function shove() {
const sp = Math.hypot(ptr.vx, ptr.vy); if (ptr.down || sp < .5) return;
const k = Math.min(1, 14 / sp) * .22, kx = ptr.vx * k, ky = ptr.vy * k; // kick capped at ~5 px/step
for (const rp of ropes) {
const e = rp.pts[SEGMENTS];
if (Math.hypot(rp.cx - ptr.x, rp.cy - ptr.y) < rp.rad + 10) { e.px -= kx; e.py -= ky; }
for (let j = 1; j < SEGMENTS; j++) { const p = rp.pts[j]; if (Math.hypot(p.x - ptr.x, p.y - ptr.y) < 24) { p.px -= kx * .5; p.py -= ky * .5; } }
}
}
function drawCharm(rp) {
const { c } = rp, e = rp.pts[SEGMENTS], s = size / 100;
g.save(); g.translate(e.x, e.y); g.rotate(-rp.angle);
g.lineWidth = 3; g.strokeStyle = "#1a1a1a";
g.beginPath(); g.arc(0, ring, ring, 0, 7); g.stroke(); // key ring
g.translate(0, ring * 2); g.scale(s, s); g.translate(-50, -c.top);
const gr = g.createLinearGradient(20, 0, 80, 100); gr.addColorStop(0, c.colors[0]); gr.addColorStop(1, c.colors[1]);
g.fillStyle = gr; g.lineWidth = 6; g.lineJoin = "round";
if (c.shape) { g.fill(c.shape); g.stroke(c.shape); }
else { g.beginPath(); g.roundRect(-14, 28, 128, 50, 25); g.fill(); g.stroke(); }
g.fillStyle = "rgba(255,255,255,.55)"; g.beginPath(); g.ellipse(c.pill ? 10 : 34, c.pill ? 42 : 34, 10, 6, -.6, 0, 7); g.fill(); // gloss
g.fillStyle = "#1a1a1a";
if (c.pill) { g.font = "800 26px Inter, sans-serif"; g.textAlign = "center"; g.fillText(c.pill, 50, 62); }
if (c.smile) { g.beginPath(); g.arc(36, 44, 5, 0, 7); g.arc(64, 44, 5, 0, 7); g.fill(); g.beginPath(); g.lineWidth = 5; g.arc(50, 56, 20, .3, Math.PI - .3); g.stroke(); }
g.restore();
}
function draw() {
g.setTransform(dpr, 0, 0, dpr, 0, 0); g.clearRect(0, 0, W, H);
ropes.forEach((rp, i) => {
const p = rp.pts;
g.strokeStyle = "#1a1a1a"; g.lineWidth = 2.5; g.lineCap = "round";
g.beginPath(); g.moveTo(p[0].x, p[0].y);
for (let j = 1; j < p.length - 1; j++) g.quadraticCurveTo(p[j].x, p[j].y, (p[j].x + p[j + 1].x) / 2, (p[j].y + p[j + 1].y) / 2);
g.lineTo(p[SEGMENTS].x, p[SEGMENTS].y); g.stroke();
if (i % 2) { g.fillStyle = "#b9b2aa"; for (const q of p) { g.beginPath(); g.arc(q.x, q.y, 3.2, 0, 7); g.fill(); } } // ball chain
g.fillStyle = "#1a1a1a"; g.beginPath(); g.arc(rp.ax, rp.ay, 4.5, 0, 7); g.fill(); // pin under the heading
});
ropes.forEach(drawCharm);
}
// pointer: push, grab, throw
function setPtr(e) { ptr.vx += e.clientX - ptr.x; ptr.vy += e.clientY - ptr.y; ptr.x = e.clientX; ptr.y = e.clientY; ptr.tvx = ptr.vx; ptr.tvy = ptr.vy; lastInput = performance.now(); }
cv.addEventListener("pointermove", (e) => {
if (ptr.x < -900) { ptr.x = e.clientX; ptr.y = e.clientY; }
setPtr(e);
cv.style.cursor = ptr.grab ? "grabbing" : ropes.some((rp) => Math.hypot(rp.cx - ptr.x, rp.cy - ptr.y) < rp.rad) ? "grab" : "";
});
cv.addEventListener("pointerdown", (e) => {
ptr.x = e.clientX; ptr.y = e.clientY; ptr.vx = ptr.vy = 0; ptr.down = true; lastInput = performance.now();
ptr.grab = ropes.find((rp) => Math.hypot(rp.cx - ptr.x, rp.cy - ptr.y) < rp.rad + 8) || null;
if (ptr.grab) cv.setPointerCapture(e.pointerId);
});
const up = () => {
if (ptr.grab) { const e = ptr.grab.pts[SEGMENTS]; e.px = e.x - (ptr.tvx || 0) * .25; e.py = e.y - (ptr.tvy || 0) * .25; } // throw with the last pointer speed
ptr.grab = null; ptr.down = false;
};
cv.addEventListener("pointerup", up); cv.addEventListener("pointercancel", up);
cv.addEventListener("pointerleave", () => { if (!ptr.grab) { ptr.x = ptr.y = -999; } });
addEventListener("resize", build);
let last = performance.now(), acc = 0;
function frame(now) {
acc += Math.min(.1, (now - last) / 1000); last = now;
const h = 1 / 120; // fixed physics step
shove(); ptr.vx = ptr.vy = 0; // pointer delta is consumed once per frame
while (acc >= h) { step(h, now / 1000); acc -= h; }
draw(); requestAnimationFrame(frame);
}
document.fonts.ready.then(build);
build(); requestAnimationFrame(frame);
</script>
</body>
</html>