Сфера из частиц в слово

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

Напишите слово до 12 букв или цифр и нажмите Enter. Новое слово, и сфера соберётся заново, сотрите поле, и точки вернутся домой.

Скачать

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

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

DOTS9000

Сколько точек, меньше значит легче для слабых телефонов.

STIFF0.045

Как сильно каждую точку тянет на своё место.

DAMP0.84

Сколько скорости точка сохраняет, больше значит сильнее раскачивается.

CURL0.02

Насколько точки закручиваются по пути.

PUSH70

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

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

Первый экран, страница запуска или обратного отсчёта, поздравление с чьим-то именем.

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

  1. CSS

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

    /* Particle Orb Word by @codinvisual · t.me/CodinVisual · page shell, only needed while this file is the whole page */
  2. HTML

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

    <!-- orb start -->
    <div class="po">
      <canvas class="po-sky" aria-hidden="true"></canvas>
      <canvas class="po-grain" aria-hidden="true"></canvas>
      <form class="po-form" novalidate>
        <label class="po-wrap"><span style="position:absolute;width:1px;height:1px;overflow:hidden;clip-path:inset(50%)">A word for the dots</span>
          <input class="po-field" name="word" maxlength="12" autocomplete="off" spellcheck="false" placeholder="Type a word">
        </label>
        <button class="po-btn" type="submit"><span>Make it</span><svg viewBox="0 0 24 24" width="22" height="22" aria-hidden="true"><path d="M4 12h15M13.5 6l6 6-6 6" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"/></svg></button>
      </form>
    </div>
    <!-- orb end -->
  3. JavaScript

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

    /* Particle Orb Word by @codinvisual · t.me/CodinVisual · free for your own site, don't resell this file */
    (() => {
    const DOTS = 9000;
    const STIFF = 0.045;
    const DAMP = 0.84;
    const CURL = 0.02;
    const PUSH = 70;
    
    const root = document.querySelector('.po');
    if (!root) return;
    const sky = root.querySelector('.po-sky'), grain = root.querySelector('.po-grain');
    const form = root.querySelector('.po-form'), field = root.querySelector('.po-field');
    const calm = matchMedia('(prefers-reduced-motion: reduce)');
    const ctx = sky.getContext('2d');
    const halo = document.createElement('canvas'), hctx = halo.getContext('2d');
    const page = document.createElement('canvas'), pctx = page.getContext('2d');
    const clamp = (v, a = 0, b = 1) => v < a ? a : v > b ? b : v;
    let seed = 9000;
    const rnd = () => {
      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;
    };
    
    // every dot: where it is, how fast it goes, where it lives on the sphere, where it is going
    const N = DOTS;
    const px = new Float32Array(N), py = new Float32Array(N), vx = new Float32Array(N), vy = new Float32Array(N), pz = new Float32Array(N);
    const hx = new Float32Array(N), hy = new Float32Array(N), hz = new Float32Array(N), ph = new Float32Array(N);
    const gx = new Float32Array(N), gy = new Float32Array(N), wait = new Float32Array(N);
    const golden = Math.PI * (3 - Math.sqrt(5));
    for (let i = 0; i < N; i++) {
      const y = 1 - (i + .5) / N * 2, r = Math.sqrt(1 - y * y), a = golden * i;
      hx[i] = Math.cos(a) * r; hy[i] = y; hz[i] = Math.sin(a) * r; ph[i] = rnd() * 6.283;
    }
    let W = 0, H = 0, DPR = 1, BW = 0, BH = 0, img = null, buf = null, R = 1, cx = 0, cy = 0;
    let word = false, turn = 0, born = 0, ptr = null;
    
    function setup() {
      const w = root.clientWidth, h = root.clientHeight;
      if (!w || !h || (w === W && h === H)) return;
      W = w; H = h;
      DPR = Math.min(2, window.devicePixelRatio || 1);
      while (W * H * DPR * DPR > 3.2e6 && DPR > 1) DPR -= .25;
      BW = Math.round(W * DPR); BH = Math.round(H * DPR);
      sky.width = BW; sky.height = BH; page.width = BW; page.height = BH;
      halo.width = Math.ceil(BW / 6); halo.height = Math.ceil(BH / 6);
      img = pctx.createImageData(BW, BH); buf = img.data;
      R = Math.min(W * .3, H * .3); cx = W * .5; cy = H * .43;
      grain.width = Math.round(W / 2); grain.height = Math.round(H / 2);
      const gc = grain.getContext('2d'), gi = gc.createImageData(grain.width, grain.height);
      for (let i = 0; i < gi.data.length; i += 4) { const v = rnd() * 255; gi.data[i] = gi.data[i + 1] = gi.data[i + 2] = v; gi.data[i + 3] = 12; }
      gc.putImageData(gi, 0, 0);
      if (!born) { for (let i = 0; i < N; i++) { const s = sphere(i); px[i] = s.x; py[i] = s.y; } born = 1; }
      if (word && last) shape(last);
    }
    // a point of the sphere on screen, turning slowly
    function sphere(i) {
      const c = Math.cos(turn), s = Math.sin(turn), x = hx[i] * c + hz[i] * s, z = -hx[i] * s + hz[i] * c;
      const tilt = .32, y = hy[i] * Math.cos(tilt) - z * Math.sin(tilt), zz = hy[i] * Math.sin(tilt) + z * Math.cos(tilt);
      const k = 3.2 / (3.2 - zz);
      return { x: cx + x * R * k, y: cy + y * R * k, z: zz };
    }
    
    // the word is drawn once on a hidden canvas, its pixels become the places for the dots
    let last = '';
    function shape(text) {
      last = text;
      const c = document.createElement('canvas'), w = Math.round(W * .88), h = Math.round(H * .46);
      c.width = w; c.height = h;
      const x = c.getContext('2d', { willReadFrequently: true });
      let fs = h * .82;
      const font = s => `900 ${s}px system-ui, "Noto Sans", sans-serif`;
      x.font = font(fs);
      const tw = x.measureText(text).width;
      if (tw > w) fs *= w / tw;
      x.font = font(fs); x.textAlign = 'center'; x.textBaseline = 'middle'; x.fillStyle = '#fff';
      x.fillText(text, w / 2, h / 2);
      const data = x.getImageData(0, 0, w, h).data;
      let area = 0;
      for (let i = 3; i < data.length; i += 16) if (data[i] > 128) area++;
      const step = Math.max(1.2, Math.sqrt(area * 4 / N) * .97);
      const pts = [];
      for (let y = 0; y < h; y += step) for (let xx = 0; xx < w; xx += step) {
        const sx = xx + (rnd() - .5) * step * .7, sy = y + (rnd() - .5) * step * .7;
        if (data[(Math.round(sy) * w + Math.round(sx)) * 4 + 3] > 128) pts.push([sx + (W - w) / 2, sy + cy - h / 2]);
      }
      if (!pts.length) return home();
      while (pts.length < N) { const p = pts[(rnd() * pts.length) | 0]; pts.push([p[0] + (rnd() - .5) * step, p[1] + (rnd() - .5) * step]); }
      pts.length = N;
      // dots and places are paired from left to right, so the flight reads as one wave
      const order = Array.from({ length: N }, (_, i) => i).sort((a, b) => px[a] - px[b]);
      pts.sort((a, b) => a[0] - b[0]);
      let far = 1;
      for (const p of pts) far = Math.max(far, Math.hypot(p[0] - cx, p[1] - cy));
      for (let k = 0; k < N; k++) {
        const i = order[k];
        gx[i] = pts[k][0]; gy[i] = pts[k][1];
        wait[i] = (Math.hypot(pts[k][0] - cx, pts[k][1] - cy) / far) * .35 + rnd() * .12;
      }
      word = true; started = performance.now();
    }
    function home() {
      word = false; last = '';
      for (let i = 0; i < N; i++) wait[i] = rnd() * .2;
      started = performance.now();
    }
    let started = 0;
    
    function frame(now) {
      const dt = Math.min(.05, frame.t ? (now - frame.t) / 1000 : .016);
      frame.t = now;
      if (!W) { requestAnimationFrame(frame); return; }
      const still = calm.matches, since = (now - started) / 1000;
      if (!still && !word) turn += dt * .1;
      const steps = Math.max(1, Math.round(dt * 60)), stiff = still ? STIFF * 2.2 : STIFF, damp = still ? .7 : DAMP, curl = still ? 0 : CURL;
      buf.fill(0);
      const t = now / 1000, dim = clamp(Math.sqrt(R / 250), .45, 1);   // a small sphere holds the same dots closer, so each one is dimmer
      for (let i = 0; i < N; i++) {
        let tx, ty, z;
        if (word) {
          // a word breathes a pixel or two
          tx = gx[i] + Math.sin(t * 1.3 + ph[i]) * .8; ty = gy[i] + Math.cos(t * 1.1 + ph[i]) * .8; z = .15 * Math.sin(ph[i]);
        } else {
          const s = sphere(i); tx = s.x; ty = s.y; z = s.z;
        }
        if (since < wait[i]) { tx = px[i]; ty = py[i]; }
        for (let s = 0; s < steps; s++) {
          const dx = tx - px[i], dy = ty - py[i];
          vx[i] = (vx[i] + dx * stiff - dy * curl) * damp;
          vy[i] = (vy[i] + dy * stiff + dx * curl) * damp;
          if (ptr) {
            const ex = px[i] - ptr.x, ey = py[i] - ptr.y, d2 = ex * ex + ey * ey;
            if (d2 < PUSH * PUSH && d2 > .01) {
              const d = Math.sqrt(d2), f = (1 - d / PUSH) * 1.6;
              vx[i] += ex / d * f; vy[i] += ey / d * f;
            }
          }
          px[i] += vx[i]; py[i] += vy[i];
        }
        pz[i] += (z - pz[i]) * .2;
        // light from the right: near dots are bigger and brighter, the lit side warmer
        const depth = (pz[i] + 1) / 2, lit = clamp(.5 + (px[i] - cx) / (R * 2.4));
        const b = word ? .88 + .1 * Math.sin(t * 1.6 + ph[i] * 3) : (.28 + .72 * depth) * (.55 + .45 * lit);
        const r = 255 * b * dim, g = (205 + 30 * (1 - lit)) * b * dim, bl = (160 + 70 * (1 - lit)) * b * dim;
        const sx = px[i] * DPR, sy = py[i] * DPR, size = Math.max(1, Math.round(DPR * (word || depth > .62 ? 1.5 : 1)));
        const x0 = sx | 0, y0 = sy | 0;
        if (x0 < 1 || y0 < 1 || x0 >= BW - 2 || y0 >= BH - 2) continue;
        for (let oy = 0; oy < size; oy++) for (let ox = 0; ox < size; ox++) {
          const o = ((y0 + oy) * BW + x0 + ox) * 4;
          buf[o] += r; buf[o + 1] += g; buf[o + 2] += bl; buf[o + 3] = 255;
        }
      }
      pctx.putImageData(img, 0, 0);
      ctx.globalCompositeOperation = 'source-over'; ctx.clearRect(0, 0, BW, BH);
      // a soft glow: the same dots, small and blurred by scaling, laid over themselves
      hctx.clearRect(0, 0, halo.width, halo.height); hctx.imageSmoothingQuality = 'high';
      hctx.drawImage(page, 0, 0, halo.width, halo.height);
      ctx.imageSmoothingQuality = 'high';
      ctx.globalCompositeOperation = 'lighter';
      ctx.globalAlpha = 1; ctx.drawImage(halo, 0, 0, BW, BH);
      if (word) { ctx.globalAlpha = .55; ctx.drawImage(halo, 0, 0, BW, BH); }
      ctx.globalAlpha = 1; ctx.drawImage(page, 0, 0);
      requestAnimationFrame(frame);
    }
    
    form.addEventListener('submit', e => {
      e.preventDefault();
      const text = field.value.trim().toUpperCase();
      if (!text) return home();
      if (word && text !== last) { home(); setTimeout(() => shape(text), calm.matches ? 0 : 650); } else shape(text);
    });
    field.addEventListener('input', () => {
      const clean = field.value.replace(/[^A-Za-z0-9 ]/g, '').slice(0, 12);
      if (clean !== field.value) field.value = clean;
      if (!clean.trim() && word) home();
      light();
    });
    const measure = document.createElement('canvas').getContext('2d');
    measure.font = '600 20px system-ui, sans-serif';
    function light() {
      const upto = field.value.slice(0, field.selectionStart ?? field.value.length).toUpperCase();
      field.parentNode.style.setProperty('--x', Math.min(field.clientWidth - 8, measure.measureText(upto).width * 1.06 + 4) + 'px');
    }
    for (const type of ['focus', 'keyup', 'click']) field.addEventListener(type, light);
    sky.addEventListener('pointermove', e => { const b = root.getBoundingClientRect(); ptr = { x: e.clientX - b.left, y: e.clientY - b.top }; });
    sky.addEventListener('pointerleave', () => { ptr = null; });
    sky.addEventListener('pointerup', e => { if (e.pointerType !== 'mouse') ptr = null; });
    
    new ResizeObserver(() => setup()).observe(root);
    setup();
    requestAnimationFrame(frame);
    })();

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

Tilda, Webflow, WordPress

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

Tilda

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

Webflow

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

WordPress

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

Ещё в разделе «Частицы и игры»

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