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

Эффекты и шейдерыТёмный3DЯркийБесплатно

Сетка фото, которую скролл закручивает в воронку

Быстрый скролл закручивает сетку фото в вихрь вокруг курсора с размытием вращения; когда скролл стихает, сетка встаёт на место.

Сетка фото, которую скролл закручивает в воронку
Промпт
Добавь на мою страницу эффект «Сетка фото, которую скролл закручивает в воронку» (по мотивам Codrops ElasticGridScroll, вариант Whirlpool, MIT). Ниже готовая страница: GSAP 3.13.0 с ScrollTrigger и ScrollSmoother (jsdelivr) плюс three.js 0.170.0 через importmap. Сначала перенеси её как есть и открой через локальный сервер, а не файл: браузер не даст прочитать пиксели картинок с адреса `file://`. Убедись, что при быстром скролле сетка закручивается, и только потом меняй.

Как устроен код. Сетка `.grid` из колонок `.grid__column` с плитками `.grid__item-img` (картинка в `background-image`, пропорции 128 к 160). Крайние колонки вдвое уже и показывают внутреннюю половину своих картинок, чтобы сетка была ровно во всю ширину окна. ScrollSmoother даёт каждой колонке своё запаздывание (`smoother.effects(el, { lag })`, больше к середине). Класс `Whirlpool` создаёт `THREE.WebGLRenderer` и один прямоугольник на весь экран с `ShaderMaterial`. Все уникальные картинки запекаются в `THREE.DataArrayTexture` размером 400 на 500 (метод `load`). Функция `sync` каждый кадр передаёт шейдеру положение каждой колонки на экране, а `update` считает закрутку по скорости скролла. Фрагментный шейдер ищет, откуда взять цвет для пикселя: функции `untwist` (поворот с затуханием от центра `uCenter`) и `gridAt` (какая плитка лежит в этой точке), девять сэмплов даёт размытие вращения. После загрузки у `body` включается класс `is-webgl`, DOM-картинки скрываются (`visibility: hidden`), а рисует их canvas.

Что менять: картинки (8 штук хватит, они повторяются; вертикальные, лучше 800 на 1000), количество колонок `COLS` и строк `ROWS` (общее число плиток не больше 256, колонок не больше 12, иначе поднимай `maxColumns` и `maxItems`), фон страницы. Характер вихря задают константы вверху скрипта: `maxTwist` (сколько оборотов, в радианах), `speedScale` (насколько быстрый скролл нужен), `reach` (радиус вихря), `pinch` (втягивание), `blur` и `shade`. Колонки отстают по-разному из-за `baseLag` и `lagFactor`.

Если проект на React: вынеси код в `useEffect`, создавай `Whirlpool` один раз, после загрузки картинок. При размонтировании вызови `gsap.ticker.remove(whirlpool.update)`, `smoother.kill()`, у рендерера `dispose()` и удали его canvas. Не оборачивай `#smooth-wrapper` и `#smooth-content` в другие блоки, не удаляй `.webgl` и `.is-webgl .grid__item-img`: иначе картинки будут нарисованы дважды. Если у посетителя включено уменьшение анимации или нет WebGL 2, оставь обычную сетку: этот случай в коде уже обработан, не убирай его.
Покажи, где на моём сайте такая сетка будет работать лучше всего.

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

Страница выглядит как обычная плотная сетка фотографий: одиннадцать колонок, каждая прокручивается с собственным запаздыванием, поэтому при скролле они «тянутся» с разной скоростью. Но стоит прокрутить быстро, и вся сетка закручивается в воронку вокруг курсора: центр поворачивается сильнее всего и втягивается внутрь, края поворачиваются меньше, картинка размывается по дуге вращения, а растянутые места темнеют. Когда скролл замедляется, вихрь раскручивается и сетка на целом числе оборотов возвращается на место, так что ни одна точка не крутится назад.

Это не CSS-трюк: все картинки собраны в одну текстуру-массив, а сетка рисуется на canvas фрагментным шейдером three.js, который на каждый пиксель решает, из какой плитки его брать. В состоянии покоя результат пиксель в пиксель совпадает с обычными DOM-картинками, а при запрете анимации или без WebGL 2 страница остаётся обычной сеткой. Подходит для портфолио, каталогов, главной страницы творческой студии. Взята самая сложная из девяти вариаций оригинала.

Код
<!-- 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>Whirlpool Grid Scroll</title>
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?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; }
html, body { margin: 0; }
body { background: #0b0a09; color: #fff; font-family: "Inter", sans-serif; }
/* the WebGL canvas sits behind the page; once it works the DOM images are hidden and the canvas draws them */
.webgl { position: fixed; top: 0; left: 0; pointer-events: none; }
.is-webgl .grid__item-img { visibility: hidden; }
.frame { position: fixed; inset: 0; z-index: 10; pointer-events: none; padding: 1.5rem 2rem; font-size: .85rem; letter-spacing: .06em; text-transform: uppercase;
  background: linear-gradient(to bottom, rgba(0,0,0,.85), rgba(0,0,0,0) 20rem, rgba(0,0,0,0) calc(100% - 20rem), rgba(0,0,0,.85)); }
.frame h1 { margin: 0; font-size: inherit; font-weight: 500; }
.frame p { margin: .4rem 0 0; color: #fece5c; }

/* 11 columns: the two outer ones are half as wide and show the inner half of their images, so the grid is exactly as wide as the window */
.grid { display: grid; grid-template-columns: 0.5fr repeat(9, 1fr) 0.5fr; padding: 0; }
.grid__column { display: flex; flex-direction: column; }
.grid__column:first-child, .grid__column:last-child { overflow: clip; }
.grid__column:first-child .grid__item, .grid__column:last-child .grid__item { width: 200%; }
.grid__column:first-child .grid__item { margin-left: -100%; }
.grid__item { margin: 0; }
.grid__item-img { aspect-ratio: 128 / 160; background-size: cover; background-position: center; }
</style>
</head>
<body>
<header class="frame"><h1>Whirlpool grid</h1><p>Scroll and move the mouse</p></header>
<div id="smooth-wrapper">
  <main id="smooth-content">
    <!-- Items are generated by the script below; the pictures are img/1.webp ... img/8.webp (portrait 4:5) -->
    <div class="grid" id="grid"></div>
  </main>
</div>

<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/gsap@3.13.0/dist/ScrollSmoother.min.js"></script>
<script type="module">
// Based on Codrops ElasticGridScroll (MIT), https://github.com/codrops/ElasticGridScroll
import * as THREE from 'three';
gsap.registerPlugin(ScrollTrigger, ScrollSmoother);

// ─── Whirlpool settings: scrolling swirls the grid around the pointer (or the middle of the window) ───
const maxTwist = 10.55;  // twist (radians, at the center) on a fast scroll
const speedScale = 2200; // scroll speed (px/s) that takes the twist to ~0.76 of maxTwist
const windUp = 0.12;     // seconds the twist takes to follow a faster scroll
const windDown = 0.3;    // seconds it takes to settle
const reach = 0.36;      // how far the twist reaches, as a share of the window's diagonal
const pinch = 0.18;      // how much it pulls in towards the center
const blur = 0.022;      // seconds of rotational motion blur
const maxBlur = 0.12;    // blur limit (radians)
const shade = 0.35;      // darkening where the twist stretches the grid most
const follow = 0.3;      // seconds the twist's center takes to catch up with the pointer
const textureWidth = 400, textureHeight = 500; // every image is baked at this size into one texture array
const maxColumns = 12, maxItems = 256;         // shader array sizes

const vertexShader = /* glsl */ `
  void main() { gl_Position = vec4(position.xy, 0.0, 1.0); } // a plane covering the canvas
`;

const fragmentShader = /* glsl */ `
  #define MAX_COLUMNS ${maxColumns}
  #define MAX_ITEMS ${maxItems}
  uniform highp sampler2DArray uImages;
  uniform vec2 uViewport; uniform float uPixelRatio; uniform vec2 uTextureSize;
  uniform float uColumnWidth, uImageHeight, uSheetLeft;
  uniform int uColumnCount;
  uniform vec4 uColumns[MAX_COLUMNS];     // per column: top (px, lag included), first item, item count
  uniform vec4 uLayers[MAX_ITEMS / 4];    // which image each item shows, four to a vec4
  uniform vec2 uCenter;                   // center of the twist (px)
  uniform float uTwist, uPhase;           // twist at the center, turn of the whole grid (radians)
  uniform float uSpinTwist, uSpinPhase;   // angles the motion blur spreads over
  uniform float uRadius, uPinch, uShade;

  float layerOf(int item) {
    vec4 four = uLayers[item / 4];
    int k = item - (item / 4) * 4;
    return k == 0 ? four.x : k == 1 ? four.y : k == 2 ? four.z : four.w;
  }

  // the grid's color at a point (px on screen, before the twist); wraps round both ways
  vec3 gridAt(vec2 q, float lod) {
    float x = (q.x - uSheetLeft) / uColumnWidth;
    float column = floor(x);
    vec4 data = uColumns[int(mod(column, float(uColumnCount)))];
    float y = q.y - data.x;
    float row = mod(floor(y / uImageHeight), data.z);
    return textureLod(uImages, vec3(x - column, y / uImageHeight - row, layerOf(int(data.y) + int(row))), lod).rgb;
  }

  // where the content shown at p comes from, for this twist and phase
  vec2 untwist(vec2 p, float twist, float phase) {
    vec2 d = p - uCenter;
    float falloff = exp(-dot(d, d) / (uRadius * uRadius));
    float a = -(phase + twist * falloff);
    return uCenter + mat2(cos(a), sin(a), -sin(a), cos(a)) * d * (1.0 + uPinch * abs(twist) * falloff);
  }

  void main() {
    vec2 p = vec2(gl_FragCoord.x, uViewport.y * uPixelRatio - gl_FragCoord.y) / uPixelRatio;
    float lod = max(log2(uTextureSize.x / (uColumnWidth * uPixelRatio)) - 0.5, 0.0);
    vec3 color;
    if (abs(uTwist) < 0.0001 && abs(uPhase) < 0.0001 && abs(uSpinTwist) + abs(uSpinPhase) < 0.0001) {
      color = gridAt(p, lod);                       // at rest: exactly the DOM images
    } else {
      color = vec3(0.0);
      for (int k = 0; k < 9; k++) {                 // rotational motion blur: nine samples across the turned angle
        float t = float(k) / 8.0 - 0.5;
        color += gridAt(untwist(p, uTwist + t * uSpinTwist, uPhase + t * uSpinPhase), lod);
      }
      color /= 9.0;
      vec2 d = p - uCenter;
      float r2 = dot(d, d) / (uRadius * uRadius);
      float shear = abs(uTwist) * 2.0 * r2 * exp(-r2);
      color *= 1.0 - uShade * min(shear, 1.0);      // darker where the grid is stretched most
    }
    gl_FragColor = vec4(color, 1.0);
  }
`;

class Whirlpool {
  constructor() {
    this.renderer = new THREE.WebGLRenderer({ antialias: false, alpha: false });   // throws without WebGL 2
    this.renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
    const [r, g, b] = getComputedStyle(document.body).backgroundColor.match(/[\d.]+/g).map(Number);
    this.renderer.setClearColor(new THREE.Color().setRGB(r / 255, g / 255, b / 255, THREE.SRGBColorSpace));
    this.renderer.domElement.className = 'webgl';
    document.body.prepend(this.renderer.domElement);

    this.uniforms = {
      uImages: { value: null }, uViewport: { value: new THREE.Vector2(1, 1) }, uPixelRatio: { value: 1 },
      uTextureSize: { value: new THREE.Vector2(textureWidth, textureHeight) },
      uColumnWidth: { value: 1 }, uImageHeight: { value: 1 }, uSheetLeft: { value: 0 }, uColumnCount: { value: 0 },
      uColumns: { value: Array.from({ length: maxColumns }, () => new THREE.Vector4()) },
      uLayers: { value: Array.from({ length: maxItems / 4 }, () => new THREE.Vector4()) },
      uCenter: { value: new THREE.Vector2() }, uTwist: { value: 0 }, uPhase: { value: 0 },
      uSpinTwist: { value: 0 }, uSpinPhase: { value: 0 }, uRadius: { value: 1 }, uPinch: { value: pinch }, uShade: { value: shade }
    };
    const material = new THREE.ShaderMaterial({ vertexShader, fragmentShader, uniforms: this.uniforms,
      blending: THREE.NoBlending, depthTest: false, depthWrite: false });
    const quad = new THREE.Mesh(new THREE.PlaneGeometry(2, 2), material);
    quad.frustumCulled = false;
    this.scene = new THREE.Scene(); this.scene.add(quad);
    this.camera = new THREE.Camera();

    this.layers = new Map(); this.columns = [];
    this.twist = 0; this.phase = 0; this.settle = null;
    this.gridTop = null; this.center = null; this.target = null; this.needsRender = true;
    addEventListener('pointermove', e => (this.target = { x: e.clientX, y: e.clientY }));
    document.documentElement.addEventListener('pointerleave', () => (this.target = null));
    this.update = this.update.bind(this); this.sync = this.sync.bind(this);
  }

  // bake every distinct image into one texture array (a layer each), cropped like background-size: cover
  async load(elements) {
    const urlOf = el => getComputedStyle(el).backgroundImage.match(/url\(["']?(.*?)["']?\)/)[1];
    const urls = [...new Set(elements.map(urlOf))];
    elements.forEach(el => this.layers.set(el, urls.indexOf(urlOf(el))));
    const images = await Promise.all(urls.map(async url => { const img = new Image(); img.src = url; await img.decode(); return img; }));
    const canvas = document.createElement('canvas');
    canvas.width = textureWidth; canvas.height = textureHeight;
    const ctx = canvas.getContext('2d', { willReadFrequently: true });
    const layerSize = textureWidth * textureHeight * 4;
    const data = new Uint8Array(layerSize * images.length);
    images.forEach((img, i) => {
      const s = Math.max(textureWidth / img.naturalWidth, textureHeight / img.naturalHeight);
      const w = img.naturalWidth * s, h = img.naturalHeight * s;
      ctx.drawImage(img, (textureWidth - w) / 2, (textureHeight - h) / 2, w, h);
      data.set(ctx.getImageData(0, 0, textureWidth, textureHeight).data, i * layerSize);
    });
    const texture = new THREE.DataArrayTexture(data, textureWidth, textureHeight, images.length);
    texture.minFilter = THREE.LinearMipmapLinearFilter; texture.magFilter = THREE.LinearFilter;
    texture.generateMipmaps = true; texture.needsUpdate = true;
    this.uniforms.uImages.value = texture;
  }

  // take over the grid's columns
  setColumns(grid, columnElements) {
    const { uColumnCount, uLayers } = this.uniforms;
    this.grid = grid;
    let item = 0;
    this.columns = columnElements.slice(0, maxColumns).map(element => {
      const images = [...element.querySelectorAll('.grid__item-img')].slice(0, maxItems - item);
      const first = item;
      images.forEach(el => { uLayers.value[Math.floor(item / 4)].setComponent(item % 4, this.layers.get(el)); item++; });
      return { element, images, first };
    });
    uColumnCount.value = this.columns.length;
    this.measure();
  }

  // measure the layout: after the grid is built and on every resize
  measure() {
    const width = innerWidth, height = innerHeight;
    this.renderer.setSize(width, height);
    const { uViewport, uPixelRatio, uColumnWidth, uImageHeight, uSheetLeft, uRadius } = this.uniforms;
    uViewport.value.set(width, height);
    uPixelRatio.value = this.renderer.getPixelRatio();
    uRadius.value = reach * Math.hypot(width, height);
    const [first, second] = this.columns[0].images.map(el => el.getBoundingClientRect());
    uColumnWidth.value = first.width;
    uImageHeight.value = second ? second.top - first.top : first.height;
    uSheetLeft.value = first.left;
    this.columns.forEach(c => (c.offset = c.images[0].getBoundingClientRect().top - c.element.getBoundingClientRect().top));
    this.gridTop = null; this.needsRender = true;
    this.sync();
  }

  // every frame: follow the scroll speed with the twist, hand the twist over to the phase as it settles, draw
  update(time, deltaTime) {
    const elapsed = deltaTime / 1000;
    if (!elapsed) return;
    const dt = Math.min(elapsed, 1 / 30);
    const top = this.grid.getBoundingClientRect().top;
    const speed = this.gridTop === null ? 0 : (top - this.gridTop) / elapsed;   // px/s, negative while scrolling down
    this.gridTop = top;

    const target = maxTwist * Math.tanh(-speed / speedScale);
    const previousTwist = this.twist, previousPhase = this.phase;
    const reversing = target * previousTwist < 0;
    const winding = reversing || Math.abs(target) > Math.abs(previousTwist);
    this.twist += (target - this.twist) * (1 - Math.exp(-dt / (winding ? windUp : windDown)));

    if (winding) {
      this.settle = null;   // the phase holds: the center turns on, the outer grid waits
    } else if (this.twist !== previousTwist) {
      // settling: the phase turns on as the twist lets go, so no point ever turns back;
      // it ends on the next whole turn, where the grid is back as it was
      if (!this.settle) {
        const center = this.phase + previousTwist;
        const turns = previousTwist > 0 ? Math.ceil(center / (2 * Math.PI)) : Math.floor(center / (2 * Math.PI));
        this.settle = { phase: this.phase, twist: previousTwist, goal: turns * 2 * Math.PI };
      }
      const { phase, twist, goal } = this.settle;
      this.phase = phase + (goal - phase) * (1 - this.twist / twist);
    }

    const left = Math.abs(this.twist) + (this.settle ? Math.abs(this.settle.goal - this.phase) : 0);
    const resting = !target && left * Math.hypot(innerWidth, innerHeight) < 0.5;
    if (resting) {
      if (this.twist || this.phase || this.uniforms.uSpinTwist.value || this.uniforms.uSpinPhase.value) this.needsRender = true;
      this.twist = 0; this.phase = 0; this.settle = null;
    } else this.needsRender = true;

    // the center drifts after the pointer (or back to the middle), but holds while the whole grid is turned
    const goal = this.target ?? { x: innerWidth / 2, y: innerHeight / 2 };
    this.center ??= { ...goal };
    if (!this.phase) {
      const ease = 1 - Math.exp(-dt / follow);
      this.center.x += (goal.x - this.center.x) * ease;
      this.center.y += (goal.y - this.center.y) * ease;
    }

    let spinTwist = ((this.twist - previousTwist) / dt) * blur;
    let spinPhase = ((this.phase - previousPhase) / dt) * blur;
    const k = Math.min(1, maxBlur / (Math.abs(spinTwist) + Math.abs(spinPhase) || 1));
    const u = this.uniforms;
    u.uTwist.value = this.twist; u.uPhase.value = this.phase;
    u.uSpinTwist.value = resting ? 0 : spinTwist * k;
    u.uSpinPhase.value = resting ? 0 : spinPhase * k;
    u.uCenter.value.set(this.center.x, this.center.y);
    this.sync();
  }

  // give the shader where every column is and draw, if anything moved
  sync() {
    const { uColumns } = this.uniforms;
    this.columns.forEach((c, i) => {
      const top = c.element.getBoundingClientRect().top + c.offset;
      if (top !== uColumns.value[i].x) this.needsRender = true;
      uColumns.value[i].set(top, c.first, c.images.length, 0);
    });
    if (!this.needsRender) return;
    this.needsRender = false;
    this.renderer.render(this.scene, this.camera);
  }
}

// ─── Page: columns with their own lag (ScrollSmoother), the WebGL layer on top of them ───
const reduced = matchMedia('(prefers-reduced-motion: reduce)').matches;
let whirlpool = null;
const smoother = ScrollSmoother.create({
  smooth: reduced ? 0 : 1, effects: true, normalizeScroll: true,
  onUpdate: () => whirlpool?.sync()   // touch scrolling moves the page outside the ticker too
});
if (!reduced) { try { whirlpool = new Whirlpool(); } catch (e) { whirlpool = null; } }   // no WebGL 2: a plain lag grid

// Build 11 columns x 12 rows from 8 pictures
const grid = document.getElementById('grid');
const COLS = 11, ROWS = 12;
for (let c = 0; c < COLS; c++) {
  let html = '';
  for (let r = 0; r < ROWS; r++) html += `<figure class="grid__item"><div class="grid__item-img" style="background-image:url(/images/${(c * 3 + r) % 8 + 1}.webp)"></div></figure>`;
  grid.insertAdjacentHTML('beforeend', `<div class="grid__column">${html}</div>`);
}

// Each column lags behind the scroll; the lag grows towards the middle column
const baseLag = 0.3, lagFactor = 0.15;
const columnEls = [...grid.querySelectorAll('.grid__column')];
const mid = (COLS - 1) / 2, maxDistance = Math.floor(COLS / 2);
columnEls.forEach((el, i) => {
  const lag = baseLag + (maxDistance - Math.abs(i - mid) + 1) * lagFactor;
  if (!reduced) smoother.effects(el, { speed: 1, lag });
});

addEventListener('resize', () => whirlpool?.measure());

const images = [...grid.querySelectorAll('.grid__item-img')];
const preload = Promise.all([...new Set(images.map(el => getComputedStyle(el).backgroundImage.slice(5, -2)))]
  .map(src => { const i = new Image(); i.src = src; return i.decode().catch(() => {}); }));
Promise.all([preload, whirlpool?.load(images)]).then(() => {
  whirlpool?.setColumns(grid, columnEls);
  if (whirlpool) {
    document.body.classList.add('is-webgl');         // hides the DOM images; the canvas draws them from here on
    whirlpool.update(0, 16);                         // first frame now, so there is never a frame without images
    gsap.ticker.add(whirlpool.update);               // then follow the scroll on every frame
  }
});
</script>
</body>
</html>

Похожие