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

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

Граница героя, которую фото «затекает» чернилами в белую страницу

Когда белая страница наезжает на фото героя, снимок затекает в неё рваными чернильными пятнами; чем быстрее скролл, тем мягче край.

Граница героя, которую фото «затекает» чернилами в белую страницу
Промпт
Добавь на мою страницу эффект «Граница героя, которую фото затекает чернилами в белую страницу» (по мотивам Codrops SeamTransitions, вариант Ink Bleed, MIT). Ниже готовая страница без библиотек: на стыке тёмного героя с фото и белой секции лежит canvas, а WebGL 2 шейдер рисует рваную чернильную границу. Сначала перенеси её как есть и открой через локальный сервер (не файл: фото грузится с другого домена с `crossorigin="anonymous"`, иначе текстуру не прочитать). Убедись, что при скролле фото затекает в белую страницу, и только потом меняй.

Как устроен код. `.hero` с картинкой `#img` (она выше героя на `--below`, это запас под «чернила»), под ним `.seam` высотой `ABOVE + below()` пикселей, внутри создаётся canvas. Функция `start` собирает программу из `vertexSrc` (один треугольник на весь canvas) и `fragmentSrc`, загружает картинку как текстуру. Каждый кадр считаются `travel` (насколько край героя поднялся от низа экрана), `progress` (то же от 0 до 1) и `velocity` (скорость скролла, сглаженная); canvas перерисовывается, только пока шов на экране. В шейдере три шума (лопасти, мелкая рваность, тонкие «прожилки») дают поле `g`: чем оно больше, тем глубже заходит фото в белое. `uProgress` и `uVelocity` задают, насколько далеко и насколько мягко. Последние строки шейдера рисуют только разницу между «страницей под canvas» (фото сверху, бумага снизу) и пятном: там, где они совпадают, canvas прозрачен.

Что менять: картинку героя и заголовок, цвет бумаги `--paper` и `uPaper` (держи их одинаковыми), `VEIL` (затемнение, должно совпадать с `.hero::after`), высоту шва `ABOVE` и `below()`, силу растекания (коэффициенты в `spread` и `reach`).

Если проект на React: перенеси код в `useEffect`, создавай WebGL контекст один раз после загрузки картинки и снимай слушатели и requestAnimationFrame при размонтировании. Не делай герой выше экрана без пересчёта `resize`: от него зависит положение шва.
Покажи, где на моём сайте такая граница будет работать лучше всего.

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

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

Всё рисует один фрагментный шейдер WebGL 2 на узкой полосе поверх стыка секций. Он знает, как далеко страница поднялась и с какой скоростью движется, поэтому при быстром скролле пятна шире и мягче. Если WebGL 2 нет, остаётся обычная ровная граница. Подойдёт для студий, лендингов с большим фото на первом экране, портфолио. Из одиннадцати вариантов оригинала взят самый наглядный (Ink Bleed), остальные работают на той же заготовке.

Код
<!-- Pictures come from picsum.photos as placeholders: replace the URLs with your own images. -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Ink Bleed Seam</title>
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;600;800&display=swap">
<style>
*, *::before, *::after { box-sizing: border-box; }
:root { --paper: #f4f1ea; --ink: #16140f; --hero: 100vh; }
html, body { margin: 0; }
body { background: var(--paper); color: var(--ink); font-family: "Plus Jakarta Sans", sans-serif; }

.hero { position: relative; height: var(--hero); overflow: hidden; background: #0f1512; color: #fff; }
/* the picture is a little taller than the hero: its lower part is what the ink "bleeds" over the white page */
.hero__img { position: absolute; inset: 0 0 auto; width: 100%; height: calc(100% + var(--below, 0px)); object-fit: cover; }
.hero::after { content: ""; position: absolute; inset: 0; background: rgba(0, 0, 0, .3); }   /* a flat dark veil so the type reads */
.hero__content { position: absolute; z-index: 2; left: 5vw; bottom: calc(var(--above, 0px) + 4vh); }
.hero__title { margin: 0; font-size: clamp(4rem, 17vw, 15rem); font-weight: 800; line-height: .85; letter-spacing: -.04em; }
.hero__note { margin: 1.2rem 0 0; font-size: 1.1rem; opacity: .85; }

/* the seam: a box astride the hero's lower edge; a WebGL canvas fills it */
.seam { position: absolute; left: 0; right: 0; z-index: 5; pointer-events: none; top: calc(var(--hero) - var(--above, 0px)); height: calc(var(--above, 0px) + var(--below, 0px)); }
.seam canvas { display: block; width: 100%; height: 100%; }

.next { position: relative; background: var(--paper); padding: 34vh 5vw 14vh; overflow-x: clip; }
.next__label { margin: 0 0 1.5rem; font-size: .9rem; letter-spacing: .08em; text-transform: uppercase; opacity: .6; }
.next__text { margin: 0; max-width: 24em; font-size: clamp(1.6rem, 3.6vw, 3rem); line-height: 1.15; font-weight: 600; }
.projects { list-style: none; margin: 14vh 0 0; padding: 0; display: flex; gap: 2rem; }
.projects li { flex: 0 0 min(28vw, 320px); }
.projects img { display: block; width: 100%; aspect-ratio: 3 / 4; object-fit: cover; background: #ddd8cc; }
.projects p { margin: .7rem 0 0; font-weight: 600; } .projects span { opacity: .5; font-weight: 400; margin-left: .4rem; }
</style>
</head>
<body>
<section class="hero" id="hero">
  <img class="hero__img" id="img" crossorigin="anonymous" src="https://picsum.photos/id/1018/1600/1000" alt="Green hills in soft light">
  <div class="hero__content"><h1 class="hero__title">Canopy</h1><p class="hero__note">Native forest<br>Since 2011</p></div>
</section>
<div class="seam" id="seam" aria-hidden="true"></div>
<section class="next">
  <p class="next__label">(01) Rewilding</p>
  <p class="next__text">We bring native forest back to hills cleared long ago: seed gathered nearby, planted by volunteers, then left to grow wild.</p>
  <ul class="projects">
    <li><img src="https://picsum.photos/id/1018/600/800" alt=""><p>Birch Hollow <span>2012</span></p></li>
    <li><img src="https://picsum.photos/id/1036/600/800" alt=""><p>Upper Loch <span>2014</span></p></li>
    <li><img src="https://picsum.photos/id/1039/600/800" alt=""><p>Rowan Ridge <span>2016</span></p></li>
    <li><img src="https://picsum.photos/id/1056/600/800" alt=""><p>Red Pine Glen <span>2018</span></p></li>
  </ul>
</section>

<script>
// Based on Codrops SeamTransitions, "Ink Bleed" (MIT), https://github.com/codrops/SeamTransitions
// The edge between the dark photo and the white page is drawn by a WebGL2 fragment shader.
// As the page scrolls up, the photograph "bleeds" down over the paper in branching lobes, like ink in wet paper.
const hero = document.getElementById('hero');
const img = document.getElementById('img');
const seamEl = document.getElementById('seam');
const clamp = (v, a, b) => Math.min(Math.max(v, a), b);
const ABOVE = 120;                                  // px the seam reaches up into the photo
const below = () => Math.round(innerHeight * 0.3);  // px it reaches down into the page
const VEIL = 0.3;                                   // must match .hero::after

const vertexSrc = `#version 300 es
uniform vec2 uSize; out vec2 vPx;
void main() {
  vec2 p = vec2(float((gl_VertexID << 1) & 2), float(gl_VertexID & 2));   // one triangle covers the canvas
  vPx = vec2(p.x, 1.0 - p.y) * uSize;
  gl_Position = vec4(p * 2.0 - 1.0, 0.0, 1.0);
}`;

const fragmentSrc = `#version 300 es
precision highp float;
uniform vec2 uSize; uniform float uEdge, uTravel, uProgress, uVelocity;
uniform sampler2D uHero; uniform vec4 uHeroBox; uniform vec3 uPaper;
in vec2 vPx; out vec4 outColor;

float hash(vec2 p) { p = fract(p * vec2(123.34, 456.21)); p += dot(p, p + 45.32); return fract(p.x * p.y); }
float noise(vec2 p) { vec2 i = floor(p), f = fract(p), u = f * f * (3.0 - 2.0 * f);
  return mix(mix(hash(i), hash(i + vec2(1, 0)), u.x), mix(hash(i + vec2(0, 1)), hash(i + vec2(1, 1)), u.x), u.y); }
float fbm(vec2 p) { float v = 0.0, a = 0.5; for (int i = 0; i < 5; i++) { v += a * noise(p); p = p * 2.03 + 17.1; a *= 0.5; } return v / 0.97; }

vec3 photo(vec2 px) { vec2 uv = clamp((px - uHeroBox.xy) / uHeroBox.zw, 0.0, 1.0); return texture(uHero, uv).rgb * ${(1 - VEIL).toFixed(3)}; }

void main() {
  vec2 px = vPx;
  if (uProgress <= 0.0) { outColor = vec4(0.0); return; }        // before the page moves: a plain edge
  float d = px.y - uEdge;                                        // below the hero edge: positive
  float down = uSize.y - uEdge, up = uEdge;                      // room below and above the edge
  // a warped noise field = lobes, a fine one = frayed edge, thin runs = paper fibres. g: how far the ink gets here
  vec2 q = (px + uTravel * vec2(0.08, 0.47)) / 300.0;
  vec2 w = vec2(fbm(q), fbm(q + vec2(5.2, 1.3)));
  float lobes = fbm(q * 1.2 + 2.2 * w);
  float fray = fbm(px / 24.0 + 3.0 * w);
  float runs = pow(fbm(vec2(px.x / 26.0, (px.y - uTravel * 0.16) / 140.0)), 3.0);
  float g = (lobes - 0.42) * 2.8 + (fray - 0.5) * 0.35 + runs * 0.9;
  // it spreads in the first third of the scroll, and further the faster the page moves
  float spread = smoothstep(0.0, 0.35, uProgress) + min(abs(uVelocity) / 3000.0, 0.35);
  float reach = g > 0.0 ? down * tanh(g * spread * 0.9) : -up * tanh(-g * spread * 0.5);
  float s = d - reach;                                           // negative = inside the ink
  float soft = max((0.8 + min(abs(uVelocity) * 0.004, 8.0)) * smoothstep(0.0, 0.03, uProgress), 0.001);
  float h = 1.0 - smoothstep(-soft, soft, s);
  float rim = 1.0 - smoothstep(0.0, 14.0, -s);                   // the ink pools darker at its edge
  vec3 dark = photo(px) * (1.0 - 0.45 * rim * step(0.0, d));
  // the page under the canvas = photo above the edge, paper below it, so only the difference is painted
  float page = step(px.y, uEdge);
  float a = abs(h - page);
  float near = 1.0 - step(1.0, abs(px.y - uEdge));
  outColor = mix(vec4(mix(dark, uPaper, page) * a, a), vec4(mix(uPaper, dark, h), 1.0), near);
}`;

let gl, program, canvas, tex, loc = {}, dpr = 1;
let uEdge = ABOVE, size = [1, 1], box = [0, 0, 1, 1];
const state = { travel: 0, progress: 0, velocity: 0 };

function compile(type, src) {
  const s = gl.createShader(type); gl.shaderSource(s, src); gl.compileShader(s);
  if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) throw new Error(gl.getShaderInfoLog(s));
  return s;
}
function resize() {
  const b = below(), h = hero.offsetHeight, w = seamEl.clientWidth;
  seamEl.style.setProperty('--above', ABOVE + 'px');
  seamEl.style.setProperty('--below', b + 'px');
  hero.style.setProperty('--above', ABOVE + 'px');
  hero.style.setProperty('--below', b + 'px');
  dpr = Math.min(1.5, devicePixelRatio || 1);
  size = [w, ABOVE + b];
  canvas.width = Math.round(size[0] * dpr); canvas.height = Math.round(size[1] * dpr);
  // where the photograph is drawn (object-fit: cover in a box hero + below tall), measured from the canvas top
  const bh = h + b, sc = Math.max(w / img.naturalWidth, bh / img.naturalHeight);
  const iw = img.naturalWidth * sc, ih = img.naturalHeight * sc;
  box = [(w - iw) / 2, (bh - ih) / 2 - (h - ABOVE), iw, ih];
  render();
}
function render() {
  gl.viewport(0, 0, canvas.width, canvas.height);
  gl.useProgram(program);
  const set = (n, v) => { const at = (loc[n] ??= gl.getUniformLocation(program, n)); if (at === null) return;
    typeof v === 'number' ? gl.uniform1f(at, v) : gl[`uniform${v.length}fv`](at, v); };
  set('uSize', size); set('uEdge', uEdge); set('uHeroBox', box); set('uPaper', [0.957, 0.945, 0.918]);
  set('uTravel', state.travel); set('uProgress', state.progress); set('uVelocity', state.velocity);
  gl.clearColor(0, 0, 0, 0); gl.clear(gl.COLOR_BUFFER_BIT); gl.drawArrays(gl.TRIANGLES, 0, 3);
}
function start() {
  canvas = document.createElement('canvas');
  gl = canvas.getContext('webgl2', { premultipliedAlpha: true, antialias: false });
  if (!gl) return;                                       // no WebGL 2: the page just keeps a plain edge
  seamEl.append(canvas);
  program = gl.createProgram();
  gl.attachShader(program, compile(gl.VERTEX_SHADER, vertexSrc));
  gl.attachShader(program, compile(gl.FRAGMENT_SHADER, fragmentSrc));
  gl.linkProgram(program);
  gl.useProgram(program);
  tex = gl.createTexture();
  gl.activeTexture(gl.TEXTURE0); gl.bindTexture(gl.TEXTURE_2D, tex);
  gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, img);
  gl.generateMipmap(gl.TEXTURE_2D);
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR);
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  gl.uniform1i(gl.getUniformLocation(program, 'uHero'), 0);
  resize();
  addEventListener('resize', resize);

  // every frame: how far the hero's edge has come up the screen, and how fast the page moves
  let lastY = scrollY, lastT = performance.now();
  (function frame(now) {
    const dt = Math.max((now - lastT) / 1000, 1 / 120);
    const speed = (scrollY - lastY) / dt;
    lastY = scrollY; lastT = now;
    state.velocity += (speed - state.velocity) * 0.3;
    if (Math.abs(state.velocity) < 2) state.velocity = 0;
    state.travel = scrollY + innerHeight - hero.offsetHeight;
    state.progress = clamp(state.travel / innerHeight, 0, 1);
    const top = hero.offsetHeight - ABOVE - scrollY;
    if (top < innerHeight && top + size[1] > 0) render();   // draw only while the seam is on screen
    requestAnimationFrame(frame);
  })(performance.now());
}
img.complete && img.naturalWidth ? start() : img.addEventListener('load', start);
</script>
</body>
</html>

Похожие