Skip to content

176 web animation techniques, each a live demo with plain settings and a ready-made prompt for your AI assistant. No dependencies, no build step.

33.0 KB
Raw Blame
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Parallax 3D Tilt — Animation Handbook</title>
  <meta name="description" content="A card tilts toward your pointer, and a light slides over it. Best for cards.">
  <link rel="canonical" href="https://matinmonshizadeh.github.io/animation-handbook/animations/06-3d-advanced/parallax-3d-tilt/">
  <link rel="icon" type="image/png" sizes="96x96" href="../../../favicon.png">
  <link rel="icon" type="image/svg+xml" href="../../../favicon.svg">
  <link rel="apple-touch-icon" href="../../../apple-touch-icon.png">
  <meta property="og:type" content="article">
  <meta property="og:site_name" content="Animation Handbook">
  <meta property="og:title" content="Parallax 3D Tilt — Animation Handbook">
  <meta property="og:description" content="A card tilts toward your pointer, and a light slides over it. Best for cards.">
  <meta property="og:url" content="https://matinmonshizadeh.github.io/animation-handbook/animations/06-3d-advanced/parallax-3d-tilt/">
  <meta property="og:image" content="https://matinmonshizadeh.github.io/animation-handbook/og-image.png">
  <meta name="twitter:card" content="summary_large_image">
  <meta name="twitter:title" content="Parallax 3D Tilt — Animation Handbook">
  <meta name="twitter:description" content="A card tilts toward your pointer, and a light slides over it. Best for cards.">
  <meta name="twitter:image" content="https://matinmonshizadeh.github.io/animation-handbook/og-image.png">
  <script type="application/ld+json">{"@context": "https://schema.org", "@type": "TechArticle", "headline": "Parallax 3D Tilt", "name": "Parallax 3D Tilt", "description": "A card tilts toward your pointer, and a light slides over it. Best for cards.", "url": "https://matinmonshizadeh.github.io/animation-handbook/animations/06-3d-advanced/parallax-3d-tilt/", "inLanguage": "en", "articleSection": "3D & Advanced", "isPartOf": {"@type": "WebSite", "name": "Animation Handbook", "url": "https://matinmonshizadeh.github.io/animation-handbook/"}, "author": {"@type": "Person", "name": "matinmonshizadeh"}, "keywords": "web animation, CSS animation, 3D & Advanced, Parallax 3D Tilt"}</script>
  <style>
    :root{--ui-accent:#3fd6c4;--perspective:1000px;--reset-dur:400ms;--k-cross:#3fd6c4;--k-light:#ffd166}
    *,*::before,*::after{box-sizing:border-box;margin:0;padding:0}
    .stage{position:relative;display:flex;align-items:center;justify-content:center;background:#060a10;perspective:var(--perspective)}
    /* Card */
    .tilt-card{
      width:clamp(240px,40%,340px);height:min(240px,86%);
      border-radius:16px;position:relative;overflow:hidden;overflow:clip;
      background:linear-gradient(135deg,#0d2040,#1a3060);
      border:1px solid rgba(255,255,255,.15);
      box-shadow:0 20px 60px rgba(0,0,0,.6);
      /* The overflow clip above is overflow:hidden first, then overflow:clip where supported (clip leaves no scroll box for a drag to
         move). The card is not a preserve-3d container, which hidden would flatten anyway, so the depth layers get their own local
         perspective instead. The card's own rotation is projected by the perspective on .stage, never by a perspective() here. */
      perspective:var(--perspective);
      transform:rotateX(0deg) rotateY(0deg) scale(1);
      transition:transform var(--reset-dur) ease;
      cursor:pointer;touch-action:none;
      will-change:transform
    }
    .tilt-card.active{transition:none}
    /* Keyboard focus: the ring goes around the card, on the dark stage */
    .hb-page .stage .tilt-card:focus-visible{outline-offset:4px}
    /* The light is one fixed gradient on a layer of its own, twice as wide as the card's diagonal (--shine-d, set by the script)
       and centred on the card's top left corner. The script moves it to the pointer with translate() and sizes it with scale(),
       so following the pointer never repaints the card. The card clips it. */
    .card-shine{
      position:absolute;left:0;top:0;width:var(--shine-d,0);height:var(--shine-d,0);
      margin:calc(var(--shine-d,0px) / -2) 0 0 calc(var(--shine-d,0px) / -2);
      background:radial-gradient(circle closest-side,rgba(255,255,255,.18) 0%,transparent 65%);
      opacity:0;pointer-events:none;transition:opacity .3s;will-change:transform
    }
    .card-content{position:relative;z-index:1;height:100%;padding:28px;display:flex;flex-direction:column;justify-content:flex-end;gap:8px}
    .card-over{font-size:11px;font-weight:600;letter-spacing:2px;text-transform:uppercase;color:rgba(255,255,255,.7)}
    .card-h{font-size:clamp(18px,2.5vw,26px);font-weight:700;color:#fff;line-height:1.2}
    .card-sub{font-size:13px;color:rgba(255,255,255,.9);line-height:1.6;max-width:240px;text-wrap:pretty}
    /* Depth layers for extra parallax within card */
    .float-orb{position:absolute;border-radius:50%;pointer-events:none;will-change:transform}
    .orb1{width:120px;height:120px;background:rgba(88,166,255,.3);top:-30px;right:-20px;filter:blur(20px);transform:translateZ(20px)}
    .orb2{width:80px;height:80px;background:rgba(210,168,255,.2);bottom:20px;right:30px;filter:blur(12px);transform:translateZ(30px)}
    /* The card snaps flat when the pointer leaves instead of easing back */
    @media(prefers-reduced-motion:reduce){.tilt-card{transition:none!important}.card-shine{transition:none!important}}
    /* See inside and Compare, drawn from tilt()'s own numbers. In See inside a cross and a ring sit on the card at the pointer's spot,
       a dashed box marks where the card lies flat, and captions stand beside the card (above and below it on phones). In Compare the
       stage is two columns: a copy that never tilts, then the real card, each with an arrow for the pointer (a ghost on the copy). */
    .card-copy,.views,.in-cross,.in-ring,.in-only,.cmp-only{display:none}
    .card-copy{pointer-events:none;cursor:default;touch-action:auto;transition:none}
    .glow1,.glow2{position:absolute;border-radius:50%;pointer-events:none} /* the copy's glows: soft gradients, so no blur is doubled */
    .glow1{width:200px;height:200px;top:-70px;right:-60px;background:radial-gradient(circle closest-side,rgba(88,166,255,.3),rgba(88,166,255,.28) 30%,rgba(88,166,255,.15) 60%,transparent)}
    .glow2{width:140px;height:140px;bottom:-10px;right:0;background:radial-gradient(circle closest-side,rgba(210,168,255,.2),rgba(210,168,255,.19) 35%,rgba(210,168,255,.1) 58%,transparent)}
    .in-cross{position:absolute;left:-12px;top:-12px;width:24px;height:24px;z-index:3;pointer-events:none;color:var(--k-cross)}
    .in-ring{position:absolute;left:0;top:0;width:48px;height:48px;translate:-50% -50%;border:2px dashed var(--k-light);border-radius:50%;z-index:3;pointer-events:none}
    .views{position:absolute;inset:0;pointer-events:none}
    .views [hidden],.tilt-card [hidden]{display:none!important}
    .in-flat{position:absolute;border:2px dashed #f4f4f2;border-radius:calc(16px*var(--fit,1))}
    .in-left,.in-right{position:absolute;top:10px;flex-direction:column;gap:8px;max-width:var(--col)}
    .in-left{left:10px;bottom:10px;justify-content:flex-end;align-items:flex-start}
    .in-right{right:10px;align-items:flex-end}
    .in-top{display:flex;flex-direction:column;gap:6px;align-items:flex-start;width:100%}
    .in-top svg{width:100%;max-width:160px;height:auto;overflow:visible}
    .lbl{width:max-content;max-width:100%;padding:3px 8px;border-radius:6px;background:rgba(6,10,16,.92);color:#f4f4f2;font:600 13px/1.3 var(--hb-font)}
    .k-flat::before,.k-ring::before,.k-cross::before{content:"";display:inline-block;vertical-align:middle;margin-right:6px}
    .k-flat::before{width:14px;border-top:2px dashed #f4f4f2}
    .k-ring::before{width:10px;height:10px;border:2px dashed var(--k-light);border-radius:50%}
    .k-cross::before{content:"+";font-weight:800;color:var(--k-cross);vertical-align:baseline}
    .cmp-half{position:absolute;top:0;bottom:0;width:50%;overflow:hidden}
    .cmp-half.h2{left:50%}
    .cmp-half.h2::before{content:"";position:absolute;left:0;top:10%;bottom:10%;width:1px;background:rgba(244,244,242,.16)}
    .cmp-l{position:absolute;left:10px;top:10px}
    .ptr{position:absolute;left:0;top:0;width:15px;height:23px;overflow:visible}
    .ghost{opacity:.65}
    .stage[data-hb-mode="inside"] .views,.stage[data-hb-mode="compare"] .views,.stage[data-hb-mode="inside"] .in-only,.stage[data-hb-mode="compare"] .cmp-only,
    .stage[data-hb-mode="inside"] .in-cross,.stage[data-hb-mode="inside"] .in-ring,.stage[data-hb-mode="compare"] .card-copy{display:block}
    .stage[data-hb-mode="inside"] .in-left,.stage[data-hb-mode="inside"] .in-right{display:flex}
    .stage[data-hb-mode="inside"] .views.no-top .in-left{display:none}
    .stage[data-hb-mode="inside"] .tilt-card,.stage[data-hb-mode="compare"] .tilt-card{scale:var(--fit,1);will-change:auto}
    .stage[data-hb-mode="compare"]{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));grid-template-rows:minmax(0,1fr);place-items:center;perspective-origin:75% calc(50% + var(--dy,0px))}
    .stage[data-hb-mode="compare"] .tilt-card{width:clamp(240px,80%,340px);translate:0 var(--dy,0px)}
    .stage[data-hb-mode="compare"].real-ptr .pretend{display:none}
    @media(max-width:600px){
      .stage[data-hb-mode="inside"] .in-left,.stage[data-hb-mode="inside"] .in-light,.stage[data-hb-mode="inside"] .more{display:none}
      .stage[data-hb-mode="inside"] .in-right{display:contents}
      .stage[data-hb-mode="inside"] .in-right .lbl{position:absolute;left:50%;translate:-50% 0;white-space:nowrap}
      .stage[data-hb-mode="inside"] .k-cross{top:var(--cap-y)}
      .stage[data-hb-mode="inside"] .k-flat{bottom:var(--cap-y)}
    }
  </style>
  <link rel="stylesheet" href="../../../assets/css/demo-page.css?v=11">
  <script src="../../../assets/js/demo-page.js?v=11" defer></script>
</head>
<body class="hb" data-hb-kind="do" data-hb-autoplay>
<nav class="hb-bar" aria-label="Animation Handbook">
  <a class="hb-home" href="../../../"><svg class="hb-mark" viewBox="0 0 32 32" aria-hidden="true"><g class="g"><circle cx="11.16" cy="20.84" r="6.1"/><circle cx="15.12" cy="16.88" r="6.1"/><circle cx="18.51" cy="13.49" r="6.1"/></g><circle class="b" cx="21.2" cy="10.8" r="6.6"/></svg><span>Animation Handbook</span></a>
  <span class="hb-pager"><a href="../scroll-driven-3d-rotation/" rel="prev" aria-label="Previous: Scroll-Driven 3D Rotation"><svg class="hb-ic" viewBox="0 0 24 24" aria-hidden="true"><path d="m15 18-6-6 6-6"/></svg><span><span class="hb-dir">Previous: </span>Scroll-Driven 3D Rotation</span></a><a href="../canvas-particle-effect/" rel="next" aria-label="Next: Canvas Particle Effect"><span><span class="hb-dir">Next: </span>Canvas Particle Effect</span><svg class="hb-ic" viewBox="0 0 24 24" aria-hidden="true"><path d="m9 18 6-6-6-6"/></svg></a></span>
  <a class="hb-star" href="https://github.com/matinmonshizadeh/animation-handbook" target="_blank" rel="noopener" aria-label="Star on GitHub"><svg class="hb-ic" viewBox="0 0 24 24" aria-hidden="true"><path d="M12 3l2.7 5.6 6.1.9-4.4 4.3 1 6.1L12 17l-5.4 2.9 1-6.1-4.4-4.3 6.1-.9z"/></svg><span>Star on GitHub</span></a>
</nav>
<main class="hb-page">
  <header class="hb-head">
    <p class="hb-cat">06.03 · 3D &amp; Advanced</p>
    <h1>Parallax 3D Tilt</h1>
    <p class="hb-lede">A card tilts toward your pointer, and a light slides over it. Best for cards.</p>
  </header>

  <section class="hb-step hb-watch" aria-labelledby="hb-watch-title">
    <div class="hb-step-head">
      <span class="hb-num" aria-hidden="true">1</span>
      <div><h2 id="hb-watch-title">Hover it</h2><p>Move your pointer over the card, drag a finger across it (or Tab to it and use the arrow keys), or press Show me.</p></div>
    </div>
    <div class="seg hb-modes" role="group" aria-label="What the box shows" data-hb-modes>
      <button type="button" data-hb-mode="normal" class="on" aria-pressed="true">Normal</button>
      <button type="button" data-hb-mode="inside" aria-pressed="false">See inside</button>
      <button type="button" data-hb-mode="compare" aria-pressed="false">Compare</button>
    </div>
    <div class="stage hb-dots">
      <div class="tilt-card card-copy" aria-hidden="true" inert>
        <div class="float-orb glow1"></div>
        <div class="float-orb glow2"></div>
        <div class="card-content">
          <div class="card-over">Feature card</div>
          <div class="card-h">Three-dimensional perspective</div>
          <div class="card-sub">The card leans toward your pointer, and the light follows it.</div>
        </div>
      </div>
      <div class="tilt-card" id="card" tabindex="0" role="group" aria-label="Feature card. Press the arrow keys to tilt it.">
        <div class="card-shine" id="shine"></div>
        <div class="float-orb orb1" id="orb1"></div>
        <div class="float-orb orb2" id="orb2"></div>
        <div class="card-content">
          <div class="card-over">Feature card</div>
          <div class="card-h">Three-dimensional perspective</div>
          <div class="card-sub">The card leans toward your pointer, and the light follows it.</div>
        </div>
        <svg class="in-cross" viewBox="-12 -12 24 24" fill="none" stroke-linecap="round" aria-hidden="true"><path d="M-8 0H8M0-8V8" stroke="#060a10" stroke-width="5"/><path d="M-8 0H8M0-8V8" stroke="currentColor" stroke-width="2.5"/></svg>
        <div class="in-ring" id="ring" aria-hidden="true"></div>
      </div>
      <div class="views" id="views" aria-hidden="true">
        <div class="in-flat in-only" id="flat"></div>
        <div class="in-left in-only"><div class="in-top">
          <svg viewBox="0 0 120 86" stroke="#f4f4f2" stroke-linecap="round"><line x1="20" y1="16" x2="100" y2="16" stroke-opacity=".4" stroke-width="3" stroke-dasharray="4 4"/><line id="sl1" stroke-opacity=".3"/><line id="sl2" stroke-opacity=".3"/><line id="bar" stroke-width="4"/><g id="eye" fill="none" stroke-width="1.5"><path d="M-9 0Q0-9 9 0Q0 9-9 0Z"/><circle r="3" fill="#f4f4f2" stroke="none"/></g></svg>
          <span class="lbl k-top" data-hb-caption>Seen from above: a nearer eye makes a deeper lean</span>
        </div></div>
        <div class="in-right in-only">
          <span class="lbl k-cross" id="cap-cross" data-hb-caption>The cross is the pointer<span class="more">: the card leans <span id="dir">toward</span> it</span></span>
          <span class="lbl k-ring in-light" id="cap-light" data-hb-caption>The light sits under the pointer</span>
          <span class="lbl k-flat" data-hb-caption>Dashed: where it lies flat</span>
        </div>
        <div class="cmp-half h1 cmp-only"><span class="lbl cmp-l" data-hb-caption>Stays flat</span><svg class="ptr ghost" id="ghost" viewBox="0 0 15 23"><path d="M0 0V19L5 14.5L8.5 22L11.5 20.7L8 13.3H14.5Z" fill="#f4f4f2" stroke="#060a10" stroke-width="1.5" stroke-linejoin="round"/></svg></div>
        <div class="cmp-half h2 cmp-only"><span class="lbl cmp-l" id="nm2" data-hb-caption>Tilts toward you</span><svg class="ptr pretend" id="pretend" viewBox="0 0 15 23"><path d="M0 0V19L5 14.5L8.5 22L11.5 20.7L8 13.3H14.5Z" fill="#f4f4f2" stroke="#060a10" stroke-width="1.5" stroke-linejoin="round"/></svg></div>
      </div>
    </div>
    <div class="hb-player">
      <button class="hb-play" type="button" id="btn-demo" data-hb-demo><svg class="hb-ic" viewBox="0 0 24 24" aria-hidden="true"><path d="M4.037 4.688a.495.495 0 0 1 .651-.651l16 6.5a.5.5 0 0 1-.063.947l-6.124 1.58a2 2 0 0 0-1.438 1.435l-1.579 6.126a.5.5 0 0 1-.947.063z"/></svg>Show me</button>
    </div>
    <div class="hb-mode-notes" aria-live="polite">
      <p data-hb-for="inside" hidden>Inside, the card leans toward the cross, your pointer, turning around its middle, and the light sits under it. Dashed: where it lies flat; point at the card, or press Show me.</p>
      <p data-hb-for="compare" hidden>Stays flat ignores the pointer, shown as a ghost, while Tilts toward you leans toward it and catches the light, like a real card. Point at the right card, or press Show me.</p>
    </div>
  </section>

  <section class="hb-step hb-try" aria-labelledby="hb-try-title">
    <div class="hb-step-head">
      <span class="hb-num" aria-hidden="true">2</span>
      <div><h2 id="hb-try-title">Try it</h2><p>Change a setting, then try it again or press Show me.</p></div>
    </div>
    <div class="hb-settings">
      <div class="hb-setting">
        <p class="hb-setting-name" id="tilt-lbl">Tilt amount</p>
        <div class="seg" id="tilt-seg" role="group" aria-labelledby="tilt-lbl">
          <button type="button" data-tilt="8" aria-pressed="false">Small</button>
          <button type="button" data-tilt="15" class="on" aria-pressed="true">Medium</button>
          <button type="button" data-tilt="25" aria-pressed="false">Large</button>
        </div>
        <p class="hb-hint">How far the card leans at its edges.</p>
      </div>
      <div class="hb-setting">
        <p class="hb-setting-name" id="depth-lbl">3D depth</p>
        <div class="seg" id="depth-seg" role="group" aria-labelledby="depth-lbl">
          <button type="button" data-px="1500" aria-pressed="false">Subtle</button>
          <button type="button" data-px="1000" class="on" aria-pressed="true">Medium</button>
          <button type="button" data-px="500" aria-pressed="false">Strong</button>
        </div>
        <p class="hb-hint">Strong looks closer and more dramatic.</p>
      </div>
      <div class="hb-setting">
        <label class="hb-switch-row"><span>Shine</span><input class="hb-switch" type="checkbox" role="switch" id="shine-tog" checked autocomplete="off"></label>
        <p class="hb-hint">A soft light follows the pointer across the card.</p>
      </div>
    </div>
    <details class="hb-options">
      <summary><span class="hb-more-label">More options</span><span class="hb-less">Fewer options</span><svg class="hb-ic" viewBox="0 0 24 24" aria-hidden="true"><path d="m6 9 6 6 6-6"/></svg></summary>
      <div class="hb-settings">
        <div class="hb-setting">
          <p class="hb-setting-name" id="return-lbl">Return speed</p>
          <div class="seg" id="return-seg" role="group" aria-labelledby="return-lbl">
            <button type="button" data-ms="650" aria-pressed="false">Slow</button>
            <button type="button" data-ms="400" class="on" aria-pressed="true">Normal</button>
            <button type="button" data-ms="250" aria-pressed="false">Fast</button>
          </div>
          <p class="hb-hint">How quickly the card settles flat again.</p>
        </div>
        <div class="hb-setting">
          <label class="hb-switch-row"><span>Tilts away from the pointer</span><input class="hb-switch" type="checkbox" role="switch" id="invert-tog" autocomplete="off"></label>
          <p class="hb-hint">Leans the other way, as if you pressed it.</p>
        </div>
        <div class="hb-setting">
          <label class="hb-switch-row"><span>Grows a little</span><input class="hb-switch" type="checkbox" role="switch" id="scale-tog" checked autocomplete="off"></label>
          <p class="hb-hint">Lifts the card slightly while it tilts.</p>
        </div>
      </div>
    </details>
  </section>

  <section class="hb-step hb-prompt-step" aria-labelledby="hb-prompt-title">
    <div class="hb-step-head">
      <span class="hb-num" aria-hidden="true">3</span>
      <div><h2 id="hb-prompt-title">Copy the prompt</h2><p>Paste it into an AI assistant such as ChatGPT, Claude or Cursor to build this in your own project.</p></div>
    </div>
    <div class="hb-card">
      <p class="hb-prompt">Add a 3D tilt to [the card you want to bring to life]. As the pointer moves over the card, rotate the card slightly around its horizontal and vertical axes according to where the pointer is, and give its container a 3D perspective so the tilt has depth. When the settings include it, move a soft light across the card with the pointer, as if it catches the light. On touch screens, dragging a finger across the card should tilt it the same way. When the pointer leaves, let the card settle back flat. If the visitor has reduced motion turned on, keep the card flat. Match the settings listed below.</p>
      <div class="hb-chips-box" hidden>
        <p class="hb-chips-title">Your settings</p>
        <ul class="hb-chips"></ul>
      </div>
      <div class="hb-copy-row">
        <button class="hb-copy" type="button"><svg class="hb-ic hb-i-copy" viewBox="0 0 24 24" aria-hidden="true"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg><svg class="hb-ic hb-i-done" viewBox="0 0 24 24" aria-hidden="true"><path d="M20 6 9 17l-5-5"/></svg><span class="hb-copy-label" aria-live="polite">Copy prompt</span></button>
        <p class="hb-hint">Replace the words in brackets with your own element. Your settings are added at the end.</p>
      </div>
    </div>
    <div class="hb-star-row"><p>Free and open source. If this helped, a star on GitHub helps other people find it.</p><a class="hb-star-btn" href="https://github.com/matinmonshizadeh/animation-handbook" target="_blank" rel="noopener"><svg class="hb-ic" viewBox="0 0 24 24" aria-hidden="true"><path d="M12 3l2.7 5.6 6.1.9-4.4 4.3 1 6.1L12 17l-5.4 2.9 1-6.1-4.4-4.3 6.1-.9z"/></svg>Star on GitHub</a></div>
  </section>

  <section class="hb-about" aria-labelledby="hb-what-title">
    <div class="hb-what">
      <h2 id="hb-what-title">What it is</h2>
      <div class="hb-what-text"><p>The full explanation is in <a href="README.md">README.md</a>.</p></div>
    </div>
    <div class="hb-fit">
      <h2>Good for</h2>
      <ul class="hb-tags hb-good"><li>Feature cards</li><li>Pricing cards</li><li>Portfolio tiles</li><li>Game cards</li></ul>
      <h3>Avoid on</h3>
      <ul class="hb-tags hb-avoid"><li>Text-heavy cards</li><li>Dense grids</li></ul>
    </div>
  </section>

  <section class="hb-related" aria-labelledby="hb-related-title" hidden>
    <h2 id="hb-related-title">Similar animations</h2>
    <div class="hb-rel-list"></div>
  </section>
</main>
<footer class="hb-foot"><span>Animation Handbook</span><a href="https://github.com/matinmonshizadeh/animation-handbook" target="_blank" rel="noopener">Source on GitHub</a><a href="#top">Back to top ↑</a></footer>
<script>
  const card=document.getElementById('card');
  const shine=document.getElementById('shine');
  const orb1=document.getElementById('orb1');
  const orb2=document.getElementById('orb2');
  const vars=document.documentElement.style;
  let maxTilt=15,invert=false,shineOn=true,scaleOn=true;
  let tiltX=0,tiltY=0; // the last x and y tilt() was given (0 after onLeave()): a Show me run starts from them
  let raf=0;           // the frame of a Show me run that is under way, 0 when there is none
  let shineD=0;        // the size given to the shine layer (--shine-d), set again only when the card's size changes
  // See inside and Compare. src is what moves the card now: '' nothing (in a mode the card rests in its pose), 'ptr' a mouse or
  // finger, 'key' the arrow keys, 'run' Show me. G holds the stage's and the card's sizes for Compare's arrows.
  const $=id=>document.getElementById(id);
  const stage=document.querySelector('.stage'),views=$('views'),ring=$('ring'),cross=card.querySelector('.in-cross');
  const flat=$('flat'),bar=$('bar'),sl1=$('sl1'),sl2=$('sl2'),eye=$('eye'),ghost=$('ghost'),pretend=$('pretend'),nm2=$('nm2');
  const capCross=$('cap-cross'),capLight=$('cap-light'),dirEl=$('dir');
  const noteIn=document.querySelector('[data-hb-for="inside"]'),noteCmp=document.querySelector('[data-hb-for="compare"]');
  const phoneMQ=matchMedia('(max-width:600px)');
  const PARK=[.38,-.38]; // the pretend pointer's resting spot in the modes: up and to the right of the card's middle
  const BAND=54;         // on phones See inside leaves this much room above and below the card for a caption
  let mode='normal',src='',persp=1000,eyeY=0,G={W:0,H:0,w:0,h:0,s:1,dy:0};
  function setSrc(v){src=v;stage.classList.toggle('real-ptr',v==='ptr')}

  // x and y run from -0.5 to 0.5 across the card. The pointer, a finger and Show me all move the card through this.
  // Only transform and opacity change: the card keeps its CSS shadow, which turns with it, and the light moves as a layer.
  function tilt(x,y,park){
    tiltX=x;tiltY=y;
    const inv=invert?-1:1;
    const rx=(-y*maxTilt*inv).toFixed(1);
    const ry=(x*maxTilt*inv).toFixed(1);
    const W=card.clientWidth,H=card.clientHeight; // the card's inner size, read before the transform is written so no frame forces a layout
    if(!park)card.classList.add('active'); // the pose leaves it off, so the card eases there over Return speed
    const scale=scaleOn?'scale(1.04)':'scale(1)';
    card.style.transform=`rotateX(${rx}deg) rotateY(${ry}deg) ${scale}`;
    if(shineOn){
      const D=2*Math.hypot(W,H);
      if(D!==shineD){shineD=D;card.style.setProperty('--shine-d',D+'px')}
      const R=Math.hypot((.5+Math.abs(x))*W,(.5+Math.abs(y))*H); // how far the light reaches: to the farthest corner
      shine.style.opacity='1';
      shine.style.transform=`translate(${(x+.5)*W}px,${(y+.5)*H}px) scale(${2*R/D})`;
    }
    // Subtle inner parallax
    orb1.style.transform=`translateZ(20px) translate(${-ry*.3}px,${rx*.3}px)`;
    orb2.style.transform=`translateZ(30px) translate(${-ry*.5}px,${rx*.5}px)`;
    if(mode==='inside'){
      cross.style.transform=ring.style.transform=`translate(${(x+.5)*W}px,${(y+.5)*H}px)`; // on the card, at the pointer's spot
      if(!phoneMQ.matches)drawBar(+ry);
    }else if(mode==='compare'){
      ghost.style.transform=pretend.style.transform=`translate(${G.W/4+x*G.w*G.s}px,${G.H/2+G.dy+y*G.h*G.s}px)`; // the same spot on each card
    }
  }
  // A finger dragged off the card keeps sending its moves to the card, so x and y are held to the card's edges.
  const edge=v=>Math.max(-.5,Math.min(.5,v));
  function onMove(e){
    const r=card.getBoundingClientRect();
    setSrc('ptr');
    tilt(edge((e.clientX-r.left)/r.width-.5),edge((e.clientY-r.top)/r.height-.5));
  }
  // Leaving flattens the card in Normal; in a mode it goes back to the pose
  function onLeave(){setSrc('');if(mode==='normal')flatten();else pose()}
  function pose(){card.classList.remove('active');tilt(PARK[0],PARK[1],true)}
  function flatten(){
    tiltX=tiltY=0;
    card.classList.remove('active');
    card.style.transform='rotateX(0deg) rotateY(0deg) scale(1)';
    shine.style.opacity='0';
    orb1.style.transform='translateZ(20px)';
    orb2.style.transform='translateZ(30px)';
  }

  // Show me: a pretend pointer circles the middle of the card one and a half times in three seconds, reaching 80% of the
  // way to the edges halfway through, and ends in the middle. It starts from where the card is; a second press starts anew.
  function showMe(){
    cancelAnimationFrame(raf);
    setSrc('run');
    const x0=tiltX,y0=tiltY;
    let t0=0;
    function step(now){
      if(!t0)t0=now;
      const p=Math.min(1,(now-t0)/3000);
      const r=.4*Math.sin(Math.PI*p),a=3*Math.PI*p;
      tilt(edge(x0*(1-p)+r*Math.cos(a)),edge(y0*(1-p)+r*Math.sin(a))); // held to the card, as a real pointer is
      if(p<1)raf=requestAnimationFrame(step);
      else{raf=0;onLeave()}
    }
    raf=requestAnimationFrame(step);
  }
  function stopRun(){cancelAnimationFrame(raf);raf=0;onLeave()}
  document.getElementById('btn-demo').addEventListener('click',showMe);
  // The visitor pressed, typed, scrolled or touched inside the stage: a run under way stops and the card settles flat.
  // Sent more than once for one press, so it does nothing when no run is under way (a finger resting on the card keeps its tilt).
  document.addEventListener('hb:input',()=>{if(raf)stopRun()});

  card.addEventListener('pointerdown',onMove);
  // Hovering sends no hb:input, so the visitor's own pointer ends a run here, then takes the card.
  card.addEventListener('pointermove',e=>{if(e.isTrusted&&raf)stopRun();onMove(e)});
  card.addEventListener('pointerleave',onLeave);
  card.addEventListener('pointercancel',onLeave);
  // The keyboard is a pretend pointer through the same tilt(): focus by keyboard ends a run and tilts the card where it leans (the
  // middle at rest), each arrow key moves it 6% of the card (held, it repeats), and Escape or leaving the card flattens it as onLeave()
  const STEP={ArrowLeft:[-1,0],ArrowRight:[1,0],ArrowUp:[0,-1],ArrowDown:[0,1]};
  let keys=false;
  card.addEventListener('focus',()=>{if(card.matches(':focus-visible')){if(raf)stopRun();keys=true;setSrc('key');tilt(tiltX,tiltY)}});
  card.addEventListener('keydown',e=>{
    const d=!e.altKey&&!e.ctrlKey&&!e.metaKey&&STEP[e.key];
    if(d){e.preventDefault();keys=true;setSrc('key');tilt(edge(tiltX+.06*d[0]),edge(tiltY+.06*d[1]))}
    else if(e.key==='Escape'&&keys){keys=false;onLeave()}
  });
  card.addEventListener('blur',()=>{if(keys){keys=false;onLeave()}});

  function choices(id,pick){
    const buttons=document.querySelectorAll('#'+id+' button');
    buttons.forEach(b=>b.addEventListener('click',()=>{
      buttons.forEach(x=>{x.classList.toggle('on',x===b);x.setAttribute('aria-pressed',String(x===b))});
      pick(b.dataset);
      relayout(); // Compare's card size follows the lean and depth
    }));
  }
  choices('tilt-seg',d=>{maxTilt=+d.tilt});
  choices('depth-seg',d=>{vars.setProperty('--perspective',d.px+'px');persp=+d.px;drawEye()});
  choices('return-seg',d=>{vars.setProperty('--reset-dur',d.ms+'ms')});
  document.getElementById('shine-tog').addEventListener('change',e=>{shineOn=e.target.checked;if(!shineOn)shine.style.opacity='0';sync();redraw()});
  document.getElementById('invert-tog').addEventListener('change',e=>{invert=e.target.checked;sync();redraw()});
  document.getElementById('scale-tog').addEventListener('change',e=>{scaleOn=e.target.checked;relayout()});

  // The modes show the pose (the pointer parked up and to the right) whenever nothing else moves the card, and redraw whatever
  // does. Normal flattens the card as before.
  function redraw(){if(mode==='normal')return;if(src==='')pose();else tilt(tiltX,tiltY)}
  const line=(el,x1,y1,x2,y2)=>{el.setAttribute('x1',x1);el.setAttribute('y1',y1);el.setAttribute('x2',x2);el.setAttribute('y2',y2)};
  // "Seen from above": the card is a bar turned by its sideways lean (deg), the eye sits farther down for a deeper 3D depth
  function drawBar(deg){
    const a=deg*Math.PI/180,dx=40*Math.cos(a),dy=40*Math.sin(a);
    line(bar,60-dx,16+dy,60+dx,16-dy);line(sl1,60,eyeY,60-dx,16+dy);line(sl2,60,eyeY,60+dx,16-dy);
  }
  function drawEye(){eyeY=36+persp*.026;eye.setAttribute('transform',`translate(60 ${eyeY})`);drawBar(0)}
  drawEye();
  // How far past its flat half-size the card reaches, across and down, at the most it can lean (a pointer in any corner) with
  // the current Tilt amount, 3D depth and Grows a little: each corner is turned as tilt()'s transform turns it, then projected.
  function reach(a,b){
    const k=scaleOn?1.04:1,t=.5*maxTilt*Math.PI/180,c=Math.cos(t),n=Math.sin(t);
    let gx=1,gy=1;
    for(const ry of[-n,n])for(const rx of[-n,n])for(const px of[-a,a])for(const py of[-b,b]){
      const x=k*px,y=k*py,f=persp/(persp-(y*rx-x*ry*c));
      gx=Math.max(gx,Math.abs(x*c)*f/a);gy=Math.max(gy,Math.abs(y*c+x*ry*rx)*f/b);
    }
    return[gx,gy];
  }
  // Sizes for the mode on show, measured: See inside's dashed box and caption room; Compare's card scale (room kept for its lean
  // and growth) and its shift down below the half names. A phone's card shrinks with the separate scale property.
  function layout(){
    if(mode==='normal')return;
    const W=stage.clientWidth,H=stage.clientHeight,cw=card.offsetWidth,ch=card.offsetHeight;
    let s=1,dy=0;
    if(mode==='inside'){
      if(phoneMQ.matches)s=Math.min(1,(H-2*BAND)/ch);
      const l=card.offsetLeft+cw*(1-s)/2,t=card.offsetTop+ch*(1-s)/2,col=Math.min(240,Math.max(0,l-34));
      Object.assign(flat.style,{left:l+'px',top:t+'px',width:cw*s+'px',height:ch*s+'px'});
      views.style.setProperty('--col',col+'px');
      views.classList.toggle('no-top',col<100);
      views.style.setProperty('--cap-y',(t-capCross.offsetHeight)/2+'px');
    }else{
      const band=nm2.offsetTop+nm2.offsetHeight+8;
      const[gx,gy]=reach(cw/2,ch/2);
      s=Math.min(1,(W/2-12)/(cw*gx),(H-band-6)/(ch*gy));dy=band/2;
    }
    stage.style.setProperty('--fit',s);stage.style.setProperty('--dy',dy+'px');
    G={W,H,w:cw,h:ch,s,dy};
  }
  // The words that change with Tilts away and Shine (written only when they differ, so the live notes are not read again)
  function put(el,t){if(el.textContent!==t)el.textContent=t}
  function sync(){
    const dir=invert?'away from':'toward',second=invert?'Tilts away':'Tilts toward you';
    ring.hidden=capLight.hidden=!shineOn;
    put(dirEl,dir);put(nm2,second);
    put(noteIn,`Inside, the card leans ${dir} the cross, your pointer, turning around its middle${shineOn?', and the light sits under it.':'; Shine is off, so no light.'} Dashed: where it lies flat; point at the card, or press Show me.`);
    put(noteCmp,`Stays flat ignores the pointer, shown as a ghost, while ${second} leans ${dir} it${shineOn?' and catches the light':''}${invert?'':(shineOn?',':'')+' like a real card'}. Point at the right card, or press Show me.`);
  }
  document.addEventListener('hb:mode',e=>{
    mode=e.detail.mode;
    layout();
    if(src==='')onLeave();else redraw();
  });
  function relayout(){layout();redraw()}
  addEventListener('resize',relayout);
  if(document.fonts)document.fonts.ready.then(relayout);
</script>
</body>
</html>