Колонка фото обёрнута по внутренней стороне барабана: к краям экрана снимки изгибаются и выцветают, на скролле идёт жидкая рябь.
Промпт
Добавь на мою страницу эффект «Галерея на барабане: фото изгибаются при скролле» (по мотивам Codrops RotatingOnScrollAnimations, вариант 7, MIT). Ниже готовая страница: GSAP 3.13.0 с ScrollTrigger, Lenis и three.js 0.170.0 (через importmap) с jsdelivr. Сначала перенеси её как есть и открой через локальный сервер, а не как файл: браузер не позволит загрузить текстуры картинок с адреса `file://`. Убедись, что фото изгибаются на скролле, и только потом подгоняй.
Как устроен код. В `.gallery` лежат блоки `.gallery__item-wrap` и `.gallery__item` с картинкой в `background-image`; на странице они скрыты (`visibility: hidden` у `.gallery--webgl .gallery__item`) и нужны только как места и размеры. Поверх лежит `<canvas class="webgl">` на весь экран. Функция `initWebGL` создаёт `THREE.WebGLRenderer`, перспективную камеру с полем зрения под размер окна (1 единица равна 1 пикселю при z = 0) и по одной плоскости `PlaneGeometry(1, 1, 32, 64)` на картинку с `ShaderMaterial`. Функция `render` на каждом кадре читает `getBoundingClientRect` блока-заглушки и передаёт шейдеру `uOffset` (расстояние до середины экрана) и размер. Вершинный шейдер изгибает плоскость по дуге барабана: `angle = (uOffset + pos.y) * uCurve`, радиус равен половине высоты окна. Фрагментный шейдер воспроизводит `background-size: cover`, добавляет «жидкость» (`uLiquid` растёт со скоростью скролла) и мешает цвет с фоном `uFog` по косинусу угла. Бегущая строка `.mark__inner` едет через ScrollTrigger со `scrub`.
Что менять: картинки в массиве `IMAGES` (хватит 6–10 штук, они повторяются; лучше вертикальные 4 к 5), число блоков (цикл на 16), ширину колонки `--item-width`, фон `--color-bg` (он же цвет затухания), цвет и размер строки `--color-marquee` и `--font-size-marquee`, имена в строке. Силу ряби задают числа 20, 30 и `uLiquid / 30` в шейдере и `render`; глубину и кривизну барабана — `uCurve` и `uDepth` в `resizeWebGL`.
Если проект на React: перенеси код в `useEffect` с пустым списком зависимостей, дождись загрузки текстур, при размонтировании вызови `gsap.ticker.remove(render)`, `renderer.dispose()`, удали слушатель `resize` и `lenis.destroy()`. Не убирай блоки-заглушки и не меняй их размеры после старта без вызова `resizeWebGL`. При `prefers-reduced-motion` барабан спрямляется (`uCurve` почти ноль), а Lenis отключается: оставь эту ветку.
Покажи, где на моём сайте такая галерея лучше всего смотрится.
Код скопируется вместе с промптом
Вертикальная колонка фотографий, которая при прокрутке ведёт себя так, будто снимки наклеены на внутреннюю стенку огромного горизонтального барабана. В середине экрана фото лежат ровно и яркие, а к верхнему и нижнему краю они изгибаются, поворачиваются и выцветают в цвет фона. Поверх идёт строка с именами, а при быстром скролле картинка «течёт»: по ней проходят волны, а цветовые каналы чуть расходятся.
Устроено так: фотографии остаются в странице как обычные блоки-заглушки, а рисует их three.js на холсте. Каждая фотография — плоскость, которую вершинный шейдер изгибает по дуге барабана (синус и косинус от расстояния до середины экрана), а фрагментный шейдер добавляет «жидкость» и обесцвечивание. Скролл ведёт Lenis, имена на строке двигает ScrollTrigger. Подходит для портфолио, страниц коллекций и работ, обложек журналов. В оригинале автора 15 вариаций, от простого вращения на CSS до этого барабана, здесь взят барабан.
Код
<!-- Pictures: /images/1.webp ... /images/8.webp (replace with your own, portrait 4:5). Serve over http, not file:// -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Drum Gallery on Scroll</title>
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Archivo:wdth,wght@62..125,100..900&family=Inter:wght@500&display=swap">
<script type="importmap">{ "imports": { "three": "https://cdn.jsdelivr.net/npm/three@0.170.0/build/three.module.js" } }</script>
<style>
*, *::before, *::after { box-sizing: border-box; }
:root {
--color-bg: #110b0c; --color-text: rgb(201, 170, 168); --color-marquee: rgb(190, 110, 115);
--item-width: 400px; --item-ar: 4 / 5; --font-size-marquee: clamp(2rem, 16vw, 7rem);
}
body { margin: 0; color: var(--color-text); background: var(--color-bg); font-family: "Inter", sans-serif; overflow-x: clip; }
html.lenis, html.lenis body { height: auto; }
.frame { position: fixed; top: 1.5rem; left: 1.5rem; z-index: 5; font-size: .8rem; letter-spacing: .06em; text-transform: uppercase; }
/* The gallery is a column of pictures. They stay in the DOM only to hold their places (visibility: hidden): the canvas draws them */
.gallery { position: relative; display: flex; flex-direction: column; align-items: center; margin: 25vh 0 35vh; }
.gallery__item-wrap { width: 100%; max-width: var(--item-width); margin-bottom: 3rem; }
.gallery__item { width: 100%; aspect-ratio: var(--item-ar); background: center / cover no-repeat; }
.gallery--webgl .gallery__item { visibility: hidden; }
.webgl { position: fixed; top: 0; left: 0; width: 100%; height: 100%; pointer-events: none; }
/* Names run across the middle of the screen, behind the canvas drawing */
.mark { position: fixed; top: 50%; left: 0; width: 100vw; transform: translateY(-50%); z-index: 1; overflow: hidden; mix-blend-mode: plus-lighter; }
.mark__inner { display: flex; gap: 3rem; width: max-content; position: relative; will-change: transform; transform: translateX(100vw);
font-family: "Archivo", sans-serif; font-stretch: 125%; font-weight: 800; }
.mark__inner span { white-space: nowrap; text-transform: uppercase; color: var(--color-marquee); font-size: var(--font-size-marquee); line-height: 1; }
</style>
</head>
<body>
<div class="frame">Drum gallery</div>
<canvas class="webgl"></canvas>
<main>
<div class="gallery gallery--webgl" id="gallery"></div>
<div class="mark">
<div class="mark__inner">
<span>Sora Ishikawa</span><span>/</span><span>Emi Takahashi</span><span>/</span><span>Kaito Murakami</span><span>/</span>
<span>Yui Sakamoto</span><span>/</span><span>Ren Ishida</span><span>/</span><span>Honoka Maeda</span><span>/</span><span>Hayato Ogawa</span>
</div>
</div>
</main>
<script src="https://cdn.jsdelivr.net/npm/gsap@3.13.0/dist/gsap.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/gsap@3.13.0/dist/ScrollTrigger.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/lenis@1.1.13/dist/lenis.min.js"></script>
<script type="module">
// Based on Codrops RotatingOnScrollAnimations (MIT), https://github.com/codrops/RotatingOnScrollAnimations
import * as THREE from 'three';
gsap.registerPlugin(ScrollTrigger);
const reduceMotion = matchMedia('(prefers-reduced-motion: reduce)').matches;
// The pictures: replace img/1.webp ... img/8.webp (portrait 4:5). 16 items are built from them
const IMAGES = [1, 2, 3, 4, 5, 6, 7, 8].map(n => `/images/${n}.webp`);
const gallery = document.getElementById('gallery');
for (let i = 0; i < 16; i++) {
gallery.insertAdjacentHTML('beforeend', `<div class="gallery__item-wrap"><div class="gallery__item" style="background-image:url('${IMAGES[i % IMAGES.length]}')"></div></div>`);
}
const items = [...gallery.querySelectorAll('.gallery__item')];
// Uniforms shared by every picture
const drumUniforms = {
uCurve: { value: 0 }, // 1 / radius of the drum
uDepth: { value: 0 }, // how far the drum's front is pushed back
uLiquid: { value: 0 }, // strength of the "liquid" distortion, follows the scroll speed
uTime: { value: 0 },
uFog: { value: new THREE.Color() }
};
const vertexShader = /* glsl */ `
uniform vec2 uSize; uniform float uOffset, uCurve, uDepth, uLiquid, uTime;
varying vec2 vUv; varying float vAngle;
void main() {
vec3 pos = position * vec3(uSize, 1.0);
// liquid: the picture sways and ripples while scrolling
pos.x += sin(uv.y * 6.0 - uTime * 3.0) * uLiquid * 20.0;
float ripple = sin(uv.y * 14.0 + uv.x * 4.0 - uTime * 5.0) * uLiquid * 30.0;
// bend the picture around the inside of a horizontal drum
float angle = (uOffset + pos.y) * uCurve;
pos.y = sin(angle) / uCurve;
pos.z = (1.0 - cos(angle)) / uCurve - uDepth;
pos += vec3(0.0, -sin(angle), cos(angle)) * ripple;
vUv = uv; vAngle = angle;
gl_Position = projectionMatrix * modelViewMatrix * vec4(pos, 1.0);
}
`;
const fragmentShader = /* glsl */ `
uniform sampler2D uTexture; uniform vec2 uSize, uImageSize; uniform float uLiquid, uTime; uniform vec3 uFog;
varying vec2 vUv; varying float vAngle;
void main() {
if (abs(vAngle) > 1.5708) discard; // nothing past the floor or the ceiling of the drum
// same as background-size: cover
vec2 ratio = vec2(min((uSize.x / uSize.y) / (uImageSize.x / uImageSize.y), 1.0),
min((uSize.y / uSize.x) / (uImageSize.y / uImageSize.x), 1.0));
vec2 uv = (vUv - 0.5) * ratio + 0.5;
// liquid: wavy refraction, colours pulled slightly apart
uv.x += sin(uv.y * 24.0 - uTime * 4.0) * 0.006 * uLiquid;
vec2 shift = vec2(0.0, 0.012 * uLiquid);
vec3 color = vec3(texture2D(uTexture, uv + shift).r, texture2D(uTexture, uv).g, texture2D(uTexture, uv - shift).b);
// pictures lose their colour and fade into the background as they turn away
float light = pow(cos(vAngle), 2.5);
float gray = dot(color, vec3(0.299, 0.587, 0.114));
color = mix(vec3(gray), color, light);
color = mix(uFog, color, 0.15 + light * 0.85);
gl_FragColor = vec4(color, 1.0);
}
`;
// Smooth scroll; remember its speed for the liquid effect
let scrollVelocity = 0;
function initSmoothScrolling() {
const lenis = new Lenis();
lenis.on('scroll', ({ velocity }) => { scrollVelocity = Math.abs(velocity); ScrollTrigger.update(); });
gsap.ticker.add(time => lenis.raf(time * 1000));
gsap.ticker.lagSmoothing(0);
}
// WebGL: one plane per picture, all bent by the vertex shader
const viewport = { width: 0, height: 0 };
let renderer, scene, camera, planes = [], lastTop = null, needsRender = true;
function initWebGL(textures) {
renderer = new THREE.WebGLRenderer({ canvas: document.querySelector('.webgl'), antialias: true, alpha: true });
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera(45, 1, 10, 5000);
camera.position.z = 1000;
// fade towards the page background
drumUniforms.uFog.value.setStyle(getComputedStyle(document.body).getPropertyValue('--color-bg').trim(), THREE.LinearSRGBColorSpace);
const geometry = new THREE.PlaneGeometry(1, 1, 32, 64);
planes = items.map(item => {
const texture = textures.get(item.style.backgroundImage.match(/url\(["']?(.*?)["']?\)/)[1]);
texture.anisotropy = renderer.capabilities.getMaxAnisotropy();
const plane = new THREE.Mesh(geometry, new THREE.ShaderMaterial({
vertexShader, fragmentShader,
uniforms: {
...drumUniforms,
uTexture: { value: texture },
uImageSize: { value: new THREE.Vector2(texture.image.width, texture.image.height) },
uSize: { value: new THREE.Vector2() },
uOffset: { value: 0 }
}
}));
plane.frustumCulled = false;
scene.add(plane);
return plane;
});
resizeWebGL();
}
function resizeWebGL() {
viewport.width = renderer.domElement.clientWidth;
viewport.height = renderer.domElement.clientHeight;
renderer.setSize(viewport.width, viewport.height, false);
camera.aspect = viewport.width / viewport.height;
// match the field of view to the viewport, so 1 unit = 1 pixel at z = 0
camera.fov = 2 * Math.atan(viewport.height / 2 / camera.position.z) * (180 / Math.PI);
camera.updateProjectionMatrix();
needsRender = true;
// the floor and the ceiling of the drum line up with the viewport edges; reduced motion flattens it
const radius = viewport.height / 2;
drumUniforms.uCurve.value = reduceMotion ? 0.000001 : 1 / radius;
drumUniforms.uDepth.value = reduceMotion ? 0 : radius;
}
// Every frame: place each plane where its DOM picture is, then draw (only if something changed)
function render() {
const top = items[0].getBoundingClientRect().top;
const settling = scrollVelocity > 0 || drumUniforms.uLiquid.value > 0.001;
if (!needsRender && !settling && top === lastTop) return;
needsRender = false;
lastTop = top;
const ease = 1 - Math.pow(1 - 0.08, gsap.ticker.deltaRatio());
drumUniforms.uLiquid.value = gsap.utils.interpolate(drumUniforms.uLiquid.value, Math.min(scrollVelocity / 30, 1), ease);
drumUniforms.uTime.value = gsap.ticker.time;
planes.forEach((plane, i) => {
const rect = items[i].getBoundingClientRect();
const { uniforms } = plane.material;
uniforms.uOffset.value = viewport.height / 2 - rect.top - rect.height / 2; // distance from the middle = place on the drum
uniforms.uSize.value.set(rect.width, rect.height);
plane.position.x = rect.left + rect.width / 2 - viewport.width / 2;
});
renderer.render(scene, camera);
}
// Names slide across the screen while the gallery scrolls past
gsap.timeline({ scrollTrigger: { trigger: gallery, start: 'top bottom', end: 'bottom top', scrub: true, invalidateOnRefresh: true } })
.fromTo('.mark__inner', { x: '100vw' }, { x: '-100%', ease: 'none' });
// Load the textures, then start
const loader = new THREE.TextureLoader();
Promise.all(IMAGES.map(async url => [url, await loader.loadAsync(url)])).then(entries => {
initWebGL(new Map(entries));
if (!reduceMotion) initSmoothScrolling();
addEventListener('resize', resizeWebGL);
gsap.ticker.add(render);
});
</script>
</body>
</html>