Кот за курсором

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

Двигайте мышью, кликните по полу, задержите точку у него на голове.

Скачать

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

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

SPRINGstiffness 60, damping 11

Насколько охотно кот гонится. Меньшая жёсткость делает кота ленивее.

GRAVITY, JUMP2200, 780

Скорость падения и сила прыжка в пикселях в секунду.

SIZE1

Размер кота.

FURcolors

Цвета шерсти, живота и ушей. Попробуйте серый или чёрный.

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

Для страницы 404, первого экрана лендинга или пустого состояния. Каждый блок .cat-room получает своего кота.

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

  1. CSS

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

    .demo { width: min(560px, 94vw); text-align: center; }
    .demo p { margin: 14px 0 0; color: #8D84A0; font-size: 14px; }
    
    .cat-room { position: relative; height: 360px; border-radius: 28px; overflow: hidden; cursor: none; touch-action: none;
      background: linear-gradient(#231C3A, #3A2B4E); box-shadow: inset 0 0 0 1px rgba(255,255,255,.08); }
    .cat-room canvas { position: absolute; inset: 0; width: 100%; height: 100%; display: block; }
    .cat-room:focus-visible { outline: 2px solid #FFB45C; outline-offset: 3px; }
    @media (hover: none) { .cat-room { cursor: auto; } }
  2. HTML

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

    <div class="demo">
      <div class="cat-room" tabindex="0" role="application" aria-label="Cat that chases the dot. Use the arrow keys to move the dot and Space to click"><canvas></canvas></div>
      <p>Move the dot, click the floor, pet the head</p>
    </div>
  3. JavaScript

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

    (() => {
    const SPRING = { stiffness: 60, damping: 11 };   // how the cat chases the dot
    const GRAVITY = 2200, JUMP = 780;                 // px/s² and px/s
    const SIZE = 1;                                   // cat scale
    const FUR = { top: '#FFB45C', side: '#EE8339', dark: '#D9772F', stripe: 'rgba(214,108,40,.7)', belly: '#FFE6C4', paw: '#FFF1DF', ear: '#FFB3C1' };
    const reduce = matchMedia('(prefers-reduced-motion: reduce)').matches;
    const clamp = (x, lo = 0, hi = 1) => Math.min(hi, Math.max(lo, x));
    const TAU = Math.PI * 2;
    
    document.querySelectorAll('.cat-room').forEach(room => {
      const canvas = room.querySelector('canvas'), g = canvas.getContext('2d');
      let W = 0, H = 0, FLOOR = 0;
      const cat = { x: 0, y: 0, vx: 0, vy: 0, dir: 1, stride: 0, onGround: true, crouch: 0, crouchLeft: 0, pending: null, happy: 0, pet: 0, blink: 0, nextBlink: 2 };
      const mouse = { x: 0, y: 0, inside: false };
      const hearts = [], dust = [];
    
      function resize() {                               // crisp on retina, sized by CSS
        const r = room.getBoundingClientRect(), dpr = Math.min(devicePixelRatio || 1, 2);
        W = r.width; H = r.height; FLOOR = H - 40;
        canvas.width = W * dpr; canvas.height = H * dpr; g.setTransform(dpr, 0, 0, dpr, 0, 0);
        if (!cat.x) { cat.x = W / 2; cat.y = FLOOR; mouse.x = W / 2; mouse.y = FLOOR - 60; }
      }
      new ResizeObserver(resize).observe(room); resize();
    
      const EDGE = 96 * SIZE;                          // keeps the head inside the room
      const head = () => ({ x: cat.x + cat.dir * 44 * SIZE, y: cat.y - 80 * SIZE });
      const catTop = () => cat.y - 120 * SIZE;
    
      // ── input
      const local = e => { const r = room.getBoundingClientRect(); return { x: e.clientX - r.left, y: e.clientY - r.top }; };
      room.addEventListener('pointermove', e => {
        Object.assign(mouse, local(e), { inside: true });
      });
      room.addEventListener('pointerleave', () => { mouse.inside = false; });
      room.addEventListener('pointerdown', e => {
        const p = local(e); Object.assign(mouse, p, { inside: true });
        const h = head();
        if (Math.hypot(p.x - cat.x, p.y - (cat.y - 50 * SIZE)) < 70 * SIZE) {   // tapped the cat
          if (cat.onGround) { launch(-620, 0); tell('happy'); }
          burst(h.x, h.y - 20, 6);
        } else if (cat.onGround) {                                               // pounce on the spot
          const dx = p.x - cat.x; cat.dir = Math.sign(dx) || cat.dir;
          if (crouchThen(-560, clamp(dx * 2.2, -700, 700), .12)) tell('pounce');
        }
      });
    
      // the arrow keys move the dot, Space or Enter does what a click does
      room.addEventListener('keydown', e => {
        const step = e.shiftKey ? 56 : 24;
        const move = { ArrowLeft: [-step, 0], ArrowRight: [step, 0], ArrowUp: [0, -step], ArrowDown: [0, step] }[e.key];
        if (move) {
          mouse.x = clamp(mouse.x + move[0], 0, W); mouse.y = clamp(mouse.y + move[1], 0, H); mouse.inside = true;
        } else if (e.key === ' ' || e.key === 'Enter') {
          room.dispatchEvent(new PointerEvent('pointerdown', { clientX: room.getBoundingClientRect().left + mouse.x, clientY: room.getBoundingClientRect().top + mouse.y, bubbles: false }));
        } else return;
        e.preventDefault();
      });
      room.addEventListener('focus', () => { mouse.inside = true; });
    
      // tell the page what the cat is doing, so you can react to it
      const tell = action => room.dispatchEvent(new CustomEvent('cat', { detail: { action } }));
    
      function launch(vy, vx) { cat.vy = vy; cat.vx += vx; cat.onGround = false; }
      function crouchThen(vy, vx, time) { if (cat.pending) return false; cat.pending = { vy, vx }; cat.crouchLeft = time; return true; }
      function burst(x, y, n) { if (reduce) return; for (let i = 0; i < n; i++) hearts.push({ x: x + (Math.random() - .5) * 50, y, age: -i * .08, drift: Math.random() * TAU }); }
    
      // ── physics, same lines as in the video
      function update(dt) {
        const pull = (mouse.inside ? clamp(mouse.x, EDGE, W - EDGE) : W / 2) - cat.x;
        const hd = head();                                  // the dot is close to the head, so the cat stops and enjoys it
        const onHead = mouse.inside && cat.onGround && Math.hypot(mouse.x - hd.x, mouse.y - hd.y) < 62 * SIZE;
        const holding = cat.crouchLeft > 0 || onHead || cat.pet > .2;
        cat.vx += (SPRING.stiffness * (holding ? 0 : pull) - SPRING.damping * cat.vx) * dt;
        if (!onHead && mouse.inside && mouse.y < catTop() && cat.onGround && Math.abs(pull) < 90) { if (crouchThen(-JUMP, 0, .16)) tell('jump'); }
        cat.vy += GRAVITY * dt;
        cat.x += cat.vx * dt; cat.y += cat.vy * dt;
    
        if (cat.y >= FLOOR) {
          if (!cat.onGround && cat.vy > 500) { cat.land = .12; puff(); }
          cat.y = FLOOR; cat.vy = 0; cat.onGround = true;
        }
        cat.x = clamp(cat.x, EDGE, W - EDGE);
        cat.stride += Math.abs(cat.vx) * dt * 0.05;
        if (Math.abs(cat.vx) > 18) cat.dir = Math.sign(cat.vx);
        else if (mouse.inside && Math.abs(mouse.x - cat.x) > 20) cat.dir = mouse.x > cat.x ? 1 : -1;
    
        // crouch before any jump, then spring off
        if (cat.crouchLeft > 0) { cat.crouchLeft -= dt; if (cat.crouchLeft <= 0 && cat.pending) { launch(cat.pending.vy, cat.pending.vx); cat.pending = null; } }
        cat.crouch += ((cat.crouchLeft > 0 ? 1 : 0) - cat.crouch) * Math.min(1, dt * 18);
        cat.land = Math.max(0, (cat.land || 0) - dt);
    
        // petting: the dot rests on the head
        const h = hd, wasPurring = cat.pet > .25;
        cat.pet = onHead ? cat.pet + dt : Math.max(0, cat.pet - dt * 2);
        if (cat.pet > .25 && !wasPurring) tell('purr');
        if (cat.pet > .25 && Math.random() < dt * 5) burst(h.x, h.y - 30, 1);
        cat.happy += ((cat.pet > .25 || hearts.length > 0 ? 1 : 0) - cat.happy) * Math.min(1, dt * 8);
    
        cat.nextBlink -= dt; if (cat.nextBlink < 0) { cat.blink = .14; cat.nextBlink = 2 + Math.random() * 3; }
        cat.blink = Math.max(0, cat.blink - dt);
    
        hearts.forEach(p => { p.age += dt; }); while (hearts.length && hearts[0].age > 1.2) hearts.shift();
        dust.forEach(p => { p.age += dt; p.x += p.vx * dt; }); while (dust.length && dust[0].age > .5) dust.shift();
        if (!reduce && cat.onGround && Math.abs(cat.vx) > 160 && Math.random() < dt * 20) dust.push({ x: cat.x - cat.dir * 40, vx: -cat.dir * 40, age: 0 });
      }
      function puff() { if (reduce) return; for (let i = 0; i < 6; i++) dust.push({ x: cat.x + (i - 2.5) * 12, vx: (i - 2.5) * 40, age: 0 }); }
    
      // ── drawing
      const t0 = performance.now();
      function frame(now) {
        const t = (now - t0) / 1000;
        update(Math.min(1 / 30, (now - (frame.last || now)) / 1000)); frame.last = now;
        g.clearRect(0, 0, W, H);
    
        const glow = g.createRadialGradient(cat.x, FLOOR - 60, 10, cat.x, FLOOR - 60, 240);
        glow.addColorStop(0, 'rgba(255,170,90,.2)'); glow.addColorStop(1, 'rgba(255,170,90,0)');
        g.fillStyle = glow; g.fillRect(0, 0, W, H);
        const floor = g.createLinearGradient(0, FLOOR - 14, 0, H);
        floor.addColorStop(0, '#4A3426'); floor.addColorStop(1, '#231710');
        g.fillStyle = floor; g.fillRect(0, FLOOR - 14, W, H);
        g.fillStyle = 'rgba(255,255,255,.06)'; g.fillRect(0, FLOOR - 14, W, 2);
    
        dust.forEach(p => { const k = p.age / .5; g.fillStyle = `rgba(230,200,170,${.28 * (1 - k)})`; g.beginPath(); g.arc(p.x, FLOOR - 6 - k * 14, 4 + k * 8, 0, TAU); g.fill(); });
    
        const speed = clamp(Math.abs(cat.vx) / 260), air = cat.onGround ? 0 : 1;
        const squash = reduce ? 1 : cat.land > 0 ? .84 : air ? clamp(1 + Math.abs(cat.vy) / 3000, 1, 1.2) : 1 - cat.crouch * .08;
        const h = head();
        drawCat(g, {
          x: cat.x, y: cat.y, dir: cat.dir, stride: cat.stride, speed, air, t, vy: cat.vy, squash,
          crouch: cat.crouch, blink: cat.blink > 0 ? 1 : 0, happy: cat.happy, purr: cat.pet > .25,
          lookX: clamp((mouse.x - h.x) / 160, -1, 1) * cat.dir, lookY: clamp((mouse.y - h.y) / 160, -1, 1), floorY: FLOOR,
        });
    
        hearts.forEach(p => {
          if (p.age < 0) return; const k = p.age / 1.2, s = .6 + .4 * Math.min(1, p.age * 6);
          g.save(); g.translate(p.x + Math.sin(p.age * 5 + p.drift) * 6, p.y - p.age * 70); g.scale(s, s); g.globalAlpha = 1 - k;
          g.fillStyle = p.drift > Math.PI ? '#FF7AA0' : '#FFB3C8';
          g.beginPath(); g.moveTo(0, 7); g.bezierCurveTo(-10, 0, -7, -9, 0, -4); g.bezierCurveTo(7, -9, 10, 0, 0, 7); g.fill(); g.restore();
        });
    
        if (cat.pet > .25) {                                                 // purring
          g.fillStyle = 'rgba(255,241,223,.9)'; g.font = '700 14px system-ui, sans-serif'; g.textAlign = 'center';
          g.fillText('prrr', h.x + cat.dir * 70, h.y - 30 + Math.sin(t * 20) * 1.5);
        }
    
        if (mouse.inside && matchMedia('(hover: hover)').matches) {           // the laser dot and the pointer
          g.fillStyle = 'rgba(255,40,40,.35)'; g.beginPath(); g.arc(mouse.x, mouse.y, 12, 0, TAU); g.fill();
          g.fillStyle = '#FF3B3B'; g.beginPath(); g.arc(mouse.x, mouse.y, 4, 0, TAU); g.fill();
          g.save(); g.translate(mouse.x, mouse.y); g.scale(1.25, 1.25);
          g.beginPath(); g.moveTo(0, 0); g.lineTo(0, 17); g.lineTo(4.5, 13); g.lineTo(7.5, 20); g.lineTo(10, 19); g.lineTo(7, 12); g.lineTo(12.5, 12); g.closePath();
          g.fillStyle = '#fff'; g.fill(); g.strokeStyle = '#000'; g.lineWidth = 1.3; g.stroke(); g.restore();
        }
        requestAnimationFrame(frame);
      }
      requestAnimationFrame(frame);
    });
    
    function drawCat(g, s) {
      const { x, y, dir, stride, speed, crouch, blink, happy, lookX, lookY, air, squash, t, purr, floorY } = s;
      // shadow stays on the floor and shrinks while the cat is in the air
      const lift = clamp((floorY - y) / 200);
      g.fillStyle = `rgba(0,0,0,${.35 * (1 - lift * .7)})`;
      g.beginPath(); g.ellipse(x, floorY + 2, 58 * SIZE * (1 - lift * .5), 8 * SIZE * (1 - lift * .5), 0, 0, TAU); g.fill();
    
      g.save(); g.translate(x + (purr ? Math.sin(t * 60) * .8 : 0), y);
      g.scale(dir * SIZE / Math.sqrt(squash), SIZE * squash);
      const bob = speed > .05 && !air ? Math.abs(Math.sin(stride * Math.PI * 2)) * 4 * speed : 0;
      const wiggle = Math.sin(t * 38) * 4 * crouch;
    
      const leg = (lx, phase, far) => {
        const a = air ? (lx > 0 ? -.7 : .8) : Math.sin((stride + phase) * TAU) * .75 * speed;
        g.save(); g.translate(lx, -20 + crouch * 6); g.rotate(a);
        roundRect(g, -8, -4, 16, 26 - crouch * 8, 8); g.fillStyle = far ? FUR.dark : FUR.top; g.fill();
        g.beginPath(); g.ellipse(0, 22 - crouch * 8, 9, 5, 0, 0, TAU); g.fillStyle = far ? '#EBD2B4' : FUR.paw; g.fill();
        g.restore();
      };
    
      // tail
      const sway = Math.sin(t * 3.2) * .5 + Math.sin(t * 7) * .12 * speed;
      g.save(); g.translate(-50 + wiggle, -38 + crouch * 10 - bob);
      const tipX = -30 - air * 25 - Math.cos(sway) * 10 + sway * 26, tipY = -62 + air * 40 + crouch * 30;
      const tail = g.createLinearGradient(0, 0, -40, -70); tail.addColorStop(0, FUR.side); tail.addColorStop(1, FUR.top);
      g.strokeStyle = tail; g.lineWidth = 15; g.lineCap = 'round';
      g.beginPath(); g.moveTo(0, 0); g.bezierCurveTo(-34, -6, -38 + sway * 30, -40, tipX, tipY); g.stroke();
      g.strokeStyle = FUR.paw; g.beginPath(); g.moveTo(tipX - 2, tipY + 4); g.lineTo(tipX, tipY); g.stroke();
      g.restore();
    
      leg(-34 + wiggle, .5, true); leg(24, 0, true);
    
      // body
      g.save(); g.translate(wiggle * .6, -bob + crouch * 10); g.rotate(-crouch * .12 + (air ? -s.vy / 9000 : 0));
      const body = g.createLinearGradient(0, -72, 0, -8); body.addColorStop(0, FUR.top); body.addColorStop(1, FUR.side);
      g.fillStyle = body; g.beginPath(); g.ellipse(0, -40, 54, 32, 0, 0, TAU); g.fill();
      g.fillStyle = FUR.belly; g.beginPath(); g.ellipse(10, -24, 32, 15, 0, 0, TAU); g.fill();
      g.strokeStyle = FUR.stripe; g.lineWidth = 5; g.lineCap = 'round';
      for (const [sx, len] of [[-26, 18], [-10, 22], [6, 18]]) { g.beginPath(); g.moveTo(sx, -70); g.quadraticCurveTo(sx + 5, -62, sx, -70 + len); g.stroke(); }
      g.fillStyle = 'rgba(255,255,255,.28)'; g.beginPath(); g.ellipse(-10, -62, 26, 8, -.1, 0, TAU); g.fill();
      g.restore();
    
      leg(-20 + wiggle, 0, false); leg(38, .5, false);
    
      // head
      g.save(); g.translate(44, -76 - bob * .6 + crouch * 16); g.rotate(-crouch * .06 + lookY * .06);
      const ear = (ex, rot) => {
        g.save(); g.translate(ex, -26); g.rotate(rot + Math.sin(t * 1.7) * .03);
        g.fillStyle = '#F39245'; g.beginPath(); g.moveTo(-15, 8); g.quadraticCurveTo(-4, -34, 4, -30); g.quadraticCurveTo(16, 2, 15, 8); g.closePath(); g.fill();
        g.fillStyle = FUR.ear; g.beginPath(); g.moveTo(-7, 4); g.quadraticCurveTo(-2, -20, 3, -19); g.quadraticCurveTo(9, 0, 8, 4); g.closePath(); g.fill();
        g.restore();
      };
      ear(-18, -.28); ear(16, .22);
      const face = g.createRadialGradient(-8, -14, 6, 0, 0, 44); face.addColorStop(0, '#FFC377'); face.addColorStop(1, '#F08A3E');
      g.fillStyle = face; g.beginPath(); g.ellipse(0, 0, 38, 34, 0, 0, TAU); g.fill();
      g.strokeStyle = FUR.stripe; g.lineWidth = 4;
      for (const sx of [-8, 0, 8]) { g.beginPath(); g.moveTo(sx, -33); g.lineTo(sx, -24 + (sx ? 3 : 0)); g.stroke(); }
      g.fillStyle = FUR.paw; g.beginPath(); g.ellipse(6, 13, 22, 15, 0, 0, TAU); g.fill();
    
      for (const ex of [-12, 16]) {                    // eyes follow the dot, squint when happy
        g.save(); g.translate(ex, -4);
        if (happy > .5) { g.strokeStyle = '#2A1A12'; g.lineWidth = 3.4; g.beginPath(); g.arc(0, 3, 7, Math.PI * 1.15, Math.PI * 1.85); g.stroke(); }
        else {
          g.scale(1, 1 - blink * .9);
          g.fillStyle = '#2A1A12'; g.beginPath(); g.ellipse(lookX * 2.5, lookY * 2, 7, 9.5, 0, 0, TAU); g.fill();
          g.fillStyle = '#fff'; g.beginPath(); g.arc(lookX * 2.5 + 2.4, lookY * 2 - 3.4, 2.8, 0, TAU); g.fill();
          g.beginPath(); g.arc(lookX * 2.5 - 2, lookY * 2 + 3, 1.2, 0, TAU); g.fill();
        }
        g.restore();
      }
      g.fillStyle = `rgba(255,120,150,${.35 + .4 * happy})`;
      g.beginPath(); g.ellipse(-20, 12, 7, 4.5, 0, 0, TAU); g.fill(); g.beginPath(); g.ellipse(28, 12, 7, 4.5, 0, 0, TAU); g.fill();
      g.fillStyle = '#FF8FA3'; g.beginPath(); g.moveTo(2, 7); g.lineTo(10, 7); g.lineTo(6, 12); g.closePath(); g.fill();
      g.strokeStyle = '#2A1A12'; g.lineWidth = 1.8;
      g.beginPath(); g.moveTo(6, 12); g.quadraticCurveTo(3, 18, -1, 16); g.moveTo(6, 12); g.quadraticCurveTo(9, 18, 13, 16); g.stroke();
      g.strokeStyle = 'rgba(255,255,255,.8)'; g.lineWidth = 1.2;
      for (const [a, b] of [[-1, 10], [1, 14], [-1, 17]]) { g.beginPath(); g.moveTo(-12, 14 + a); g.lineTo(-36, b); g.moveTo(24, 14 + a); g.lineTo(46, b); g.stroke(); }
      g.restore();
      g.restore();
    }
    
    function roundRect(g, x, y, w, h, r) { g.beginPath(); g.roundRect(x, y, w, h, r); }
    })();

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

Tilda, Webflow, WordPress

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

Tilda

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

Webflow

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

WordPress

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

Ещё в разделе «Живые персонажи»

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