Эффекты и шейдерыТёмный3DЯркийТипографикаБесплатно
Карусель карточек, которые гнутся, как страницы
Яркие карточки листаются перетаскиванием и на ходу выгибаются, как бумага на ветру; по краям загибаются цилиндром.
Промпт
Добавь на мою страницу эффект «Карусель карточек, которые гнутся, как страницы» (Сергей Дургалян, MIT). Ниже готовая страница на three.js 0.170.0 (jsdelivr, import map). Сначала перенеси её как есть и проверь: карточки тянутся мышью и пальцем, на ходу выгибаются, после отпускания встают точно по центру, точки внизу показывают текущую, без касаний карусель листается сама. Потом меняй.
Как устроен код. Каждая карточка — `PlaneGeometry(W, H, 96, 1)`: 96 сегментов по ширине нужны для гладкого изгиба. Текстура рисуется на canvas 1600×1000 функцией `drawCard` (скруглённый прямоугольник, цветные фигуры, слово, подогнанное по ширине, подпись), шрифты грузятся через `document.fonts.load(шрифт, текст)`: текст передавать обязательно, иначе для кириллицы подгрузится не тот набор символов. В вершинном шейдере два изгиба: цилиндр `0.034 * x²` от положения карточки на экране и «волна» `sin(u·π) * uSpeed`, где `uSpeed` — сглаженная скорость перетаскивания. Тень считается из наклона поверхности, поэтому выгнутые края темнее. Перетаскивание переводит пиксели в мировые единицы через fov камеры, отпускание и колесо доводят карусель до ближайшей карточки.
Что менять: массив `CARDS` (слово, подпись, цвет фона, текста и фигур), размеры `W`, `H`, `GAP`, силу изгиба (коэффициенты в шейдере и множитель скорости в `setAnimationLoop`), интервал автолистания. На узком экране камера отъезжает так, чтобы карточка целиком помещалась по ширине.
Если проект на React: держи сцену в компоненте с `useRef` на canvas, создание и очистку делай в `useEffect` (`setAnimationLoop(null)`, `dispose()` геометрии, материалов, текстур и рендерера, снять слушатели). Данные карточек передавай пропсом.
Предложи, какие 4 карточки с одним словом лучше всего расскажут о моём продукте.
Код скопируется вместе с промптом
Горизонтальная лента ярких карточек с крупными словами. Их тянут мышью или пальцем, листают колесом. Пока карточка едет, она выгибается, как лист бумаги на ветру, а когда останавливается, выпрямляется. Карточки по краям экрана загибаются от зрителя, будто лежат на большом барабане. Если никто не трогает страницу, карусель листается сама.
Карточки здесь не HTML-блоки, а мелко нарезанные плоскости в WebGL, и изгиб делает вершинный шейдер. Картинку на карточке рисует обычный canvas 2D: фон, фигуры, слово и подпись. Поэтому содержимое меняется в одном массиве, а кривизна не зависит от вёрстки. Хорош для блока ценностей, этапов работы, тарифов или «чем мы занимаемся».
Код
<!-- 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>Page Bend Cards</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 { background: #111214; color: #f2f2f2; font-family: "Inter", sans-serif; overflow: hidden; }
canvas#gl { position: fixed; inset: 0; width: 100%; height: 100%; display: block; cursor: grab; touch-action: pan-y; }
canvas#gl:active { cursor: grabbing; }
.ui { position: fixed; left: 0; right: 0; bottom: 5vh; display: flex; justify-content: center; gap: .5rem; pointer-events: none; }
.dot { width: 8px; height: 8px; border-radius: 50%; background: #f2f2f2; opacity: .25; transition: opacity .3s, transform .3s; }
.dot.on { opacity: 1; transform: scale(1.4); }
.title { position: fixed; top: 5vh; left: 0; right: 0; text-align: center; font-size: .8rem; letter-spacing: .16em; text-transform: uppercase; opacity: .55; }
</style>
</head>
<body>
<div class="title">Тяните карточки в сторону</div>
<canvas id="gl"></canvas>
<div class="ui" id="dots"></div>
<script type="importmap">{ "imports": { "three": "https://cdn.jsdelivr.net/npm/three@0.170.0/build/three.module.js" } }</script>
<script type="module">
// Page-bend carousel: each card is a finely subdivided plane. The vertex shader bends it
// (1) around a cylinder, more the further the card is from the centre, and
// (2) like a page in the wind, proportional to drag speed. Card art is drawn on a 2D canvas.
import * as THREE from 'three';
const CARDS = [
{ word: 'ИДЕИ', sub: 'Сначала — много идей', bg: '#3ddc6a', ink: '#0f2a12', accent: '#e8ff5a' },
{ word: 'ЛЮДИ', sub: 'Потом — правильные люди', bg: '#5b6cff', ink: '#ffffff', accent: '#ffd2f0' },
{ word: 'ИГРА', sub: 'И немного игры', bg: '#ff9a1f', ink: '#fffaf0', accent: '#ff3d6e' },
{ word: 'СМЕЛО', sub: 'Делаем смелые вещи', bg: '#ff4f9a', ink: '#ffffff', accent: '#2a1aff' },
];
const W = 6.4, H = 4, GAP = 0.9, STEP = W + GAP;
const reduce = matchMedia('(prefers-reduced-motion: reduce)').matches;
const canvas = document.getElementById('gl');
const renderer = new THREE.WebGLRenderer({ canvas, antialias: true, alpha: true });
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(35, 1, 0.1, 100);
camera.position.z = 12;
// --- Card art on a 2D canvas -------------------------------------------------
function roundRect(ctx, x, y, w, h, r) {
ctx.beginPath(); ctx.moveTo(x + r, y); ctx.arcTo(x + w, y, x + w, y + h, r); ctx.arcTo(x + w, y + h, x, y + h, r);
ctx.arcTo(x, y + h, x, y, r); ctx.arcTo(x, y, x + w, y, r); ctx.closePath();
}
function drawCard(c, i) {
const cv = document.createElement('canvas'); cv.width = 1600; cv.height = 1000;
const ctx = cv.getContext('2d');
roundRect(ctx, 0, 0, 1600, 1000, 70); ctx.fillStyle = c.bg; ctx.fill(); ctx.save(); ctx.clip();
// playful shapes behind the word
ctx.fillStyle = c.accent;
for (let k = 0; k < 7; k++) {
const x = 120 + ((k * 397 + i * 151) % 1380), y = 120 + ((k * 263 + i * 89) % 760), r = 30 + ((k * 37) % 70);
ctx.globalAlpha = 0.85; ctx.beginPath();
if (k % 2) ctx.arc(x, y, r, 0, Math.PI * 2); else { ctx.translate(x, y); ctx.rotate(k); ctx.rect(-r, -r, r * 2, r * 2); ctx.setTransform(1, 0, 0, 1, 0, 0); }
ctx.fill();
}
ctx.globalAlpha = 1;
// the big word, fitted to the card width
ctx.fillStyle = c.ink; ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
let size = 360; ctx.font = `900 ${size}px Unbounded`;
while (ctx.measureText(c.word).width > 1360) { size -= 10; ctx.font = `900 ${size}px Unbounded`; }
ctx.fillText(c.word, 800, 470);
ctx.font = '700 54px Inter'; ctx.fillText(c.sub, 800, 760);
ctx.font = '500 34px Inter'; ctx.globalAlpha = .7; ctx.fillText(`0${i + 1} / 0${CARDS.length}`, 800, 120);
ctx.restore();
const tex = new THREE.CanvasTexture(cv);
tex.colorSpace = THREE.SRGBColorSpace; tex.anisotropy = renderer.capabilities.getMaxAnisotropy();
return tex;
}
// --- Bend shader ------------------------------------------------------------------
const vertex = /* glsl */`
uniform float uX; // card centre in world units (after scroll)
uniform float uSpeed; // drag velocity, signed
varying vec2 vUv;
varying float vShade;
void main() {
vUv = uv;
vec3 p = position;
float wx = p.x + uX; // world x of this vertex
// 1) cylinder: cards curl away from the viewer the further they are from centre
float curve = 0.034 * wx * wx;
// 2) page-in-the-wind: a sine bulge across the card, stronger with speed; the edges lag behind
float u = p.x / ${W.toFixed(1)} + 0.5;
float wave = sin(u * 3.14159) * uSpeed * 2.4 + (u - 0.5) * (u - 0.5) * abs(uSpeed) * 5.0;
p.z -= curve + wave;
p.y *= 1.0 - abs(uSpeed) * 0.06 * sin(u * 3.14159); // slight pinch in the middle while moving
// fake lighting from the surface slope (derivative of the bend along x)
float slope = 0.068 * wx + cos(u * 3.14159) * 3.14159 / ${W.toFixed(1)} * uSpeed * 2.4;
vShade = 1.0 - clamp(abs(slope) * 0.55, 0.0, 0.45);
gl_Position = projectionMatrix * modelViewMatrix * vec4(p, 1.0);
}`;
const fragment = /* glsl */`
uniform sampler2D uMap;
varying vec2 vUv;
varying float vShade;
void main() {
vec4 c = texture2D(uMap, vUv);
if (c.a < 0.01) discard; // rounded corners come from the canvas alpha
gl_FragColor = vec4(c.rgb * vShade, c.a);
#include <colorspace_fragment>
}`;
await document.fonts.load('900 100px Unbounded', CARDS.map((c) => c.word).join('')); // pass the text so the Cyrillic subset loads
await document.fonts.load('700 40px Inter', CARDS.map((c) => c.sub).join(''));
await document.fonts.load('500 30px Inter', '0123456789/');
const geo = new THREE.PlaneGeometry(W, H, 96, 1);
const cards = CARDS.map((c, i) => {
const mat = new THREE.ShaderMaterial({
vertexShader: vertex, fragmentShader: fragment, transparent: true, side: THREE.DoubleSide,
uniforms: { uMap: { value: drawCard(c, i) }, uX: { value: 0 }, uSpeed: { value: 0 } },
});
const mesh = new THREE.Mesh(geo, mat);
scene.add(mesh);
return mesh;
});
// --- Drag, wheel, snapping -------------------------------------------------------
const dots = document.getElementById('dots');
CARDS.forEach(() => dots.insertAdjacentHTML('beforeend', '<span class="dot"></span>'));
let pos = 0, target = 0, speed = 0, dragging = false, startX = 0, startTarget = 0, lastInput = 0;
const maxPos = (CARDS.length - 1) * STEP;
const clamp = (v) => Math.max(-0.6, Math.min(maxPos + 0.6, v));
const snap = () => { target = Math.round(Math.max(0, Math.min(maxPos, target)) / STEP) * STEP; };
const worldPerPx = () => (2 * Math.tan(THREE.MathUtils.degToRad(camera.fov / 2)) * camera.position.z) / innerHeight;
canvas.addEventListener('pointerdown', (e) => { dragging = true; startX = e.clientX; startTarget = target; lastInput = performance.now(); canvas.setPointerCapture(e.pointerId); });
canvas.addEventListener('pointermove', (e) => { if (!dragging) return; lastInput = performance.now(); target = clamp(startTarget - (e.clientX - startX) * worldPerPx() * 1.4); });
const release = () => { if (dragging) { dragging = false; snap(); } };
canvas.addEventListener('pointerup', release); canvas.addEventListener('pointercancel', release);
let wheelTimer;
addEventListener('wheel', (e) => { lastInput = performance.now(); target = clamp(target + (e.deltaX || e.deltaY) * 0.01); clearTimeout(wheelTimer); wheelTimer = setTimeout(snap, 140); }, { passive: true });
// Idle demo: every 2.6 s without input, move to the next card (and wrap around)
setInterval(() => {
if (dragging || performance.now() - lastInput < 4000) return;
const i = Math.round(target / STEP);
target = ((i + 1) % CARDS.length) * STEP;
}, 2600);
function resize() {
renderer.setSize(innerWidth, innerHeight, false);
camera.aspect = innerWidth / innerHeight;
// keep one card comfortably on screen on narrow phones
camera.position.z = Math.max(12, (W + 1.2) / (2 * Math.tan(THREE.MathUtils.degToRad(camera.fov / 2)) * camera.aspect));
camera.updateProjectionMatrix();
}
addEventListener('resize', resize); resize();
renderer.setAnimationLoop(() => {
const prev = pos;
pos += (target - pos) * (reduce ? 1 : 0.075);
const v = reduce ? 0 : pos - prev;
speed += (THREE.MathUtils.clamp(v * 2.6, -0.7, 0.7) - speed) * 0.15; // smoothed, so the bend settles softly
cards.forEach((m, i) => {
const x = i * STEP - pos;
m.position.x = x;
m.material.uniforms.uX.value = x;
m.material.uniforms.uSpeed.value = speed;
});
const active = Math.round(pos / STEP);
[...dots.children].forEach((d, i) => d.classList.toggle('on', i === active));
renderer.render(scene, camera);
});
</script>
</body>
</html>