Магнитное скачивание

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

Подведите курсор к заблокированной карточке, затем введите пароль magnet и нажмите для скачивания.

Скачать

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

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

PASSmagnet

Пароль, который разблокирует карточку файла.

PUSH90

На сколько пикселей заблокированная карточка отскакивает от курсора.

PULL_R200

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

SPRING0.16

Скорость пружины, с которой карточка тянется за курсором и возвращается.

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

Подходит для закрытых загрузок, выдачи цифровых продуктов и приватных ссылок.

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

  1. CSS

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

    /* Magnetic Download by @codinvisual · t.me/CodinVisual · page shell, only while this file is the whole page */
  2. HTML

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

    <!-- stage start -->
    <div class="mdl">
      <div class="mdl-col">
        <h1 class="mdl-title"><b>Brand kit, locked</b><span>ENTER THE WORD TO UNLOCK</span></h1>
        <div class="mdl-stage">
          <div class="mdl-mover">
            <div class="mdl-shade"></div>
            <div class="mdl-body">
              <a class="mdl-hit" href="#" draggable="false" download="brand-kit.zip">
                <svg class="mdl-ico" viewBox="0 0 36 36" aria-hidden="true">
                  <path d="M9 5.5h11.2L27 12.2V29a1.6 1.6 0 0 1-1.6 1.6H9A1.6 1.6 0 0 1 7.4 29V7.1A1.6 1.6 0 0 1 9 5.5z" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linejoin="round"></path>
                  <path d="M20 5.6V12h6.2" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linejoin="round"></path>
                  <path d="M18 17.5v8.2M14.2 22.2 18 26l3.8-3.8" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"></path>
                </svg>
                <span>
                  <span class="mdl-name">brand-kit.zip</span>
                  <span class="mdl-sub"><span class="mdl-size">1 KB</span><span class="mdl-word">Download</span></span>
                </span>
                <svg class="mdl-lock" viewBox="0 0 22 22" aria-hidden="true">
                  <path class="shackle" d="M7 10V7.2a4 4 0 0 1 8 0V10" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"></path>
                  <rect x="4.5" y="10" width="13" height="10" rx="2.4" fill="currentColor"></rect>
                </svg>
                <span class="mdl-ring"></span>
              </a>
            </div>
          </div>
        </div>
        <label class="mdl-lockbox">
          <span class="mdl-lab">PASSWORD</span>
          <input class="mdl-key" type="password" autocomplete="off" spellcheck="false" aria-label="Password">
        </label>
        <div class="mdl-hint" aria-live="polite"></div>
      </div>
    </div>
    <!-- stage end -->
  3. JavaScript

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

    /* Magnetic Download by @codinvisual · t.me/CodinVisual · free for your own site, don't resell this file */
    const PASS = 'magnet';
    const PUSH = 90;
    const PULL_R = 200;
    const SPRING = 0.16;
    const FILE_URL = '';
    const FILE_NAME = 'brand-kit.zip';
    const FILE_SIZE = '1 KB';
    
    const reduce = matchMedia('(prefers-reduced-motion: reduce)').matches;
    const root = document.querySelector('.mdl');
    const mover = document.querySelector('.mdl-mover');
    const plate = document.querySelector('.mdl-hit');
    const nameEl = document.querySelector('.mdl-name');
    const sizeEl = document.querySelector('.mdl-size');
    const key = document.querySelector('.mdl-key');
    const hint = document.querySelector('.mdl-hint');
    let unlocked = false;
    
    let x = 0, y = 0, vx = 0, vy = 0, tx = 0, ty = 0, tilt = 0;
    let mode = 'rest', pid = 0, nativeDrag = false, moved = false;
    let gx = 0, gy = 0, hx = 0, hy = 0, raf = 0, cursor = null;
    let halfW = 260, halfH = 60;
    let bounds = { minX: -240, maxX: 240, minY: -120, maxY: 300 };
    const hist = [];
    const blank = new Image();
    blank.src = 'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==';
    
    function clamp(v, a, b) { return v < a ? a : v > b ? b : v; }
    function rubber(over, dim) {
    const c = 0.55, a = Math.abs(over);
    return Math.sign(over) * (a * dim * c) / (dim + c * a);
    }
    function crc32(buf) {
    let c = ~0;
    for (let i = 0; i < buf.length; i++) {
      c ^= buf[i];
      for (let k = 0; k < 8; k++) c = (c >>> 1) ^ (0xedb88320 & -(c & 1));
    }
    return ~c >>> 0;
    }
    function zipHref() {
    if (zipHref.cache) return zipHref.cache;
    const file = new TextEncoder().encode('CodinVisual brand kit\nInk #eef1f5\nPlate #15181c\nAccent #5EEAD4\nType system-ui\nSet FILE_URL to ship your own file.\n');
    const fname = new TextEncoder().encode('brand-kit.txt');
    const crc = crc32(file);
    const bin = [];
    const u16 = (n) => bin.push(n & 255, (n >>> 8) & 255);
    const u32 = (n) => bin.push(n & 255, (n >>> 8) & 255, (n >>> 16) & 255, (n >>> 24) & 255);
    u32(0x04034b50); u16(20); u16(0); u16(0); u16(0); u16(0);
    u32(crc); u32(file.length); u32(file.length); u16(fname.length); u16(0);
    fname.forEach((b) => bin.push(b));
    file.forEach((b) => bin.push(b));
    const cdOff = bin.length;
    u32(0x02014b50); u16(20); u16(20); u16(0); u16(0); u16(0); u16(0);
    u32(crc); u32(file.length); u32(file.length); u16(fname.length);
    u16(0); u16(0); u16(0); u16(0); u16(0); u32(0); u32(0);
    fname.forEach((b) => bin.push(b));
    const cdSize = bin.length - cdOff;
    u32(0x06054b50); u16(0); u16(0); u16(1); u16(1);
    u32(cdSize); u32(cdOff); u16(0);
    const bytes = new Uint8Array(bin);
    let raw = '';
    for (let i = 0; i < bytes.length; i++) raw += String.fromCharCode(bytes[i]);
    zipHref.cache = 'data:application/zip;base64,' + btoa(raw);
    sizeEl.textContent = bytes.length < 1024 ? bytes.length + ' B' : (bytes.length / 1024).toFixed(1) + ' KB';
    return zipHref.cache;
    }
    function fileHref() { return FILE_URL || zipHref(); }
    nameEl.textContent = FILE_NAME;
    sizeEl.textContent = FILE_SIZE;
    plate.href = fileHref();
    plate.setAttribute('download', FILE_NAME);
    
    function measure() {
    const rr = root.getBoundingClientRect();
    const pr = plate.getBoundingClientRect();
    hx = pr.left + pr.width / 2 - x;
    hy = pr.top + pr.height / 2 - y;
    halfW = pr.width / 2;
    halfH = pr.height / 2;
    const half = Math.max(80, (rr.width - pr.width) / 2 - 16);
    bounds = { minX: -half, maxX: half, minY: Math.min(-40, -(hy - rr.top - 40)), maxY: rr.bottom - hy - 40 };
    }
    function wake() { if (!raf) raf = requestAnimationFrame(frame); }
    function softLimit(nx, ny) {
    let ox = 0, oy = 0;
    if (nx < bounds.minX) { ox = nx - bounds.minX; nx = bounds.minX; }
    else if (nx > bounds.maxX) { ox = nx - bounds.maxX; nx = bounds.maxX; }
    if (ny < bounds.minY) { oy = ny - bounds.minY; ny = bounds.minY; }
    else if (ny > bounds.maxY) { oy = ny - bounds.maxY; ny = bounds.maxY; }
    return { x: nx + (ox ? rubber(ox, 280) : 0), y: ny + (oy ? rubber(oy, 280) : 0) };
    }
    function flick() {
    if (hist.length < 2) return { x: vx, y: vy };
    const a = hist[0], b = hist[hist.length - 1];
    const dt = Math.max(16, b.t - a.t);
    return { x: (b.x - a.x) / dt * 16.67, y: (b.y - a.y) / dt * 16.67 };
    }
    function pushHist(e) {
    hist.push({ x: e.clientX, y: e.clientY, t: performance.now() });
    if (hist.length > 5) hist.shift();
    }
    function place(e) {
    const lim = softLimit(e.clientX - gx - hx, e.clientY - gy - hy);
    if (Math.hypot(lim.x - x, lim.y - y) > 4) moved = true;
    vx = lim.x - x;
    vy = lim.y - y;
    x = lim.x;
    y = lim.y;
    }
    function release() {
    if (mode !== 'hold') return;
    const v = reduce ? { x: 0, y: 0 } : flick();
    vx = v.x; vy = v.y;
    if (!moved && Math.hypot(vx, vy) < 0.8) { mode = 'rest'; wake(); return; }
    mode = reduce ? 'rest' : 'throw';
    wake();
    }
    /* locked: the plate flees the pointer. unlocked: it chases the pointer */
    function aim() {
    tx = 0; ty = 0;
    if (!cursor) return;
    const dx = cursor.x - hx;
    const dy = cursor.y - hy;
    const d = Math.hypot(dx, dy);
    if (d < 0.001) return;
    const ax = Math.max(0, Math.abs(dx) - halfW);
    const ay = Math.max(0, Math.abs(dy) - halfH);
    const outer = Math.hypot(ax, ay);
    if (outer >= PULL_R) return;
    const f = (1 - outer / PULL_R) ** 2;
    if (unlocked) {
      const span = Math.min(d, 170) * 0.62 * f;
      tx = dx / d * span;
      ty = dy / d * span;
    } else {
      tx = -dx / d * PUSH * f;
      ty = -dy / d * PUSH * f;
    }
    }
    function frame() {
    raf = 0;
    if (mode === 'rest' || mode === 'hold') aim();
    if (mode === 'rest') {
      if (reduce) { x = tx; y = ty; vx = 0; vy = 0; }
      else {
        vx += (tx - x) * SPRING;
        vy += (ty - y) * SPRING;
        vx *= 0.72; vy *= 0.72;
        x += vx; y += vy;
      }
    } else if (mode === 'throw') {
      vx *= 0.92; vy *= 0.92; x += vx; y += vy;
      if (x < bounds.minX) { x = bounds.minX + rubber(x - bounds.minX, 280); vx *= 0.84; }
      else if (x > bounds.maxX) { x = bounds.maxX + rubber(x - bounds.maxX, 280); vx *= 0.84; }
      if (y < bounds.minY) { y = bounds.minY + rubber(y - bounds.minY, 280); vy *= 0.84; }
      else if (y > bounds.maxY) { y = bounds.maxY + rubber(y - bounds.maxY, 280); vy *= 0.84; }
      if (Math.hypot(vx, vy) < 0.45) mode = 'rest';
    }
    const spd = mode === 'hold' ? flick() : { x: vx, y: vy };
    tilt = clamp((mode === 'hold' ? spd.x : vx) * 0.06 + tx * 0.06, -8, 8);
    if (cursor) {
      const r = plate.getBoundingClientRect();
      plate.style.setProperty('--lx', ((cursor.x - r.left) / r.width * 100).toFixed(1) + '%');
      plate.style.setProperty('--ly', ((cursor.y - r.top) / r.height * 100).toFixed(1) + '%');
    }
    const px = Math.round(x);
    const py = Math.round(y);
    mover.style.transform = (px || py || Math.abs(tilt) > 0.4)
      ? 'translate(' + px + 'px,' + py + 'px) rotate(' + tilt.toFixed(2) + 'deg)'
      : 'none';
    const live = mode !== 'rest' || Math.hypot(vx, vy) > 0.08 || Math.hypot(tx - x, ty - y) > 0.6;
    if (live) raf = requestAnimationFrame(frame);
    }
    
    plate.addEventListener('pointerdown', (e) => {
    if (!unlocked) { e.preventDefault(); return; }
    if (e.button > 0 || pid) return;
    measure();
    pid = e.pointerId;
    mode = 'hold';
    moved = false;
    nativeDrag = false;
    gx = e.clientX - (hx + x);
    gy = e.clientY - (hy + y);
    hist.length = 0;
    pushHist(e);
    if (e.pointerType !== 'mouse') { plate.draggable = false; plate.setPointerCapture(e.pointerId); }
    else plate.draggable = true;
    wake();
    });
    window.addEventListener('pointermove', (e) => {
    cursor = { x: e.clientX, y: e.clientY };
    if (mode === 'hold' && !nativeDrag && e.pointerId === pid) { pushHist(e); place(e); }
    wake();
    });
    function endPointer(e) {
    if (e.pointerId !== pid) return;
    pid = 0;
    if (!nativeDrag) release();
    }
    window.addEventListener('pointerup', endPointer);
    window.addEventListener('pointercancel', endPointer);
    document.documentElement.addEventListener('pointerleave', () => { cursor = null; wake(); });
    plate.addEventListener('dragstart', (e) => {
    if (!unlocked) { e.preventDefault(); return; }
    nativeDrag = true;
    e.dataTransfer.setData('DownloadURL', 'application/zip:' + FILE_NAME + ':' + fileHref());
    e.dataTransfer.setData('text/plain', FILE_NAME);
    e.dataTransfer.effectAllowed = 'copy';
    e.dataTransfer.setDragImage(blank, 0, 0);
    });
    plate.addEventListener('drag', (e) => {
    if (!e.clientX && !e.clientY) return;
    cursor = { x: e.clientX, y: e.clientY };
    pushHist(e);
    place(e);
    wake();
    });
    plate.addEventListener('dragend', (e) => {
    nativeDrag = false;
    pid = 0;
    const left = e.clientX <= 0 || e.clientY <= 0 || e.clientX >= innerWidth || e.clientY >= innerHeight;
    if (left) { mode = 'rest'; wake(); return; }
    release();
    });
    plate.addEventListener('click', (e) => { if (!unlocked || moved) e.preventDefault(); });
    key.addEventListener('input', () => {
    const ok = key.value === PASS;
    if (ok && !unlocked) hint.textContent = 'unlocked. take the file';
    if (ok) hint.className = 'mdl-hint ok';
    else if (!key.value) { hint.textContent = ''; hint.className = 'mdl-hint'; }
    unlocked = ok;
    root.classList.toggle('mdl-open', unlocked);
    plate.draggable = unlocked;
    if (!unlocked && mode === 'hold') { pid = 0; mode = 'rest'; }
    wake();
    });
    key.addEventListener('keydown', (e) => {
    if (e.key !== 'Enter' || unlocked) return;
    hint.textContent = 'wrong word. try again';
    hint.className = 'mdl-hint bad';
    });
    window.addEventListener('resize', measure);
    measure();

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

Перенесите проверку пароля на сервер и отдавайте подписанную ссылку в FILE_URL после проверки.

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

Tilda, Webflow, WordPress

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

Tilda

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

Webflow

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

WordPress

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

Ещё в разделе «Кнопки и переключатели»

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