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.

28.5 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>Flip In — Animation Handbook</title>
  <meta name="description" content="Swings into view in 3D, like a card turning over. Best for cards and tiles.">
  <link rel="canonical" href="https://matinmonshizadeh.github.io/animation-handbook/animations/02-entrance-and-exit/flip-in/">
  <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="Flip In — Animation Handbook">
  <meta property="og:description" content="Swings into view in 3D, like a card turning over. Best for cards and tiles.">
  <meta property="og:url" content="https://matinmonshizadeh.github.io/animation-handbook/animations/02-entrance-and-exit/flip-in/">
  <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="Flip In — Animation Handbook">
  <meta name="twitter:description" content="Swings into view in 3D, like a card turning over. Best for cards and tiles.">
  <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": "Flip In", "name": "Flip In", "description": "Swings into view in 3D, like a card turning over. Best for cards and tiles.", "url": "https://matinmonshizadeh.github.io/animation-handbook/animations/02-entrance-and-exit/flip-in/", "inLanguage": "en", "articleSection": "Entrance & Exit", "isPartOf": {"@type": "WebSite", "name": "Animation Handbook", "url": "https://matinmonshizadeh.github.io/animation-handbook/"}, "author": {"@type": "Person", "name": "matinmonshizadeh"}, "keywords": "web animation, CSS animation, Entrance & Exit, Flip In"}</script>
  <style>
    :root{--ui-accent:#5fd88a;--ui-muted:#8a8a92;--dur:600ms;--ease:ease-out;--persp:1000px;--rot-y:90deg;--rot-x:0deg;--origin:center}
    *,*::before,*::after{box-sizing:border-box;margin:0;padding:0}
    .stage{display:flex;align-items:center;justify-content:center;background:#0b0b0d;perspective:var(--persp)}
    .card{background:#161b22;border:1px solid #30363d;border-radius:14px;padding:clamp(28px,5vw,48px);text-align:center;width:clamp(220px,50%,280px);
      opacity:0;transform:rotateY(var(--rot-y)) rotateX(var(--rot-x));transform-origin:var(--origin);
      transition:transform var(--dur) var(--ease),opacity var(--dur) var(--ease);will-change:transform,opacity}
    .card.in{opacity:1;transform:rotateY(0deg) rotateX(0deg)}
    .card-icon{font-size:32px;margin-bottom:14px;opacity:.6}
    .card-title{font-size:clamp(16px,2.4vw,21px);font-weight:bold;margin-bottom:8px}
    .card-sub{font-size:11px;color:var(--ui-muted);line-height:1.65}
    .stage{position:relative}
    .half,.fig,.side,.when{display:none}
    .cap{padding:3px 7px;border-radius:5px;background:rgba(11,11,13,.88);color:#f4f4f2;font:600 13px/1.25 var(--hb-font)}
    /* See inside: the card (hinge line on it) beside a drawing of the swing made from the page's numbers, its words under it. */
    .stage[data-hb-mode="inside"]{display:grid;grid-template-columns:minmax(0,.8fr) minmax(0,1.2fr);grid-template-rows:minmax(0,1fr);
      align-items:center;gap:clamp(8px,3vw,28px);padding:clamp(8px,2vw,20px)}
    .stage[data-hb-mode="inside"] .card{position:relative;justify-self:center;width:min(280px,100%)}
    .stage[data-hb-mode="inside"] .card::before,.stage[data-hb-mode="inside"] .card::after{content:'';position:absolute;z-index:-1;opacity:.75;background:var(--ui-accent);display:none}
    .stage[data-hb-mode="inside"] .card[data-hv]::before{display:block;top:-6px;bottom:-6px;left:var(--hx);width:2px;margin-left:-1px}
    .stage[data-hb-mode="inside"] .card[data-hh]::after{display:block;left:-6px;right:-6px;top:var(--hy);height:2px;margin-top:-1px}
    .stage[data-hb-mode="inside"] .fig{display:flex;flex-direction:column;align-items:flex-start;gap:4px;height:100%;min-height:0;min-width:0}
    .fig-box{flex:1 1 0;min-height:0;align-self:stretch;position:relative}
    .fig-box svg{position:absolute;left:50%;top:50%;transform:translate(-50%,-50%);overflow:visible}
    .fig-r::before{content:'';display:inline-block;width:14px;border-top:2px solid var(--ui-accent);margin-right:7px;vertical-align:middle}
    .fig-r[data-k="start"]::before{border-top:2px dashed #f4f4f2}.fig-r[data-k="ticks"]::before{border-top:3px dotted #f4f4f2}.fig-r[data-k="eye"]::before{display:none}
    .fa,.fs,.ft,.fc,.fe{fill:none;stroke:#f4f4f2}.fa{stroke-opacity:.45;stroke-width:1.5}.fs{stroke-width:1.5;stroke-dasharray:4 4}
    .ft,.fe{stroke-width:2;stroke-linecap:round}.fc{stroke-opacity:.3;stroke-dasharray:2 4}.fdot{fill:#f4f4f2}
    .blade{stroke:var(--ui-accent);stroke-width:6;stroke-linecap:round;transform:rotate(var(--ba,-90deg));transform-origin:115px 100px;
      transition:transform var(--dur) var(--ease)}
    .blade.in{transform:rotate(0deg)}
    /* Compare: No depth is a copy in a box with no 3D space (a flat squash); With depth is the card itself, held part-way through. */
    .stage[data-hb-mode="compare"]{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));grid-template-rows:minmax(0,1fr) auto;
      align-items:center;justify-items:center;gap:0 clamp(12px,3vw,32px);padding:44px clamp(8px,2vw,24px) 8px}
    .stage[data-hb-mode="compare"]::after{content:'';position:absolute;top:0;bottom:42px;left:50%;border-left:1px solid rgba(244,244,242,.12)}
    .stage[data-hb-mode="compare"] .half{display:flex;grid-area:1/1;justify-content:center;width:100%}
    .stage[data-hb-mode="compare"] .card{grid-area:1/2}
    .stage[data-hb-mode="compare"] .side,.stage[data-hb-mode="compare"] .when{display:block}
    .side{position:absolute;top:10px}.side.first{left:12px}.side.second{left:calc(50% + 12px)}
    .when{grid-area:2/1/3/3;margin-top:8px;text-align:center;visibility:hidden}
    .stage[data-hb-mode="compare"].posed .when{visibility:visible}
    .stage[data-hb-mode="compare"].posed .card{transform:rotateY(var(--py)) rotateX(var(--px))!important;opacity:var(--po)!important;transition:none!important}
    @media(max-width:600px){.fig-tk{display:none}.side.first{left:8px}.side.second{left:calc(50% + 8px)}}
    @media(max-width:600px),(max-height:640px){
      .stage[data-hb-mode="inside"] .card,.stage[data-hb-mode="compare"] .card{padding:14px 16px;width:min(100%,150px)}
      .stage[data-hb-mode="inside"] .card-sub,.stage[data-hb-mode="compare"] .card-sub{display:none}
      .stage[data-hb-mode="inside"] .card-icon,.stage[data-hb-mode="compare"] .card-icon{font-size:22px;margin-bottom:6px}
      .cap{font-size:12px;padding:2px 6px}
    }
    @media(prefers-reduced-motion:reduce){.card{transition:opacity 300ms linear!important;transform:none!important}.blade{transition:none!important}}
  </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="once" 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="../blur-in/" rel="prev" aria-label="Previous: Blur In"><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>Blur In</span></a><a href="../bounce-in/" rel="next" aria-label="Next: Bounce In"><span><span class="hb-dir">Next: </span>Bounce In</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">02.11 · Entrance &amp; Exit</p>
    <h1>Flip In</h1>
    <p class="hb-lede">Swings into view in 3D, like a card turning over. Best for cards and tiles.</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">Watch it</h2><p>It plays by itself. Turn on slow motion to see each part of the movement.</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="half" aria-hidden="true"></div>
      <div class="card" id="card">
        <div class="card-icon">⬡</div>
        <div class="card-title">3D Flip</div>
        <div class="card-sub">The depth comes from the space around the card. Without it, the turn looks like a flat squash.</div>
      </div>
      <div class="fig" aria-hidden="true">
        <p class="cap fig-t" id="f-title" data-hb-caption>From above</p>
        <div class="fig-box"><svg id="fsvg" viewBox="0 0 230 204"><g id="frot"><g id="fx"></g><line class="blade" id="bl" y1="100" y2="100"/><circle class="fdot" cx="115" cy="100" r="5.5"/></g></svg></div>
        <p class="cap fig-r" data-k="hinge" id="f-hinge" data-hb-caption>Hinge: through the middle</p>
        <p class="cap fig-r" data-k="start" id="f-start" data-hb-caption>Starts a quarter turn away, see-through</p>
        <p class="cap fig-r" data-k="eye" id="f-eye" data-hb-caption>Your eye: at arm's length</p>
        <p class="cap fig-r fig-tk" data-k="ticks" id="f-ticks" data-hb-caption>Ticks: each tenth of the time; it turns in about half a second</p>
      </div>
      <p class="cap side first" aria-hidden="true" data-hb-caption>No depth</p>
      <p class="cap side second" aria-hidden="true" data-hb-caption>With depth</p>
      <p class="cap when" id="f-when" aria-hidden="true" data-hb-caption>Part-way through the turn</p>
    </div>
    <div class="hb-player">
      <button class="hb-play" type="button" id="btn-play" data-hb-replay><svg class="hb-ic" viewBox="0 0 24 24" aria-hidden="true"><path d="M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"/><path d="M3 3v5h5"/></svg>Replay</button>
      <label class="hb-toggle"><input class="hb-switch" type="checkbox" role="switch" id="loop-tog" data-hb-loop autocomplete="off"><span>Loop</span></label>
      <label class="hb-toggle"><input class="hb-switch" type="checkbox" role="switch" id="slow-tog" data-hb-slowmo autocomplete="off"><span>Slow motion</span></label>
    </div>
    <div class="hb-mode-notes" aria-live="polite">
      <p data-hb-for="inside" hidden>Inside, the small drawing shows the card from above: it starts turned away and swings on its hinge to face you. The closer your eye, the deeper the turn looks.</p>
      <p data-hb-for="compare" hidden>No depth has no 3D space around it, so its turn is a flat squash; With depth swings in real depth. With Loop off, both rest part-way through the turn.</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 and the animation plays again.</p></div>
    </div>
    <div class="hb-settings">
      <div class="hb-setting">
        <p class="hb-setting-name" id="axis-lbl">Swing direction</p>
        <div class="seg" id="axis-seg" role="group" aria-labelledby="axis-lbl">
          <button type="button" data-axis="Y" class="on" aria-pressed="true">Sideways</button>
          <button type="button" data-axis="X" aria-pressed="false">Up and down</button>
          <button type="button" data-axis="both" aria-pressed="false">Diagonal</button>
        </div>
        <p class="hb-hint">Sideways turns like a door, up and down like a flap.</p>
      </div>
      <div class="hb-setting">
        <p class="hb-setting-name" id="origin-lbl">Hinge</p>
        <div class="seg" id="origin-seg" role="group" aria-labelledby="origin-lbl">
          <button type="button" data-o="center" class="on" aria-pressed="true">Center</button>
          <button type="button" data-o="top center" aria-pressed="false">Top</button>
          <button type="button" data-o="bottom center" aria-pressed="false">Bottom</button>
          <button type="button" data-o="left center" aria-pressed="false">Left</button>
        </div>
        <p class="hb-hint">An edge hinge makes it swing from that side.</p>
      </div>
      <div class="hb-setting">
        <p class="hb-setting-name" id="speed-lbl">Speed</p>
        <div class="seg" id="speed-seg" role="group" aria-labelledby="speed-lbl">
          <button type="button" data-ms="1000" aria-pressed="false">Slow</button>
          <button type="button" data-ms="600" class="on" aria-pressed="true">Normal</button>
          <button type="button" data-ms="350" aria-pressed="false">Fast</button>
        </div>
        <p class="hb-hint">Slow is easy to follow. Fast feels snappy.</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="rot-lbl">How far it turns</p>
          <div class="seg" id="rot-seg" role="group" aria-labelledby="rot-lbl">
            <button type="button" data-rot="45" aria-pressed="false">A little</button>
            <button type="button" data-rot="90" class="on" aria-pressed="true">¼ turn</button>
            <button type="button" data-rot="180" aria-pressed="false">½ turn</button>
          </div>
          <p class="hb-hint">¼ turn starts edge-on; ½ turn starts facing away.</p>
        </div>
        <div class="hb-setting">
          <p class="hb-setting-name" id="persp-lbl">3D depth</p>
          <div class="seg" id="persp-seg" role="group" aria-labelledby="persp-lbl">
            <button type="button" data-persp="2000px" aria-pressed="false">Subtle</button>
            <button type="button" data-persp="1000px" class="on" aria-pressed="true">Medium</button>
            <button type="button" data-persp="400px" aria-pressed="false">Strong</button>
          </div>
          <p class="hb-hint">Strong looks closer and more dramatic.</p>
        </div>
        <div class="hb-setting">
          <p class="hb-setting-name" id="feel-lbl">Feel</p>
          <div class="seg" id="feel-seg" role="group" aria-labelledby="feel-lbl">
            <button type="button" data-ease="ease-out" class="on" aria-pressed="true">Smooth</button>
            <button type="button" data-ease="cubic-bezier(.34,1.56,.64,1)" aria-pressed="false">Springy</button>
            <button type="button" data-ease="ease-in-out" aria-pressed="false">Gentle</button>
            <button type="button" data-ease="linear" aria-pressed="false">Even</button>
          </div>
          <p class="hb-hint">Springy swings a little past, then settles.</p>
        </div>
        <div class="hb-setting">
          <label class="hb-switch-row"><span>Fades in</span><input class="hb-switch" type="checkbox" role="switch" id="fade-tog" checked autocomplete="off"></label>
          <p class="hb-hint">Softens the first moment.</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 flip-in entrance to [the card you want to animate]. The card should start turned away from the viewer and swing toward them until it faces them flat. Give the card's container a 3D perspective so the swing has real depth; without it, the flip looks like a flat squash. The hinge can sit in the middle or along one edge, and the card can fade in while it turns. If the visitor has reduced motion turned on, show the card facing forward without the flip. 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>Cards</li><li>Flashcards and tiles</li><li>Dashboard panels</li><li>Onboarding steps</li></ul>
      <h3>Avoid on</h3>
      <ul class="hb-tags hb-avoid"><li>Text blocks</li><li>Full-page sections</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'),stage=card.parentElement;
  const vars=document.documentElement.style;
  const loopTog=document.getElementById('loop-tog'),slowTog=document.getElementById('slow-tog');
  const fadeTog=document.getElementById('fade-tog');
  const motionOk=!window.matchMedia('(prefers-reduced-motion:reduce)').matches;
  let axis='Y',origin='center',ms=600,rot=90,persp='1000px',ease='ease-out',timers=[];
  // The Feel choices as speed-curve numbers, the held moment, the card's length, the hinge dot and the eye's distance per 3D depth.
  const CURVES={'ease-out':[0,0,.58,1],'ease-in-out':[.42,0,.58,1],linear:[0,0,1,1],'cubic-bezier(.34,1.56,.64,1)':[.34,1.56,.64,1]};
  const POSE_MS=200,L=84,CX=115,CY=100,EYE={'2000px':84,'1000px':64,'400px':44};
  const $=id=>document.getElementById(id),svgBox=$('fsvg').parentElement,blade=$('bl');
  // Compare's first card: a copy of the card, out of reach of the keyboard and screen readers, in a box with no 3D space
  const twin=card.cloneNode(true);
  twin.removeAttribute('id');twin.inert=true;twin.setAttribute('aria-hidden','true');
  stage.querySelector('.half').append(twin);
  let mode='normal',poseOn=false,VB=[230,204];
  function dur(){return slowTog.checked?ms*3:ms}
  function apply(){
    const ry=axis==='X'?'0deg':rot+'deg';
    const rx=axis==='Y'?'0deg':rot+'deg';
    vars.setProperty('--rot-y',ry);
    vars.setProperty('--rot-x',rx);
    vars.setProperty('--origin',origin);
    vars.setProperty('--dur',dur()+'ms');
    vars.setProperty('--ease',ease);
    vars.setProperty('--persp',persp);
    [card,twin].forEach(c=>c.style.opacity=fadeTog.checked?'':'1');
  }
  function later(fn,wait){timers.push(setTimeout(fn,wait))}
  function setIn(on){[card,twin,blade].forEach(e=>e.classList.toggle('in',on))}
  function flipIn(){
    // snap back to the starting pose without a transition so every play starts from the beginning
    [card,twin,blade].forEach(e=>e.style.setProperty('transition','none','important'));
    setIn(false);void card.offsetWidth;
    [card,twin,blade].forEach(e=>e.style.removeProperty('transition'));
    setIn(true);
  }
  // Compare's held moment comes back once a play is over (the reduced fade is 300ms), if Compare is still on show
  function holdLater(){later(()=>{if(mode==='compare')pose(true)},(motionOk?dur():300)+700)}
  // One play flips in; with Loop on it holds, flips out, waits and repeats. Slow motion stretches the flips, not the waits.
  function cycle(){
    apply();pose(!motionOk&&mode==='compare');
    const falling=loopTog.checked&&motionOk;
    flipIn();
    if(!falling){if(mode==='compare')holdLater();return}
    later(()=>{
      if(!loopTog.checked)return;
      setIn(false);
      later(cycle,dur()+400);
    },dur()+800);
  }
  function play(){timers.forEach(clearTimeout);timers=[];cycle()}
  document.getElementById('btn-play').addEventListener('click',play);
  // Loop off: a play in its hold ends there (and in Compare is then held); one flipping out or waiting plays on, flips in once more
  loopTog.addEventListener('change',()=>{
    if(loopTog.checked)play();
    else if(card.classList.contains('in')&&mode==='compare')holdLater();
    refresh();
  });
  slowTog.addEventListener('change',refresh);fadeTog.addEventListener('change',refresh);
  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);
      refresh();
    }));
  }
  choices('axis-seg',d=>{axis=d.axis});
  choices('origin-seg',d=>{origin=d.o});
  choices('speed-seg',d=>{ms=+d.ms});
  choices('rot-seg',d=>{rot=+d.rot});
  choices('persp-seg',d=>{persp=d.persp});
  choices('feel-seg',d=>{ease=d.ease});
  apply();
  // The value of a speed curve at a share x of its time: the curve's own t for x found by halving, then its height there
  function curveAt([a,b,c,e],x){
    const at=(p,q,t)=>3*p*t*(1-t)*(1-t)+3*q*t*t*(1-t)+t*t*t;
    let lo=0,hi=1,t=x;
    for(let i=0;i<30;i++){t=(lo+hi)/2;if(at(a,c,t)<x)lo=t;else hi=t}
    return at(b,e,t);
  }
  function words(t){return t<=400?'about a third of a second':t<=700?'about half a second':t<=1200?'about a second':t<=2000?'about two seconds':'about three seconds'}
  // Compare's still moment: a fifth of a second in, kept clear of edge-on (at most 70, 55 or 30 degrees) and of facing you (a fifth of the turn).
  function moment(){
    const p=curveAt(CURVES[ease],Math.min(1,POSE_MS/dur())),raw=rot*(1-p);
    return {p:Math.max(p,.35),a:Math.min(rot===180?70:rot===90?55:30,Math.max(rot/5,raw))};
  }
  function pose(on){
    poseOn=on;stage.classList.toggle('posed',on);
    if(!on)return;
    const {p,a}=moment(),v=stage.style;
    v.setProperty('--py',(axis==='X'?0:a)+'deg');v.setProperty('--px',(axis==='Y'?0:a)+'deg');
    v.setProperty('--po',fadeTog.checked?Math.min(1,p).toFixed(3):1);
    $('f-when').textContent={45:'A little turn',90:'A quarter turn',180:'A half turn'}[rot]+', part-way';
  }
  // The drawing, from the page's own numbers: seen from above (the side for Up and down) the card is a line swinging on its hinge dot.
  function drawFig(){
    const side=axis==='X',diag=axis==='both';
    const f=side?(/^top/.test(origin)?1:/^bottom/.test(origin)?0:.5):(/^left/.test(origin)?0:.5);
    const a=-L*f,b=L*(1-f),s=b>=-a?1:-1,r=Math.max(-a,b),T=rot*Math.PI/180,e=EYE[persp],n=v=>v.toFixed(1);
    const pt=(l,t,o=0)=>n(CX+l*Math.cos(t)+o*Math.sin(t))+' '+n(CY-l*Math.sin(t)+o*Math.cos(t));
    let ticks='';
    for(let i=1;i<=10;i++){const t=rot*(1-curveAt(CURVES[ease],i/10))*Math.PI/180;ticks+=`M${pt(s*(r+4),t)}L${pt(s*(r+10),t)}`}
    $('frot').setAttribute('transform',side?`rotate(-90 ${CX} ${CY})`:'');
    const R=r+12;VB=side?[R+e+12,2*R]:[2*R,R+e+12];
    $('fsvg').setAttribute('viewBox',`${CX-R} ${CY-R} ${VB[0]} ${VB[1]}`);
    $('fsvg').style.setProperty('--ba',-rot+'deg');
    blade.setAttribute('x1',CX+a);blade.setAttribute('x2',CX+b);
    $('fx').innerHTML=`<path class="fa" d="M${pt(s*r,T)}A${r} ${r} 0 0 1 ${CX+s*r} ${CY}"/><path class="fs" d="${[-5,5].map(o=>`M${pt(a,T,o)}L${pt(b,T,o)}`).join('')}"/>`+
      `<path class="ft" d="${ticks}"/><path class="fc" d="M${CX+a} ${CY}L${CX} ${CY+e}L${CX+b} ${CY}"/>`+
      `<g transform="translate(${CX} ${CY+e})"><path class="fe" d="M-11 0Q0-10 11 0Q0 10-11 0Z"/><circle class="fe" r="3.5"/></g>`;
    card.toggleAttribute('data-hv',!side);card.toggleAttribute('data-hh',axis!=='Y');
    card.style.setProperty('--hx',/^left/.test(origin)?'0%':'50%');
    card.style.setProperty('--hy',/^top/.test(origin)?'0%':/^bottom/.test(origin)?'100%':'50%');
    const edge=side?(f===1?'top':f===0?'bottom':''):(f===0?'left':'');
    $('f-title').textContent=side?'From the side':diag?'From above (it also tips forward)':'From above';
    $('f-hinge').textContent=diag?'Hinge: both lines it turns on':'Hinge: '+(edge?`the card's ${edge} edge`:'through the middle');
    $('f-start').textContent=['Starts turned a little','Starts a quarter turn away','Starts facing away'][rot===45?0:rot===90?1:2]+(fadeTog.checked?', see-through':', solid');
    $('f-eye').textContent='Your eye: '+{'2000px':'far away, a gentle turn','1000px':"at arm's length",'400px':'close up, a deep turn'}[persp];
    $('f-ticks').textContent='Ticks: each tenth of the time; it turns in '+words(dur());
  }
  // The notes say what the box shows now (the markup's own words for the defaults); under reduced motion they say it is still
  function notes(){
    const view=axis==='X'?'the side':'above',when='part-way through the turn';
    document.querySelector('[data-hb-for="inside"]').textContent=motionOk
      ?`Inside, the small drawing shows the card from ${view}: it starts turned away and swings on its hinge to face you. The closer your eye, the deeper the turn looks.`
      :`Shown still: the small drawing shows the card from ${view}, turned away at the start and swinging on its hinge to face you; the eye marks how close you are.`;
    document.querySelector('[data-hb-for="compare"]').textContent=motionOk
      ?`No depth has no 3D space around it, so its turn is a flat squash; With depth swings in real depth. With Loop off, both rest ${when}.`
      :`Shown still, ${when}: No depth is a flat, squashed card, while With depth leans back in real depth.`;
  }
  // The drawing fills the room it has; the stage's vanishing point follows the card (Normal keeps the middle, where the card is)
  function fit(){
    const W=svgBox.clientWidth,H=svgBox.clientHeight,k=Math.min(W/VB[0],H/VB[1],1.5),sv=$('fsvg').style;
    if(W&&H){sv.width=VB[0]*k+'px';sv.height=VB[1]*k+'px'}
    stage.style.perspectiveOrigin=mode==='normal'?'':`${card.offsetLeft+card.offsetWidth/2}px ${card.offsetTop+card.offsetHeight/2}px`;
  }
  function refresh(){drawFig();notes();fit();if(poseOn)pose(true)}
  // The mode switch: draws the mode at once. The shared script then presses Replay (not under reduced motion), which plays it.
  document.addEventListener('hb:mode',e=>{
    const was=mode;mode=e.detail.mode;
    // Leaving Compare's held moment shows the cards as they now are, at once, with no turn (a play under way goes on)
    if(was==='compare'&&mode!=='compare'&&poseOn){
      [card,twin].forEach(c=>c.style.setProperty('transition','none','important'));pose(false);void card.offsetWidth;
      [card,twin].forEach(c=>c.style.removeProperty('transition'));
    }
    pose(mode==='compare'&&!(loopTog.checked&&motionOk));
    refresh();
  });
  const redraw=new ResizeObserver(fit);redraw.observe(stage);redraw.observe(svgBox);
  refresh();
</script>
</body>
</html>