Вход с кометой

Форма входа, где свет даёт крошечная комета. Она летит к полю, по которому кликнули, следует за вводом и кружит в ожидании. Неверный пароль тускнит её, делает розовой, и она отскакивает от кнопки. Верный заставляет её отступить, нырнуть в Sign in и обежать всю форму, пока по небу зажигаются звёзды.

Кликните в поле Email и печатайте. Сначала попробуйте неверный пароль, потом введите stardust и нажмите Sign in.

Скачать

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

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

STIFF0.06

Как сильно комета тянется к цели, больше значит быстрее.

DAMP0.82

Как долго она раскачивается после поворота, ближе к 1, сильнее.

ORBIT14

Размер круга, который она описывает в ожидании, 0 выключает кружение.

TAIL36

Длина хвоста в шагах по 1/60 секунды.

LAP3

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

DIM[1, .4, .15, .3, .6, .85, 1]

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

STARS90

Сколько звёзд, 0 их выключает.

DEMO_PASSWORD'stardust'

Единственный верный ответ в демо. Удалите его, когда пароль начнёт проверять ваш сервер, см. шаг 4.

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

Страница входа портфолио, студии или космического продукта, везде, где первый экран может позволить себе немного движения.

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

  1. CSS

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

    /* Comet Login by @codinvisual · t.me/CodinVisual · free for your own site, don't resell this file */
    /* a soft dark around the form, the comet carries a cold light; --r grows and shrinks with its glow */
    .night { position: fixed; inset: 0; z-index: 5; pointer-events: none; transition: opacity .6s ease;
      background: radial-gradient(circle at var(--x, -200px) var(--y, 30%), rgba(140,203,255,.08) 0, rgba(5,7,12,.22) calc(var(--r, 260px) * .5), rgba(5,7,12,.52) var(--r, 260px)); }
    .night.day { opacity: .3; }
    .sky { position: fixed; inset: 0; z-index: 6; width: 100%; height: 100%; pointer-events: none; mix-blend-mode: screen; }   /* stars, tail and sparks add light */
    
    .login { position: relative; box-sizing: border-box; width: min(360px, 92vw); display: grid; gap: 16px; margin: 0; }
    
    /* the edge of a field turns icy as the comet gets close, --rim goes from 0 to 1 */
    .field { position: relative; height: 52px; border-radius: 14px; background: #10141B; overflow: hidden;
      box-shadow: inset 0 0 0 1.2px rgba(160,210,255, calc(.1 + .45 * var(--rim, 0))), 0 0 calc(18px * var(--rim, 0)) rgba(120,185,255, calc(.18 * var(--rim, 0))); }
    .field:focus-within { box-shadow: inset 0 0 0 1.6px rgba(140,203,255,.9), 0 0 0 4px rgba(140,203,255,.16); }
    .field input { position: relative; box-sizing: border-box; width: 100%; height: 100%; padding: 0 52px 0 18px; border: 0; outline: 0; background: transparent;
      font: 500 16px system-ui, sans-serif; color: #EEF4FA; caret-color: #8CCBFF; transition: opacity .35s ease; }
    .field input::placeholder { color: rgba(180,195,215,.45); }
    /* a wrong password: a rose edge comes over the field and the button for a moment, then fades */
    .field::after, .send::after { content: ""; position: absolute; inset: 0; border-radius: inherit; pointer-events: none; opacity: 0; transition: opacity .25s ease; }
    .field::after { box-shadow: inset 0 0 0 1.6px rgba(255,143,160,.95), inset 0 0 14px rgba(255,143,160,.16); }
    .send::after { box-shadow: inset 0 0 0 1.6px rgba(255,143,160,.9); }
    .field.bad::after, .send.bad::after { opacity: 1; }
    
    /* password: the real input stays type="password", what you see is drawn next to it */
    .pass input { color: transparent; caret-color: transparent; }
    .mirror { position: absolute; left: 18px; right: 52px; top: 0; bottom: 0; pointer-events: none; overflow: hidden; font: 500 16px system-ui, sans-serif; transition: opacity .35s ease; }
    /* when the comet leaves, what was typed fades out */
    .login.clear input, .login.clear .mirror { opacity: 0; }
    .dots, .text { position: absolute; left: 0; top: 0; bottom: 0; display: flex; align-items: center; white-space: pre;
      transition: opacity .3s cubic-bezier(.77, 0, .175, 1), filter .3s cubic-bezier(.77, 0, .175, 1); }
    .dots i { flex: none; width: 14px; height: 14px; display: grid; place-items: center; }
    .dots i::after { content: ""; width: 7px; height: 7px; border-radius: 50%; background: #EEF4FA; }
    .text { opacity: 0; filter: blur(3px); letter-spacing: .5px; }
    .text b { font-weight: 500; }
    .show .dots { opacity: 0; filter: blur(3px); }
    .show .text { opacity: 1; filter: none; }
    .dots i.new, .text b.new { animation: flash .5s cubic-bezier(.23, 1, .32, 1); }
    @keyframes flash { from { filter: drop-shadow(0 0 5px #A8D8FF) brightness(1.7); } }
    /* the wrong dots turn rose, sink out of the field one after another and fade */
    .pass.drop .dots i, .pass.drop .text b { animation: drop .45s cubic-bezier(.45, 0, .55, 1) calc(var(--i, 0) * 40ms) forwards; }
    .pass.drop .dots i::after { animation: rose .15s ease forwards; }
    .pass.drop .text b { color: #FF8FA0; }
    @keyframes drop { to { translate: 0 16px; opacity: 0; } }
    @keyframes rose { to { background: #FF8FA0; } }
    .pass.drop input::placeholder { color: transparent; }
    .caret { position: absolute; left: 0; top: 16px; width: 2px; height: 20px; background: #8CCBFF; opacity: 0; }
    .pass:focus-within .caret { opacity: 1; animation: blink 1s steps(1) infinite; }
    @keyframes blink { 50% { opacity: 0; } }
    
    .eye { position: absolute; right: 8px; top: 8px; width: 36px; height: 36px; padding: 0; border: 0; border-radius: 10px; background: transparent;
      display: grid; place-items: center; cursor: pointer; color: rgba(215,225,238,.55); transition: color .2s ease, transform .16s ease-out; }
    .eye:active { transform: scale(.94); }
    .eye:focus-visible { outline: 2px solid #8CCBFF; outline-offset: 1px; }
    .eye svg { width: 22px; height: 22px; fill: none; stroke: currentColor; stroke-width: 1.7; stroke-linecap: round; stroke-linejoin: round; }
    .eye .slash { stroke-dasharray: 26; stroke-dashoffset: 0; transition: stroke-dashoffset .25s cubic-bezier(.23, 1, .32, 1); }
    .show .eye { color: #8CCBFF; }
    .show .eye .slash { stroke-dashoffset: 26; }
    
    .note { position: absolute; left: 4px; top: 128px; margin: 0; font: 600 13px system-ui, sans-serif; color: #FF8FA0; opacity: 0; transform: translateY(-4px);
      transition: opacity .2s ease-out, transform .2s ease-out; pointer-events: none; }
    .note.on { opacity: 1; transform: none; }
    
    /* the button fills with light from the point where the comet hit it */
    .send { position: relative; height: 54px; margin-top: 10px; border: 0; border-radius: 27px; background: #161B24; box-shadow: inset 0 0 0 1.2px rgba(215,230,255,.10);
      color: #E6EDF5; font: 600 16px system-ui, sans-serif; cursor: pointer; overflow: hidden; transition: transform .16s ease-out; }
    .send:active { transform: scale(.97); }
    .send:focus-visible { outline: 2px solid #8CCBFF; outline-offset: 3px; }
    .send::before { content: ""; position: absolute; inset: 0; background: linear-gradient(#CFEAFF, #86C4FF);
      clip-path: circle(0 at var(--hx, 50%) 50%); transition: clip-path .5s cubic-bezier(.23, 1, .32, 1); }
    .send.done::before { clip-path: circle(150% at var(--hx, 50%) 50%); }
    .send.still::before, .send.still span { transition: none; }
    /* the comet bounced off: the button shudders once */
    @media (prefers-reduced-motion: no-preference) {
      .send.bad { animation: nope .4s cubic-bezier(.36, .07, .19, .97); }
    }
    @keyframes nope { 15% { translate: -7px 0; } 40% { translate: 6px 0; } 65% { translate: -3px 0; } 85% { translate: 1px 0; } }
    .send span { position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; gap: 8px;
      transition: opacity .3s ease-out, filter .3s ease-out, transform .3s cubic-bezier(.23, 1, .32, 1); }
    .send .ok { color: #07182C; opacity: 0; filter: blur(3px); transform: translateY(6px); }
    .send .ok svg { width: 18px; height: 18px; fill: none; stroke: currentColor; stroke-width: 2.4; stroke-linecap: round; stroke-linejoin: round; }
    .send.done .go { opacity: 0; filter: blur(3px); transform: translateY(-6px); }
    .send.done .ok { opacity: 1; filter: none; transform: none; transition-delay: .16s; }
    @media (hover: hover) and (pointer: fine) {
      .send:not(.done):hover { background: #1C2230; }
    }
    
    /* the comet's head: the glow breathes, after a wrong password the rose layers come over the icy ones and go; the script sets the four opacities */
    .comet { position: fixed; left: 0; top: 0; z-index: 7; width: 110px; height: 110px; margin: -55px 0 0 -55px; pointer-events: none; }
    .comet i { position: absolute; border-radius: 50%; }
    .comet .glow { inset: 0; opacity: var(--glow, 1);
      background: radial-gradient(circle, rgba(170,215,255,.7), rgba(120,185,255,.22) 22%, rgba(120,185,255,.06) 42%, rgba(120,185,255,0) 62%); }
    .comet .glow.hot { opacity: var(--hot-glow, 0);
      background: radial-gradient(circle, rgba(255,170,185,.7), rgba(255,110,135,.22) 22%, rgba(255,110,135,.06) 42%, rgba(255,110,135,0) 62%); }
    .comet .core { left: 50%; top: 50%; width: 9px; height: 9px; margin: -4.5px 0 0 -4.5px; background: #F4FAFF; opacity: var(--core, 1);
      box-shadow: 0 0 6px 2px rgba(200,230,255,.9), 0 0 16px 5px rgba(140,203,255,.55); }
    .comet .core.hot { background: #FFF1F3; opacity: var(--hot-core, 0); box-shadow: 0 0 6px 2px rgba(255,220,228,.9), 0 0 16px 5px rgba(255,143,160,.55); }
  2. HTML

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

    <div class="night" aria-hidden="true"></div>
    <canvas class="sky" aria-hidden="true"></canvas>
    
    <form class="login" novalidate>
      <div class="field mail">
        <input id="email" type="email" name="email" placeholder="Email" autocomplete="username" aria-label="Email">
      </div>
      <div class="field pass">
        <input id="pass" type="password" name="password" placeholder="Password" autocomplete="current-password" aria-label="Password">
        <span class="mirror" aria-hidden="true"><span class="dots"></span><span class="text"></span><i class="caret"></i></span>
        <button class="eye" type="button" aria-label="Show password" aria-pressed="false">
          <svg viewBox="0 0 24 24"><path d="M1.5 12S5.5 4.5 12 4.5 22.5 12 22.5 12 18.5 19.5 12 19.5 1.5 12 1.5 12Z"/><circle cx="12" cy="12" r="3.2"/><path class="slash" d="M3.5 20.5 20.5 3.5"/></svg>
        </button>
      </div>
      <p class="note" aria-live="polite"></p>
      <button class="send" type="submit">
        <span class="go">Sign in</span>
        <span class="ok"><svg viewBox="0 0 24 24"><path d="M5 12.5l4.5 4.5L19 7.5"/></svg>You're in</span>
      </button>
    </form>
    
    <div class="comet" aria-hidden="true"><i class="glow"></i><i class="glow hot"></i><i class="core"></i><i class="core hot"></i></div>
  3. JavaScript

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

    // Comet Login by @codinvisual · t.me/CodinVisual · free for your own site, don't resell this file
    const STIFF = 0.06, DAMP = 0.82, ORBIT = 14;
    const SPIN = 5.7, TAIL = 36;               // SPIN is how fast it circles, in radians a second
    const LAP = 3;                             // after You're in it circles the whole form, this fast
    // after a wrong password the light follows DIM, one number per 0.15 s, blended in between
    const DIM = [1, .4, .15, .3, .6, .85, 1];
    const STARS = 90;
    const DEMO_PASSWORD = 'stardust';          // the only right answer in this file, delete it once your server checks
    
    const $ = s => document.querySelector(s);
    const form = $('.login'), email = $('#email'), pass = $('#pass'), eye = $('.eye'), send = $('.send'), note = $('.note');
    const mailField = email.parentElement, passField = pass.parentElement;
    const comet = $('.comet'), night = $('.night'), dots = $('.dots'), text = $('.text'), caret = $('.caret');
    const sky = $('.sky'), g = sky.getContext('2d');
    const reduce = matchMedia('(prefers-reduced-motion: reduce)').matches;
    const wait = ms => new Promise(r => setTimeout(r, ms));
    const clamp = (v, a = 0, b = 1) => Math.min(b, Math.max(a, v));
    const pen = document.createElement('canvas').getContext('2d');
    pen.font = '500 16px system-ui, sans-serif';
    
    // where the comet goes for each element: just above a field, into the middle of a button
    function at(el) {
      const r = el.getBoundingClientRect();
      if (el === email || el === pass) return { x: r.left + 22, y: r.top - 4 };
      return { x: r.left + r.width / 2, y: r.top + r.height / 2 };
    }
    // while you type it follows the last character, through the password it flies inside the field
    function caretGoal(input) {
      const r = input.getBoundingClientRect(), v = input.value;
      if (input === email) return { x: r.left + 24 + Math.min(pen.measureText(v).width, r.width - 70), y: r.top - 4 };
      const w = passField.classList.contains('show') ? pen.measureText(v).width + v.length * .5 : v.length * 14 - 7;
      return { x: r.left + 18 + Math.min(Math.max(w, 6), r.width - 70), y: r.top + r.height / 2 };
    }
    
    // it starts at the email field and already circles, so it is lit and moving from the first frame
    let { x, y } = at(email), vx = 0, vy = 0;
    let goal = { x, y }, idle = 1, dimAt = -1e4;
    let rx = ORBIT, ry = ORBIT / 2, spin = SPIN;      // the circle it draws around its goal
    let day = false, dawn = 0, strike = null;
    let last = performance.now(), acc = 0, dpr = 1;
    const tail = [], sparks = [], rings = [];
    // a new goal; wide is the two radii of a big circle, without it the comet draws its small one
    const aim = (p, wide) => { goal = p; idle = 0; rx = wide ? wide.x : ORBIT; ry = wide ? wide.y : ORBIT / 2; spin = wide ? LAP : SPIN; };
    const daylight = on => { day = on; night.classList.toggle('day', on); };
    function size() {
      dpr = Math.min(2, devicePixelRatio || 1);
      sky.width = innerWidth * dpr; sky.height = innerHeight * dpr;
    }
    addEventListener('resize', size); size();
    
    // how bright it is; a frame can start a little before the wrong answer came, so s < 0 counts as full light
    function light(now) {
      const s = (now - dimAt) / 150, i = Math.floor(s);
      if (reduce || s < 0 || i >= DIM.length - 1) return 1;
      return DIM[i] + (DIM[i + 1] - DIM[i]) * (s - i);
    }
    // how rose it is: comes in over .15 s, holds while the light fades and comes back, goes over .3 s
    const heat = now => { const s = (now - dimAt) / 1000; return s < 0 ? 0 : clamp(s / .15) * clamp((1.05 - s) / .3); };
    const stars = Array.from({ length: STARS }, () => ({ x: Math.random(), y: Math.random(), r: .6 + .8 * Math.random(), f: .683 * (3 + Math.floor(4 * Math.random())), p: 7 * Math.random() }));
    
    (function fly(now = performance.now()) {
      acc += Math.min(100, now - last); last = now;
      for (; acc >= 1000 / 60; acc -= 1000 / 60) {
        if (!reduce) idle += 1 / 60;          // with reduced motion idle stays 0, so it never circles
        const grow = clamp(idle * 2 - .6);
        const ox = Math.cos(idle * spin) * rx * grow;
        const oy = Math.sin(idle * spin) * ry * grow;
        vx = (vx + (goal.x + ox - x) * STIFF) * DAMP;
        vy = (vy + (goal.y + oy - y) * STIFF) * DAMP;
        x += vx; y += vy; tail.unshift({ x, y });
        if (tail.length > TAIL) tail.pop();
        if (strike && Math.hypot(goal.x - x, goal.y - y) < 20) { strike(); strike = null; }
        dawn += ((day ? 1 : 0) - dawn) * .05;
        if (!reduce && Math.hypot(vx, vy) > 2.5 && Math.random() < .5)
          sparks.push({ x, y, vx: vx * .15 + Math.random() - .5, vy: vy * .15 + Math.random() - .5, age: 0, life: .5 + Math.random() * .5, r: 1.3, red: heat(now) > .5 });
        for (const p of sparks) {                   // stardust from the hit slows down fast and settles, tail sparks just fall
          const f = p.dust ? .93 : .95;
          p.x += p.vx; p.y += p.vy; p.vx *= f; p.vy = p.vy * f + (p.dust ? .012 : .03); p.age += 1 / 60;
        }
        for (const o of rings) o.age += 1 / 60;
      }
      for (let i = sparks.length - 1; i >= 0; i--) if (sparks[i].age >= sparks[i].life) sparks.splice(i, 1);
      for (let i = rings.length - 1; i >= 0; i--) if (rings[i].age >= .7) rings.splice(i, 1);
      const k = light(now), hot = heat(now), t = now / 1000;
      const pulse = reduce ? 1 : .86 + .14 * Math.sin(t * 5.464), level = (.3 + .7 * k) * pulse, core = .4 + .6 * k;
      comet.style.translate = `${x}px ${y}px`;
      comet.style.setProperty('--glow', (level * (1 - hot)).toFixed(3));
      comet.style.setProperty('--hot-glow', (level * hot).toFixed(3));
      comet.style.setProperty('--core', (core * (1 - hot)).toFixed(3));
      comet.style.setProperty('--hot-core', (core * hot).toFixed(3));
      night.style.setProperty('--x', x + 'px');
      night.style.setProperty('--y', y + 'px');
      night.style.setProperty('--r', (260 * (.4 + .6 * k)).toFixed(1) + 'px');
      for (const f of [mailField, passField]) {       // the nearer the comet, the colder the edge
        const r = f.getBoundingClientRect(), dx = Math.max(r.left - x, 0, x - r.right), dy = Math.max(r.top - y, 0, y - r.bottom);
        f.style.setProperty('--rim', (clamp(1 - Math.hypot(dx, dy) / 150) * k).toFixed(3));
      }
      draw(k, hot, t);
      requestAnimationFrame(fly);
    })();
    
    // the tail is the path of the last TAIL steps, drawn three times: wide and faint, then thinner and brighter; rose while it is dimmed
    const PASSES = [[1, 9, [140, 203, 255], .16], [.65, 4.5, [160, 212, 255], .4], [.35, 2, [236, 246, 255], .95]];
    const PASSES_HOT = [[255, 120, 145], [255, 143, 160], [255, 226, 232]];
    function draw(k, hot, t) {
      g.setTransform(dpr, 0, 0, dpr, 0, 0);
      g.clearRect(0, 0, innerWidth, innerHeight);
      g.globalCompositeOperation = 'lighter';
      for (const s of stars) {                        // faint all over, bright near the comet, out everywhere once you're in
        const sx = s.x * innerWidth + (reduce ? 0 : Math.sin(t * .683 + s.p) * 6), sy = s.y * innerHeight + (reduce ? 0 : Math.cos(t * .683 + s.p * 1.7) * 8);
        const near = clamp(1 - Math.hypot(sx - x, sy - y) / (260 * (.4 + .6 * k))) ** 1.5;
        const a = (.08 + .34 * dawn + .8 * near) * (reduce ? 1 : .55 + .45 * Math.sin(t * s.f + s.p));
        if (a < .02) continue;
        g.fillStyle = `rgba(200,230,255,${a.toFixed(3)})`; g.beginPath(); g.arc(sx, sy, s.r, 0, 7); g.fill();
      }
      g.lineCap = g.lineJoin = 'round';
      if (!reduce && tail.length > 2) {
        for (let pi = 0; pi < PASSES.length; pi++) {
          const [part, width, c, alpha] = PASSES[pi], h = PASSES_HOT[pi], rgb = `rgba(${c.map((v, j) => Math.round(v + (h[j] - v) * hot)).join()},`;
          const n = Math.max(2, Math.round(tail.length * part)), end = tail[n - 1];
          const fade = g.createLinearGradient(tail[0].x, tail[0].y, end.x, end.y);
          fade.addColorStop(0, rgb + (alpha * k).toFixed(3) + ')'); fade.addColorStop(1, rgb + '0)');
          g.strokeStyle = fade; g.lineWidth = width;
          g.beginPath(); g.moveTo(tail[0].x, tail[0].y);
          for (let i = 1; i < n; i++) g.lineTo(tail[i].x, tail[i].y);
          g.stroke();
        }
      }
      for (const p of sparks) {
        const a = 1 - p.age / p.life;
        if (!p.dust) { g.fillStyle = `rgba(${p.red ? '255,143,160' : '200,230,255'},${a.toFixed(3)})`; g.beginPath(); g.arc(p.x, p.y, p.r, 0, 7); g.fill(); continue; }
        const al = a * (.6 + .4 * Math.sin(p.age * 14 + p.r * 9)), d = g.createRadialGradient(p.x, p.y, 0, p.x, p.y, p.r * 4);
        d.addColorStop(0, `rgba(236,246,255,${al.toFixed(3)})`); d.addColorStop(.35, `rgba(140,203,255,${(.5 * al).toFixed(3)})`); d.addColorStop(1, 'rgba(140,203,255,0)');
        g.fillStyle = d; g.fillRect(p.x - p.r * 4, p.y - p.r * 4, p.r * 8, p.r * 8);
      }
      for (const o of rings) {                        // a flash and a shock wave where it hit the button
        const e = 1 - (1 - o.age / .7) ** 3, q = 1 - o.age / .3;
        if (q > 0) {
          const R = 50 + 170 * (1 - q), d = g.createRadialGradient(o.x, o.y, 0, o.x, o.y, R);
          d.addColorStop(0, `rgba(236,246,255,${(.85 * q).toFixed(3)})`); d.addColorStop(.4, `rgba(140,203,255,${(.3 * q).toFixed(3)})`); d.addColorStop(1, 'rgba(140,203,255,0)');
          g.fillStyle = d; g.fillRect(o.x - R, o.y - R, R * 2, R * 2);
        }
        g.strokeStyle = `rgba(160,212,255,${(.75 * (1 - o.age / .7)).toFixed(3)})`; g.lineWidth = 2.5;
        g.beginPath(); g.ellipse(o.x, o.y, 10 + 190 * e, 4 + 52 * e, 0, 0, 7); g.stroke();
      }
    }
    
    const follow = el => () => aim(at(el));
    for (const el of [email, pass, eye, send])
      el.onfocus = el.onclick = follow(el);
    
    email.addEventListener('input', () => aim(caretGoal(email)));
    
    function paintPassword(fresh) {
      const v = [...pass.value], mark = (node, i) => { if (fresh && i === v.length - 1) node.className = 'new'; return node; };
      dots.replaceChildren(...v.map((_, i) => { const d = mark(document.createElement('i'), i); d.style.setProperty('--i', i); return d; }));
      text.replaceChildren(...v.map((ch, i) => { const b = mark(document.createElement('b'), i); b.textContent = ch; b.style.setProperty('--i', i); return b; }));
      caret.style.translate = (passField.classList.contains('show') ? text.offsetWidth : v.length * 14) + 'px 0';
    }
    pass.addEventListener('input', () => {
      clearTimeout(dropT); passField.classList.remove('drop'); note.classList.remove('on');
      paintPassword(true); aim(pass.value ? caretGoal(pass) : at(pass));
    });
    
    eye.addEventListener('click', () => {
      const on = passField.classList.toggle('show');
      eye.setAttribute('aria-pressed', on);
      eye.setAttribute('aria-label', on ? 'Hide password' : 'Show password');
      paintPassword(false);
    });
    
    // a wrong password: the comet dims and ricochets off the button with rose sparks, the dots sink out, a rose edge comes and goes
    let dropT, badT;
    function fizzle() {
      dimAt = performance.now();
      vx = 6; vy = -14;
      if (!reduce) for (let i = 0; i < 22; i++)
        sparks.push({ x, y, vx: (Math.random() - .5) * 10, vy: -1.5 - 5 * Math.random(), age: 0, life: .45 + .45 * Math.random(), r: 1.8, red: true });
      passField.classList.add('bad', 'drop'); send.classList.add('bad');
      note.textContent = 'Wrong password'; note.classList.add('on');
      pass.value = ''; pass.focus(); aim(at(pass));
      clearTimeout(dropT); dropT = setTimeout(() => { passField.classList.remove('drop'); paintPassword(false); }, 600);
      clearTimeout(badT); badT = setTimeout(() => { passField.classList.remove('bad'); send.classList.remove('bad'); }, 1050);
    }
    
    // the button's light grows from the point where the comet is, and drains back to it;
    // the point is moved with transitions off, so only the size of the circle animates
    function lightFrom() {
      const r = send.getBoundingClientRect();
      send.classList.add('still');
      send.style.setProperty('--hx', clamp(x - r.left, 0, r.width) + 'px');
      send.offsetWidth;
      send.classList.remove('still');
    }
    
    function impact() {
      rings.push({ x, y, age: 0 });
      for (let i = 0; i < 56; i++) {               // stardust: bursts up, slows down fast and settles, twinkling
        const a = -Math.PI / 2 + (Math.random() - .5) * 2.8, s = 2 + 4.5 * Math.random();
        sparks.push({ x, y, vx: Math.cos(a) * s * 1.4, vy: Math.sin(a) * s, age: 0, life: 1.4 + 1.4 * Math.random(), r: .9 + 1.3 * Math.random(), dust: 1 });
      }
    }
    
    async function signIn(login, password) {
      // a real request goes here, for example:
      // const res = await fetch('/api/login', {
      //   method: 'POST',
      //   headers: { 'Content-Type': 'application/json' },
      //   body: JSON.stringify({ login, password }),
      // });
      // return res.ok;
      await wait(250);
      return password === DEMO_PASSWORD;
    }
    
    let round = 0;                            // grows on every submit and reset, so a late answer can tell it's stale
    form.addEventListener('submit', async e => {
      e.preventDefault();
      if (send.classList.contains('done')) return;
      const empty = !email.value ? email : !pass.value ? pass : null;
      if (empty) { aim(at(empty)); empty.focus(); return; }
      aim(at(send));
      const mine = ++round;
      const [ok] = await Promise.all([signIn(email.value, pass.value), wait(300)]);
      if (mine !== round) return;
      if (!ok) return fizzle();
      const r = send.getBoundingClientRect();
      if (!reduce) {                          // it backs off above the form, then dives into the button
        aim({ x: r.left + r.width * .9, y: r.top - 150 });
        await wait(280);
        aim(at(send)); vx -= 6; vy += 12;
        await new Promise(hit => { strike = hit; setTimeout(hit, 400); });
        if (mine !== round) return;
      }
      lightFrom();
      send.classList.add('done');
      daylight(true);
      if (!reduce) {
        impact(); vx = vy = 0; aim({ x, y });          // it stops dead where it hit
        form.animate([{ translate: '0 0' }, { translate: '0 6px', offset: .2 }, { translate: '0 0' }], { duration: 420, easing: 'cubic-bezier(.23, 1, .32, 1)' });
      }
      await wait(450);
      if (mine !== round) return;
      const f = form.getBoundingClientRect();     // and stays, circling the whole form
      aim({ x: f.left + f.width / 2, y: f.top + f.height / 2 }, { x: f.width * .52, y: f.height * .7 });
    });
    
    // back to an empty form, the comet waits at the email field
    function reset() {
      round++;
      clearTimeout(dropT); clearTimeout(badT); dimAt = -1e4;
      email.value = pass.value = '';
      passField.classList.remove('show', 'bad', 'drop'); eye.setAttribute('aria-pressed', false);
      form.classList.remove('clear'); strike = null;
      send.classList.add('still'); send.classList.remove('done', 'bad');       // back to Sign in at once, no unfilling
      requestAnimationFrame(() => requestAnimationFrame(() => send.classList.remove('still')));
      daylight(false); note.classList.remove('on');
      paintPassword(false);
    }
    // call it after a login, before you move on: the comet leaves and takes the light with it,
    // the button drains toward it, the typed text fades, then it comes back to an empty form
    async function leave() {
      const f = form.getBoundingClientRect();
      lightFrom();
      send.classList.remove('done'); form.classList.add('clear'); daylight(false);
      aim({ x: f.left + f.width * .4, y: -160 });
      await wait(600);
      reset();
      aim(at(email));
    }

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

Не вписывайте свой пароль вместо демо, его прочитает любой через код страницы. Найдите a real request goes here в signIn(), удалите демо-проверку и используйте пример с fetch(), указав адрес вашего входа. Верните true, если вход верный, false заставит комету потускнеть и отскочить.

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

Tilda, Webflow, WordPress

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

Tilda

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

Webflow

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

WordPress

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

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

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