Вход из песка

Приветствие из тысяч песчинок над формой входа. Проведите курсором, как ладонью, и каждая песчинка возвращается на своё место.

Проведите курсором по приветствию, зажмите, чтобы продавить ямку. Введите любую почту и пароль и нажмите Log in: кнопка рассыплется песком.

Скачать

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

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

SANDfour tones

Четыре оттенка песка, каждый как красный, зелёный, синий от 0 до 255.

SAND_GRAINS5000, 12000

Сколько песчинок в приветствии на телефоне и на компьютере.

SAND_GRAIN2.4

Размер одной песчинки в пикселях.

SPRING70

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

SAND_PUSH9000

Как сильно курсор отталкивает песок.

SAND_PALM48

Ширина ладони курсора в пикселях.

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

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

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

  1. CSS

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

    /* page shell, only needed while this file is the whole page */
  2. HTML

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

    <!-- login start -->
    <main class="ds">
      <section class="ds-door">
        <canvas class="ds-sand" aria-hidden="true"></canvas>
        <h1 class="ds-display ds-pour">Welcome back.</h1>
        <div class="ds-gate">
          <h2 class="ds-gate-h">Log in to your account</h2>
          <form class="ds-form" novalidate data-busy="Logging in" data-label="Logged in" data-done="You are in. Change this line or send people to their page.">
            <label class="ds-hide" for="ds-user">Email</label>
            <input class="ds-line" id="ds-user" name="email" type="email" autocomplete="username" placeholder="you@example.com" data-need="Enter your email.">
            <label class="ds-hide" for="ds-pass">Password</label>
            <input class="ds-line" id="ds-pass" name="password" type="password" autocomplete="current-password" placeholder="Password" data-need="Enter your password.">
            <button class="ds-button" type="submit">Log in</button>
            <p class="ds-note" role="status"></p>
          </form>
        </div>
      </section>
    </main>
    <!-- login end -->
  3. JavaScript

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

    /* Drift Sand Login by @codinvisual · t.me/CodinVisual · free for your own site, don't resell this file */
    (() => {
    const root = document.querySelector('.ds');
    if (!root) return;
    
    const SAND = [[236, 208, 164], [214, 171, 114], [190, 133, 79], [150, 88, 56]];
    const SAND_GRAINS = [5000, 12000], SAND_GRAIN = 2.4, SPRING = 70, SAND_FRICTION = 5, SAND_PUSH = 9000, SAND_PALM = 48, SAND_DRIFT = 260, SAND_WIND = 14;
    
    const reduce = matchMedia('(prefers-reduced-motion: reduce)').matches;
    root.classList.add('ds-js');
    const $ = (s, el = root) => el.querySelector(s);
    const $$ = (s, el = root) => [...el.querySelectorAll(s)];
    const clamp = (x, a = 0, b = 1) => Math.min(b, Math.max(a, x));
    const wait = ms => new Promise(r => setTimeout(r, ms));
    // one fixed sequence instead of Math.random, so the page behaves the same on every visit
    let seed = 20261009;
    const dice = () => (seed = seed * 16807 % 2147483647) / 2147483647;
    
    /* sand: the greeting is poured from grains; the pointer sweeps them like a palm and each grain finds its own way back */
    const dunes = [];
    $$('.ds-pour').forEach(h => h.classList.add('ds-settle'));
    $$('.ds-sand').forEach(cv => {
      if (reduce) return;
      const host = cv.parentNode, title = $('.ds-pour', host);
      const gl = cv.getContext('webgl2', { alpha: true, premultipliedAlpha: true, antialias: false, depth: false });
      if (!gl) return;
      const VERT = `#version 300 es
    in vec2 p;
    in float tone;
    uniform vec2 view;
    uniform float size;
    uniform vec3 tones[4];
    out vec3 c;
    void main() {
    gl_Position = vec4(p.x / view.x * 2. - 1., 1. - p.y / view.y * 2., 0., 1.);
    gl_PointSize = size;
    c = tones[int(tone)];
    }`;
      const FRAG = `#version 300 es
    precision mediump float;
    in vec3 c;
    out vec4 o;
    void main() {
    // a soft grain: round, a little darker at the rim, no glow
    float d = length(gl_PointCoord - .5), a = smoothstep(.5, .3, d);
    o = vec4(c * (1. - .25 * smoothstep(.1, .45, d)) * a, a);
    }`;
      const sh = (type, src) => { const s = gl.createShader(type); gl.shaderSource(s, src); gl.compileShader(s); return s; };
      const prog = gl.createProgram();
      gl.attachShader(prog, sh(gl.VERTEX_SHADER, VERT)); gl.attachShader(prog, sh(gl.FRAGMENT_SHADER, FRAG));
      gl.bindAttribLocation(prog, 0, 'p'); gl.bindAttribLocation(prog, 1, 'tone'); gl.linkProgram(prog);
      if (!gl.getProgramParameter(prog, gl.LINK_STATUS)) return;
      gl.useProgram(prog);
      const U = n => gl.getUniformLocation(prog, n);
      gl.uniform3fv(U('tones'), SAND.flat().map(v => v / 255));
      gl.enable(gl.BLEND); gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
      const posBuf = gl.createBuffer(), toneBuf = gl.createBuffer();
    
      // every grain: where it is, how fast it goes, where it belongs and how stiff its spring is
      let n = 0, word = 0, X, Y, VX, VY, TX, TY, K, SX, SY, DL, W = 1, H = 1, k = 1, pos;
      function targets() {
        const out = [];
        if (!title) return out;
        const box = host.getBoundingClientRect(), cs = getComputedStyle(title), size = parseFloat(cs.fontSize);
        const c = document.createElement('canvas'); c.width = Math.ceil(W); c.height = Math.ceil(H);
        const x = c.getContext('2d', { willReadFrequently: true });
        x.font = `${cs.fontWeight} ${cs.fontSize} ${cs.fontFamily}`;
        if ('letterSpacing' in x) x.letterSpacing = cs.letterSpacing;
        x.fillStyle = '#fff';
        const m = x.measureText('Hg'), up = m.fontBoundingBoxAscent || size * .8, down = m.fontBoundingBoxDescent || size * .2;
        let lo = 1e9, hi = 0, le = 1e9, ri = 0;
        for (const wd of $$('.ds-wd', title)) {
          const r = wd.getBoundingClientRect(), top = r.top - box.top, left = r.left - box.left;
          x.fillText(wd.textContent, left, top + (r.height - up - down) / 2 + up);
          lo = Math.min(lo, top); hi = Math.max(hi, top + r.height); le = Math.min(le, left); ri = Math.max(ri, left + r.width);
        }
        lo = Math.max(0, Math.floor(lo)); le = Math.max(0, Math.floor(le));
        const bw = Math.min(c.width - le, Math.ceil(ri - le)), bh = Math.min(c.height - lo, Math.ceil(hi - lo));
        if (bw < 1 || bh < 1) return out;
        const data = x.getImageData(le, lo, bw, bh).data;
        let ink = 0;
        for (let i = 3; i < data.length; i += 4) if (data[i] > 127) ink++;
        const most = innerWidth < 760 ? SAND_GRAINS[0] : SAND_GRAINS[1];
        const step = clamp(Math.sqrt(ink / most), 1.6, 4);
        for (let y = 0; y < bh; y += step) for (let xx = 0; xx < bw; xx += step) {
          const jx = xx + (dice() - .5) * step * .6, jy = y + (dice() - .5) * step * .6;
          const a = data[(Math.min(bh - 1, Math.round(jy)) * bw + Math.min(bw - 1, Math.round(jx))) * 4 + 3];
          if (a > 127) out.push(le + jx, lo + jy);
        }
        return out;
      }
      function build(fresh) {
        W = host.clientWidth; H = host.clientHeight;
        if (!W || !H) return false;
        k = Math.min(devicePixelRatio || 1, 2);
        cv.width = Math.round(W * k); cv.height = Math.round(H * k);
        const goal = targets();
        word = goal.length / 2;
        const drift = Math.round(SAND_DRIFT * W * H / 1e6);
        n = word + drift;
        X = new Float32Array(n); Y = new Float32Array(n); VX = new Float32Array(n); VY = new Float32Array(n);
        TX = new Float32Array(n); TY = new Float32Array(n); K = new Float32Array(n); SX = new Float32Array(n); SY = new Float32Array(n); DL = new Float32Array(n);
        pos = new Float32Array(n * 2);
        const tone = new Float32Array(n);
        for (let i = 0; i < n; i++) {
          if (i < word) {
            TX[i] = goal[i * 2]; TY[i] = goal[i * 2 + 1];
            // each grain starts somewhere past the edge of the screen and flies in on its own delay
            const side = dice(), along = dice();
            [SX[i], SY[i]] = side < .4 ? [-20 - dice() * 60, along * H] : side < .8 ? [W + 20 + dice() * 60, along * H] : [along * W, H + 20 + dice() * 40];
            DL[i] = dice() * .55 + TX[i] / W * .25;
          } else {
            TX[i] = dice() * W; TY[i] = dice() * H; SX[i] = TX[i]; SY[i] = TY[i]; DL[i] = -1;
          }
          X[i] = fresh ? SX[i] : TX[i]; Y[i] = fresh ? SY[i] : TY[i];
          K[i] = SPRING * (.65 + dice() * .7);
          const r = dice();
          tone[i] = i < word ? (r < .5 ? 0 : r < .82 ? 1 : r < .96 ? 2 : 3) : (r < .5 ? 1 : 2);
        }
        gl.bindBuffer(gl.ARRAY_BUFFER, toneBuf); gl.bufferData(gl.ARRAY_BUFFER, tone, gl.STATIC_DRAW);
        gl.enableVertexAttribArray(1); gl.vertexAttribPointer(1, 1, gl.FLOAT, false, 0, 0);
        gl.bindBuffer(gl.ARRAY_BUFFER, posBuf); gl.bufferData(gl.ARRAY_BUFFER, pos, gl.DYNAMIC_DRAW);
        gl.enableVertexAttribArray(0); gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 0, 0);
        return true;
      }
      if (title) title.innerHTML = title.textContent.trim().split(' ').map(w => `<span class="ds-wd">${w}</span>`).join(' ');
      if (!build(true)) return;
      root.classList.add('ds-poured');
    
      // the palm: where the pointer is, how fast it goes; a finger on the screen presses a pit
      let mx = -1e4, my = -1e4, mvx = 0, mvy = 0, pit = 0, lastMove = 0, gust = 0;
      let shown = true, running = false, last = 0, start = 0;
      const ease = u => 1 - Math.pow(1 - u, 3);
      function frame(now) {
        if (!shown || document.hidden) { running = false; return; }
        const t = now / 1000, dt = Math.min(t - last, 1 / 30); last = t;
        const age = t - start, damp = Math.exp(-SAND_FRICTION * dt);
        if (t - lastMove > .06) { mvx *= Math.exp(-14 * dt); mvy *= Math.exp(-14 * dt); }
        pit = Math.max(0, pit - dt * 2.2);
        const R = SAND_PALM, R2 = R * R;
        for (let i = 0; i < n; i++) {
          let x = X[i], y = Y[i];
          if (i < word && age < DL[i] + 1.1) {
            // the way in: an easy curve from the edge, then the spring takes over
            const u = clamp((age - DL[i]) / 1.1), e = ease(u);
            x = SX[i] + (TX[i] - SX[i]) * e + Math.sin(u * Math.PI) * 26 * (i % 2 ? 1 : -1);
            y = SY[i] + (TY[i] - SY[i]) * e;
            X[i] = x; Y[i] = y; VX[i] = 0; VY[i] = 0;
          } else {
            let ax, ay;
            if (i < word) { ax = (TX[i] - x) * K[i]; ay = (TY[i] - y) * K[i]; }
            else {
              // loose sand drifts slowly to the right and wraps around
              TX[i] += SAND_WIND * dt * (.6 + (i % 7) * .1);
              if (TX[i] > W + 10) { TX[i] -= W + 20; X[i] -= W + 20; x = X[i]; }
              ax = (TX[i] - x) * 4; ay = (TY[i] + Math.sin(t * .7 + i) * 6 - y) * 4;
            }
            const dx = x - mx, dy = y - my, d2 = dx * dx + dy * dy;
            if (d2 < R2) {
              const d = Math.sqrt(d2) + .01, f = 1 - d / R;
              ax += dx / d * f * (SAND_PUSH * (.35 + pit)) + mvx * f * 14;
              ay += dy / d * f * (SAND_PUSH * (.35 + pit)) + mvy * f * 14;
            }
            ay -= gust * (40 + (i % 13) * 10);
            VX[i] = (VX[i] + ax * dt) * damp; VY[i] = (VY[i] + ay * dt) * damp;
            X[i] = x + VX[i] * dt; Y[i] = y + VY[i] * dt;
          }
          // at rest the grains barely breathe
          pos[i * 2] = X[i] + Math.sin(t * 1.3 + i * 1.7) * .22;
          pos[i * 2 + 1] = Y[i] + Math.cos(t * 1.1 + i * 2.3) * .22;
        }
        gust = Math.max(0, gust - dt * 1.6);
        gl.viewport(0, 0, cv.width, cv.height);
        gl.clearColor(0, 0, 0, 0); gl.clear(gl.COLOR_BUFFER_BIT);
        gl.uniform2f(U('view'), W, H); gl.uniform1f(U('size'), SAND_GRAIN * k);
        gl.bindBuffer(gl.ARRAY_BUFFER, posBuf); gl.bufferSubData(gl.ARRAY_BUFFER, 0, pos);
        gl.drawArrays(gl.POINTS, 0, n);
        requestAnimationFrame(frame);
      }
      const wake = () => { if (running || !shown || document.hidden) return; running = true; requestAnimationFrame(t => { last = t / 1000; if (!start) start = last; frame(t); }); };
    
      const spot = e => { const r = cv.getBoundingClientRect(); return [e.clientX - r.left, e.clientY - r.top]; };
      host.addEventListener('pointermove', e => {
        const [x, y] = spot(e), now = performance.now() / 1000, dt = Math.max(now - lastMove, 1 / 120);
        if (mx > -1e3 && now - lastMove < .2) { mvx = mvx * .5 + (x - mx) / dt * .5; mvy = mvy * .5 + (y - my) / dt * .5; }
        mx = x; my = y; lastMove = now;
      });
      host.addEventListener('pointerleave', () => { mx = my = -1e4; mvx = mvy = 0; });
      host.addEventListener('pointercancel', () => { mx = my = -1e4; mvx = mvy = 0; });
      // a tap or a press: the palm pushes a pit into the sand
      host.addEventListener('pointerdown', e => {
        if (e.target.closest('a, button, input, textarea, label')) return;
        [mx, my] = spot(e); lastMove = performance.now() / 1000; pit = 1.6;
      });
      host.addEventListener('pointerup', e => { if (e.pointerType !== 'mouse') { mx = my = -1e4; mvx = mvy = 0; } });
      // scrolling blows the sand up a little; the springs bring it back
      let top = scrollY;
      addEventListener('scroll', () => {
        const d = Math.abs(scrollY - top); top = scrollY;
        if (shown && d) gust = Math.min(1.4, gust + d / 260);
      }, { passive: true });
      // a form that went through throws the headline up in the air; the springs pour it back
      dunes.push({ burst() { for (let i = 0; i < word; i++) { VX[i] += (dice() - .5) * 520; VY[i] -= 260 + dice() * 520; } } });
      new ResizeObserver(() => { if (cv.width && Math.abs(host.clientWidth - W) + Math.abs(host.clientHeight - H) > 2) { build(false); start = last - 9; } }).observe(host);
      new IntersectionObserver(([e]) => { shown = e.isIntersecting; wake(); }).observe(cv);
      document.addEventListener('visibilitychange', wake);
      wake();
    });
    
    /* a form that went through: its button crumbles into sand, and the sand pours itself into the word of the result */
    function crumble(btn, word) {
      if (reduce) return;
      const r = btn.getBoundingClientRect(), k = Math.min(devicePixelRatio || 1, 2), cs = getComputedStyle(btn);
      const cv = document.createElement('canvas'), c = cv.getContext('2d');
      cv.className = 'ds-dust'; cv.width = innerWidth * k; cv.height = innerHeight * k;
      root.append(cv);
      // where the word will stand: drawn once in a small canvas over the button and read back as points
      const w = Math.ceil(r.width), h = Math.ceil(r.height), t = document.createElement('canvas');
      t.width = w; t.height = h;
      const x = t.getContext('2d', { willReadFrequently: true });
      const page = getComputedStyle(root);
      x.font = `500 ${Math.round(parseFloat(cs.fontSize) * 2)}px ${page.getPropertyValue('--serif') || 'serif'}`; x.textAlign = 'center'; x.textBaseline = 'middle'; x.fillStyle = '#fff';
      x.fillText(word, w / 2, h / 2 + 1);
      const data = x.getImageData(0, 0, w, h).data, goal = [];
      for (let y = 0; y < h; y += 2) for (let i = 0; i < w; i += 2) if (data[(y * w + i) * 4 + 3] > 120) goal.push([r.left + i, r.top + y]);
      // the grains are the button itself, sampled over its rounded shape
      const rad = Math.min(h / 2, parseFloat(cs.borderTopLeftRadius) || 0), bits = [];
      for (let y = 1; y < h; y += 2.4) for (let i = 1; i < w; i += 2.4) {
        const ex = Math.max(rad - i, i - (w - rad), 0), ey = Math.max(rad - y, y - (h - rad), 0);
        if (ex * ex + ey * ey > rad * rad) continue;
        const a = dice() * Math.PI * 2, v = 60 + dice() * 220;
        bits.push({ x: r.left + i, y: r.top + y, vx: Math.cos(a) * v, vy: Math.sin(a) * v - 140, g: null, tone: dice() });
      }
      for (let i = 0; i < goal.length; i++) bits[Math.floor(i * bits.length / goal.length)].g = goal[i];
      const tones = SAND.map(c => `rgb(${c})`), ink = page.color;
      btn.style.transition = 'none'; btn.style.opacity = '0';
      dunes.forEach(d => d.burst());
      const t0 = performance.now();
      let last = t0;
      requestAnimationFrame(function pour(now) {
        const age = (now - t0) / 1000, dt = Math.min((now - last) / 1000, .05); last = now;
        c.setTransform(k, 0, 0, k, 0, 0); c.clearRect(0, 0, innerWidth, innerHeight);
        const gather = clamp((age - .45) / .8), fade = clamp((age - 1.7) / .4);
        for (const b of bits) {
          if (b.g && age > .45) {
            // the word grains leave the heap and settle into the letters
            const e = 1 - Math.pow(1 - gather, 3);
            b.x += (b.g[0] - b.x) * Math.min(1, e * 9 * dt + e * e * .25);
            b.y += (b.g[1] - b.y) * Math.min(1, e * 9 * dt + e * e * .25);
          } else {
            b.vy += 900 * dt; b.vx *= 1 - 2 * dt; b.x += b.vx * dt; b.y += b.vy * dt;
          }
          const alpha = b.g ? 1 - fade : clamp(1 - age / 1.2);
          if (alpha <= 0) continue;
          c.globalAlpha = alpha;
          c.fillStyle = b.g && gather > .6 ? ink : tones[b.tone < .55 ? 0 : b.tone < .85 ? 1 : 2];
          c.fillRect(b.x - 1, b.y - 1, 2, 2);
        }
        if (age > 1.65 && btn.style.opacity === '0') { btn.style.transition = 'opacity .4s ease'; btn.style.opacity = '1'; }
        if (age < 2.1) requestAnimationFrame(pour); else { cv.remove(); btn.style.transition = ''; }
      });
    }
    
    /* the form: checks the fields, waits for the server, then the button turns to sand */
    $$('.ds-form').forEach(form => {
      const btn = $('.ds-button', form), note = $('.ds-note', form), fields = $$('input, textarea', form);
      form.addEventListener('submit', async e => {
        e.preventDefault();
        const bad = fields.find(f => !f.value.trim() || f.type === 'email' && !/^\S+@\S+\.\S+$/.test(f.value.trim()));
        fields.forEach(f => f.classList.toggle('ds-bad', f === bad));
        form.classList.toggle('ds-form-bad', !!bad);
        if (bad) {
          note.textContent = bad.type === 'email' && bad.value.trim() ? 'That does not look like an email. Try one like name@example.com.' : bad.dataset.need || 'Fill in this field first.';
          bad.focus();
          return;
        }
        btn.disabled = true; btn.textContent = form.dataset.busy || 'Sending';
        // a real server request goes here, for example:
        // await fetch('/api/login', { method: 'POST', body: new FormData(form) });
        await wait(700);
        fields.forEach(f => { f.disabled = true; });
        btn.textContent = form.dataset.label || 'Sent';
        form.classList.add('ds-sent');
        note.textContent = form.dataset.done || 'Thank you. We will write back soon.';
        crumble(btn, btn.textContent);
      });
      fields.forEach(f => f.addEventListener('input', () => { form.classList.remove('ds-form-bad'); f.classList.remove('ds-bad'); note.textContent = ''; }));
    });
    })();

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

Форма ничего не отправляет, пока вы её не подключили. Найдите a real server request goes here, поставьте туда свой fetch() и уберите таймер на следующей строке.

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

Tilda, Webflow, WordPress

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

Tilda

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

Webflow

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

WordPress

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

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

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