Капсула из жидкого металла

Кнопка входа из жидкого металла. Нажмите, и капсула вытягивает ртутную перемычку, которая рвётся и разбрасывает капли под силой тяжести, а вращающийся блик, отстающий отсвет и тёплая с холодной подсветка краёв следуют за курсором.

Поводите мышью над металлом, нажмите Sign in, введите что угодно и дважды нажмите Enter.

Скачать

Что можно поменять

Поменяйте число, сохраните файл и обновите страницу, разница будет видна сразу.

spring{ k: 55, damping: 11 }

Как открываются и закрываются половины. Меньше затухание, больше отскок.

DROPS7

Сколько капель вылетает, когда рвётся перемычка.

GRAV900

Как быстро падают капли, в пикселях на секунду в квадрате.

SHEEN37.5

Как быстро полоса света поворачивается по металлу, в градусах в секунду.

LAG0.15

На сколько секунд второй блик отстаёт от курсора.

Как поставить на свой сайт

Кнопка входа на лендинге, в листе ожидания или на любом тёмном первом экране, где одна кнопка должна выглядеть дорого.

Комментарии в коде на английском, так файл понятен любому разработчику.

  1. CSS

    Вставьте в свой файл стилей или в тег <style> внутри <head>.

    @property --sheenA { syntax: '<angle>'; inherits: false; initial-value: 0deg; }
    .lm-form { --paper: #F3F5F8; --smoke: #7A8290; --emerald: #34D399; }
    .lm-form * { box-sizing: border-box; }
    .lm-stack { position: relative; width: min(340px, 92vw); height: 210px; }
    .lm-liquid, .lm-splash { position: absolute; inset: 0; width: 100%; height: 100%; overflow: visible; pointer-events: none; }
    .lm-splash { z-index: 4; }
    
    /* half: dark field underneath, metal and its lights on top, they melt away as it opens */
    .lm-half { position: absolute; overflow: hidden; background: linear-gradient(180deg, #222731 0%, #1B1F27 100%); }
    .lm-half .metal, .lm-half .sheen, .lm-half .spec, .lm-half .spec2, .lm-half .warm, .lm-half .cool, .lm-half .tint {
      position: absolute; inset: 0; border-radius: inherit; pointer-events: none; }
    .lm-half .metal { background-color: #CDD2D9;
      background-image: repeating-linear-gradient(0deg, rgba(255,255,255,.022) 0 1px, rgba(0,0,0,0) 1px 2px),
                        linear-gradient(180deg, #EDF0F4 0%, #D6DBE1 38%, #C5CBD3 62%, #DADEE4 100%);
      background-size: 100% 58px, 100% 58px; background-repeat: repeat, no-repeat; }
    #bot .metal { background-position: 0 -29px, 0 -29px; }
    .lm-half .sheen { background: linear-gradient(var(--sheenA), rgba(255,255,255,0) 36%, rgba(255,255,255,.5) 50%, rgba(255,255,255,0) 64%); mix-blend-mode: soft-light; }
    .lm-half .warm { mix-blend-mode: color-dodge; }
    .lm-half .cool { mix-blend-mode: soft-light; }
    .lm-half .tint { background: rgba(52,211,153,.11); mix-blend-mode: color; opacity: 0; transition: opacity .3s ease-out; }
    [data-state="done"] .lm-half .tint { opacity: .8; }
    
    .lm-half label { position: absolute; left: 18px; top: 10px; font-size: 12px; color: var(--smoke); pointer-events: none; }
    .lm-half input { position: absolute; left: 18px; right: 18px; bottom: 9px; border: 0; outline: 0; background: none;
      color: var(--paper); font: 500 17px/1.2 system-ui, sans-serif; caret-color: var(--emerald); }
    .lm-half input::placeholder { color: #4A515C; }
    
    /* capsule face, this is the button you actually press */
    .lm-cap { position: absolute; display: flex; align-items: center; justify-content: center; gap: 8px;
      border: 0; background: none; cursor: pointer; font: 600 17px/1 system-ui, sans-serif; letter-spacing: -.015em;
      color: #1A1D23; text-shadow: 0 1px 0 rgba(255,255,255,.55); z-index: 3; }
    .lm-cap:focus-visible { outline: 2px solid var(--emerald); outline-offset: 4px; border-radius: 30px; }
    .lm-cap svg { width: 18px; height: 18px; }
    .lm-cap path { stroke-dasharray: 18; stroke-dashoffset: 18; transition: stroke-dashoffset .35s ease-out; }
    [data-state="done"] .lm-cap path { stroke-dashoffset: 0; }
    
    .lm-seam { position: absolute; height: 2px; border-radius: 2px; pointer-events: none; opacity: 0; box-shadow: 0 0 12px 2px rgba(210,236,255,.5); }
    .lm-sr { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); }
    .lm-hint { margin-top: 22px; text-align: center; font: 13px/1.4 system-ui, sans-serif; color: #5C6472; }
    
    @media (prefers-reduced-motion: reduce) {
      .lm-half .sheen { display: none; }
    }
  2. HTML

    Поставьте в то место страницы, где должен быть эффект.

    <form id="form" class="lm-form" novalidate>
      <div class="lm-stack" id="stack" data-state="idle">
        <svg class="lm-liquid" aria-hidden="true">
          <defs>
            <linearGradient id="mg" x1="0" y1="0" x2="0" y2="1">
              <stop offset="0" stop-color="#EDF0F4"/><stop offset="38%" stop-color="#D6DBE1"/>
              <stop offset="62%" stop-color="#C5CBD3"/><stop offset="100%" stop-color="#DADEE4"/>
            </linearGradient>
          </defs>
          <path id="bridge" fill="url(#mg)"/>
        </svg>
    
        <div class="lm-half" id="top">
          <div class="metal"></div><div class="tint"></div><div class="sheen"></div><div class="warm"></div><div class="cool"></div><div class="spec"></div><div class="spec2"></div>
          <label for="email">Email</label>
          <input id="email" type="email" autocomplete="username" placeholder="you@example.com">
        </div>
        <div class="lm-half" id="bot">
          <div class="metal"></div><div class="tint"></div><div class="sheen"></div><div class="warm"></div><div class="cool"></div><div class="spec"></div><div class="spec2"></div>
          <label for="pass">Password</label>
          <input id="pass" type="password" autocomplete="current-password" placeholder="••••••••">
        </div>
    
        <svg class="lm-splash" aria-hidden="true">
          <defs>
            <radialGradient id="dg" cx="35%" cy="30%" r="75%">
              <stop offset="0" stop-color="#FFFFFF"/><stop offset="35%" stop-color="#E4E8EE"/><stop offset="100%" stop-color="#9AA2AD"/>
            </radialGradient>
          </defs>
          <g id="drops" fill="url(#dg)"></g>
        </svg>
    
        <div class="lm-seam" id="seam"></div>
        <button type="button" class="lm-cap" id="cap">
          <svg viewBox="0 0 18 18" id="check" hidden><path d="M3.5 9.6 L7.3 13.2 L14.5 5.2" fill="none" stroke="#0E7A55" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"/></svg>
          <span id="capText">Sign in</span>
        </button>
        <button type="submit" class="lm-sr">Submit</button>
      </div>
      <p class="lm-hint">Move the mouse over the metal, press Sign in, type anything and hit Enter.</p>
    </form>
  3. JavaScript

    Вставьте перед закрывающим тегом </body>, внутри <script></script>.

    // ── the same numbers as in the video
    const spring = { k: 55, damping: 11 };
    const DROPS = 7, GRAV = 900;
    const NECK = 0.34, PULL = 26;
    const SHEEN = 37.5, LAG = 0.15;
    const PW = 240, PH = 58, FW = 320, FH = 64, GAP = 12;
    
    const $ = id => document.getElementById(id);
    const clamp = (x, a = 0, b = 1) => Math.min(b, Math.max(a, x));
    const lerp = (a, b, k) => a + (b - a) * k;
    const reduce = matchMedia('(prefers-reduced-motion: reduce)').matches;
    
    // topHalf/botHalf, not top/bot, because window.top belongs to the browser
    const stack = $('stack'), topHalf = $('top'), botHalf = $('bot'), cap = $('cap');
    const email = $('email'), pass = $('pass');
    const sheens = stack.querySelectorAll('.sheen');
    
    let CX = 170, CY = 105;
    const measure = () => { CX = stack.clientWidth / 2; CY = stack.clientHeight / 2; };
    new ResizeObserver(measure).observe(stack); measure();
    
    let g = 0, v = 0, target = 0, pressed = 0;       // g is 0 for the capsule, 1 for two fields
    let last = performance.now(), snapped = false, loadingSince = 0;
    
    // the pointer, and a copy of it that trails behind
    const light = { x: CX + 60, y: CY - 30, x2: CX + 60, y2: CY - 30 };
    stack.addEventListener('pointermove', e => { const r = stack.getBoundingClientRect(); light.x = e.clientX - r.left; light.y = e.clientY - r.top; });
    stack.addEventListener('pointerleave', () => { light.x = CX + 60; light.y = CY - 30; });
    
    const patchAt = q => lerp(PW, PW * NECK, clamp(q * 1.4));
    const waistAt = q => patchAt(q) * Math.pow(clamp(1 - q / .80), 1.6);
    
    // ── liquid metal neck between the edges of the halves
    function bridge(q, yTop, yBot) {
      const el = $('bridge'), gh = yBot - yTop, wPatch = patchAt(q), waist = waistAt(q);
      if (gh <= .5 || waist <= .6) { el.setAttribute('d', ''); return 0; }
      const half = wPatch / 2, hw = waist / 2, ym = (yTop + yBot) / 2, c = gh * .34;
      el.setAttribute('d',
        `M ${CX - half} ${yTop} C ${CX - half} ${yTop + c} ${CX - hw} ${ym - c} ${CX - hw} ${ym}` +
        ` C ${CX - hw} ${ym + c} ${CX - half} ${yBot - c} ${CX - half} ${yBot}` +
        ` L ${CX + half} ${yBot} C ${CX + half} ${yBot - c} ${CX + hw} ${ym + c} ${CX + hw} ${ym}` +
        ` C ${CX + hw} ${ym - c} ${CX + half} ${yTop + c} ${CX + half} ${yTop} Z`);
      return waist;
    }
    
    // ── drops: thrown at their own angle, then only gravity. mulberry32 with a fixed seed gives the same splash as the video
    const rng = seed => () => { seed = seed + 0x6D2B79F5 | 0; let t = Math.imul(seed ^ seed >>> 15, 1 | seed); t = t + Math.imul(t ^ t >>> 7, 61 | t) ^ t; return ((t ^ t >>> 14) >>> 0) / 4294967296; };
    let drops = [];
    function throwDrops(n, power, seed) {
      if (reduce) return;
      const r = rng(seed), born = performance.now() / 1000;
      for (let i = 0; i < n; i++) {
        const th = r() * Math.PI * 2, v0 = (130 + r() * 130) * power;
        drops.push({ born, x0: CX + (r() - .5) * PW * .3, y0: CY, vx: v0 * Math.cos(th), vy: v0 * Math.sin(th) - v0 * .6, size: 3.6 + r() * 3.4, x: 0, y: 0 });
      }
    }
    function splash(n) { if (snapped) return; snapped = true; throwDrops(n, 1, 4242); }   // fires once per snap
    function merge() { snapped = false; throwDrops(5, .65, 4243); }
    
    function drawDrops(now) {
      const LIFE = .6;
      drops = drops.filter(d => now - d.born < LIFE);
      for (const d of drops) {
        const t = now - d.born;
        d.x = d.x0 + d.vx * t;
        d.y = d.y0 + (d.vy + GRAV*t/2) * t;
      }
      let out = '';
      for (const d of drops) {
        const t = now - d.born, fade = 1 - t / LIFE;
        for (const [lag, alpha, sc] of [[.02, .4, .7], [0, 1, 1]]) {           // a dimmer tail 20 ms behind
          const s = t - lag; if (s < 0) continue;
          const x = d.x0 + d.vx * s, y = d.y0 + (d.vy + GRAV * s / 2) * s, vy = d.vy + GRAV * s;
          const speed = Math.hypot(d.vx, vy), ang = Math.atan2(vy, d.vx) * 180 / Math.PI;
          const rx = d.size * (1 + speed / 1100) * sc * (.5 + .5 * fade), ry = d.size * .86 * sc * (.5 + .5 * fade);
          out += `<ellipse cx="${x.toFixed(1)}" cy="${y.toFixed(1)}" rx="${rx.toFixed(2)}" ry="${ry.toFixed(2)}" transform="rotate(${ang.toFixed(1)} ${x.toFixed(1)} ${y.toFixed(1)})" opacity="${(alpha * fade).toFixed(2)}"/>`;
        }
      }
      $('drops').innerHTML = out;
    }
    
    function frame(nowMs) {
      const dt = Math.min((nowMs - last) / 1000, 1 / 30); last = nowMs;
      const now = nowMs / 1000;
      // a real spring with mass 1, acceleration = k * (target - position) - damping * velocity
      v += (spring.k * (target - g) - spring.damping * v) * dt;
      g = clamp(g + v * dt, -.02, 1.05);
      pressed += ((stack.classList.contains('lm-pressed') ? 1 : 0) - pressed) * Math.min(1, dt * 30);
    
      const m = clamp((g - .8) / .18);                         // metal stays while the neck is stretching
      const w = lerp(PW, FW, g), hTop = lerp(PH / 2, FH, g);
      const pull = PULL * Math.sin(Math.PI * clamp(g / .8));
      const cTop = lerp(CY - PH / 4, CY - FH / 2 - GAP / 2, g) - pull / 2;
      const cBot = lerp(CY + PH / 4, CY + FH / 2 + GAP / 2, g) + pull / 2;
      const rOut = clamp(lerp(PH / 2, 18, g), 16, 29), rIn = clamp(lerp(0, 18, g), 0, 18);
      const sc = 1 - .03 * pressed;
    
      // lights: the second highlight follows the first with a delay of about LAG seconds
      const k = 1 - Math.exp(-dt / LAG);
      light.x2 += (light.x - light.x2) * k; light.y2 += (light.y - light.y2) * k;
      const a = `${(now * SHEEN) % 360}deg`;
      for (const sheen of sheens)
        sheen.style.setProperty('--sheenA', a);
    
      for (const [el, cy, isTop] of [[topHalf, cTop, true], [botHalf, cBot, false]]) {
        const left = CX - w / 2, top = cy - hTop / 2;
        el.style.left = left + 'px'; el.style.width = w + 'px';
        el.style.top = top + 'px'; el.style.height = hTop + 'px';
        el.style.borderRadius = isTop ? `${rOut}px ${rOut}px ${rIn}px ${rIn}px` : `${rIn}px ${rIn}px ${rOut}px ${rOut}px`;
        el.style.transform = `scale(${sc})`;
        el.style.transformOrigin = isTop ? '50% 100%' : '50% 0%';
        const lx = light.x - left, ly = light.y - top, lx2 = light.x2 - left, ly2 = light.y2 - top, metalA = 1 - m;
        el.querySelector('.metal').style.opacity = metalA;
        el.querySelector('.sheen').style.opacity = metalA;
        el.querySelector('.spec').style.background = `radial-gradient(150px 70px at ${lx}px ${ly}px, rgba(255,255,255,.55), rgba(255,255,255,0) 70%)`;
        el.querySelector('.spec').style.opacity = metalA * .9;
        el.querySelector('.spec2').style.background = `radial-gradient(90px 44px at ${lx2}px ${ly2}px, rgba(255,255,255,.4), rgba(255,255,255,0) 70%)`;
        el.querySelector('.spec2').style.opacity = metalA * .8;
        el.querySelector('.warm').style.background = `radial-gradient(120px 60px at ${lx}px ${ly}px, rgba(255,178,107,.2), rgba(255,178,107,0) 70%)`;
        el.querySelector('.cool').style.background = `radial-gradient(120px 60px at ${w - lx}px ${ly}px, rgba(107,207,255,.18), rgba(107,207,255,0) 70%)`;
        el.querySelector('.warm').style.opacity = el.querySelector('.cool').style.opacity = metalA;
        el.style.boxShadow = `0 0 0 1px rgba(255,255,255,${.10 * m}), inset 0 1px 0 rgba(255,255,255,${.7 * (1 - m) + .05 * m}), 0 18px 34px -14px rgba(3,6,10,.8)`;
      }
    
      const yTop = cTop + hTop / 2, yBot = cBot - hTop / 2;
      if (m < .98) bridge(g, yTop, yBot); else $('bridge').setAttribute('d', '');
      const waist = waistAt(g) > .6 ? waistAt(g) : 0;
      // snaps when the waist hits zero
      if (waist <= 0) splash(DROPS);
      else if (snapped) merge();                           // melts back, a smaller splash
      drawDrops(now);
    
      // capsule face and fields are never shown together
      const capA = clamp(1 - g * 14), fieldA = clamp((g - .82) / .14);
      cap.style.opacity = capA; cap.style.pointerEvents = capA > .5 ? 'auto' : 'none';
      cap.style.left = (CX - w / 2) + 'px'; cap.style.top = (CY - 11) + 'px'; cap.style.width = w + 'px';
      cap.style.transform = `scale(${sc})`;
      for (const el of [topHalf, botHalf]) {
        el.querySelector('label').style.opacity = fieldA;
        const inp = el.querySelector('input');
        inp.style.opacity = fieldA; inp.style.pointerEvents = fieldA > .5 ? 'auto' : 'none';
      }
    
      // while loading, a light runs along the seam
      const seam = $('seam'), loading = stack.dataset.state === 'loading', sw = (loading ? PW : w) - 30;
      seam.style.width = sw + 'px'; seam.style.left = (CX - sw / 2) + 'px'; seam.style.top = (CY - 1) + 'px';
      if (loading) {
        const q = ((now - loadingSince) * 1.4) % 1, x = q * 100;
        seam.style.opacity = .95;
        seam.style.background = `linear-gradient(90deg, rgba(232,244,255,0) ${Math.max(0, x - 35)}%, #EAF6FF ${x}%, rgba(232,244,255,0) ${Math.min(100, x + 35)}%)`;
      } else seam.style.opacity = 0;
    
      requestAnimationFrame(frame);
    }
    requestAnimationFrame(frame);
    
    // ── states
    function open() { stack.dataset.state = 'open'; target = 1; setTimeout(() => email.focus(), 260); }
    function close() { stack.dataset.state = 'idle'; target = 0; email.blur(); pass.blur(); }
    
    cap.addEventListener('pointerdown', () => stack.classList.add('lm-pressed'));
    addEventListener('pointerup', () => stack.classList.remove('lm-pressed'));
    cap.addEventListener('click', () => {
      if (stack.dataset.state === 'done') { $('check').hidden = true; $('capText').textContent = 'Sign in'; email.value = pass.value = ''; close(); }
      else if (target === 0) open();
    });
    email.addEventListener('keydown', e => { if (e.key === 'Enter') { e.preventDefault(); pass.focus(); } });
    document.addEventListener('keydown', e => { if (e.key === 'Escape' && target === 1) close(); });
    
    $('form').addEventListener('submit', e => {
      e.preventDefault();
      stack.dataset.state = 'loading'; loadingSince = performance.now() / 1000; target = 0; email.blur(); pass.blur();
      setTimeout(() => {                                   // a real server request goes here
        stack.dataset.state = 'done';
        $('capText').textContent = 'Signed in'; $('check').hidden = false;
      }, 1100);
    });

Подключение к серверу

Замените таймер у a real server request goes here своим fetch() к адресу входа и показывайте Signed in только после ответа.

Полезно знать

Tilda, Webflow, WordPress

Нажмите «Скопировать весь код» вверху и вставьте его в один HTML-блок.

Tilda

Добавить блок, Другое, T123 HTML-код. Вставьте и сохраните. Проверяйте на опубликованной странице, в редакторе скрипты не запускаются.

Webflow

Панель Add, Embed. Вставьте и нажмите Save & Close. Свой код работает на опубликованном сайте.

WordPress

Добавить блок, Произвольный HTML. Вставьте и нажмите «Обновить».

Ещё в разделе «Вход и формы»

Все
Скопировано