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.
HTML ai-promptsanimationcss-animationsfrontendgithub-pagesjavascriptmicrointeractionsmotion-designno-dependenciesreferencescroll-animationui-animationweb-animationweb-developmentwebgl
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Cube Transition — Animation Handbook</title>
<meta name="description" content="The pages sit on a cube that turns to show the next. Best for photo stories.">
<link rel="canonical" href="https://matinmonshizadeh.github.io/animation-handbook/animations/03-page-transitions/cube-transition/">
<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="Cube Transition — Animation Handbook">
<meta property="og:description" content="The pages sit on a cube that turns to show the next. Best for photo stories.">
<meta property="og:url" content="https://matinmonshizadeh.github.io/animation-handbook/animations/03-page-transitions/cube-transition/">
<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="Cube Transition — Animation Handbook">
<meta name="twitter:description" content="The pages sit on a cube that turns to show the next. Best for photo stories.">
<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": "Cube Transition", "name": "Cube Transition", "description": "The pages sit on a cube that turns to show the next. Best for photo stories.", "url": "https://matinmonshizadeh.github.io/animation-handbook/animations/03-page-transitions/cube-transition/", "inLanguage": "en", "articleSection": "Page Transitions", "isPartOf": {"@type": "WebSite", "name": "Animation Handbook", "url": "https://matinmonshizadeh.github.io/animation-handbook/"}, "author": {"@type": "Person", "name": "matinmonshizadeh"}, "keywords": "web animation, CSS animation, Page Transitions, Cube Transition"}</script>
<style>
:root{--bg:#0b0b0d;--ui-bg:#111114;--ui-border:rgba(255,255,255,.09);--ui-accent:#b98cff;--ui-text:#f4f4f2;--ui-muted:#8a8a92}
*,*::before,*::after{box-sizing:border-box;margin:0;padding:0}
.stage{position:relative;display:flex;flex-direction:column;overflow:hidden;background:var(--bg);color:var(--ui-text)}
.mini-nav{display:flex;gap:6px;padding:10px 12px;background:var(--ui-bg);border-bottom:1px solid var(--ui-border);flex-shrink:0}
.nav-btn{background:none;border:1px solid var(--ui-border);color:var(--ui-muted);font:inherit;font-size:13px;padding:0 12px;border-radius:4px;cursor:pointer;min-height:44px}
.nav-btn.active{border-color:var(--ui-accent);color:var(--ui-accent)}
@media(hover:hover){.nav-btn:hover{border-color:var(--ui-accent)}}
.page-area{flex:1;position:relative;overflow:hidden;background:#060608}
/* A side of the cube that turns away from you is not drawn, as on a real cube seen from outside */
.page{position:absolute;inset:0;opacity:0;pointer-events:none;backface-visibility:hidden;-webkit-backface-visibility:hidden}
.page.active{opacity:1;pointer-events:auto}
/* Each page darkens as it turns away from the light */
.dim{position:absolute;inset:0;background:#000;opacity:0;pointer-events:none}
/* page content */
.pc{display:flex;flex-direction:column;justify-content:center;height:100%;padding:clamp(20px,4vw,40px);gap:12px}
.pe{font-size:10px;text-transform:uppercase;letter-spacing:3px;opacity:.6}
.ph{font-size:clamp(22px,3.5vw,36px);font-weight:bold;line-height:1.15}
.pp{font-size:12px;opacity:.6;line-height:1.65;max-width:320px}
.pgrid{display:grid;grid-template-columns:repeat(3,1fr);gap:6px;margin-top:4px}
.gi{background:rgba(255,255,255,.07);border:1px solid rgba(255,255,255,.1);border-radius:6px;padding:18px 12px;font-size:11px}
.pstat{display:flex;gap:20px;margin-top:4px}
.pstat b{display:block;font-size:clamp(18px,2.5vw,24px);color:var(--ui-accent)}
.pstat span{font-size:9px;opacity:.6;text-transform:uppercase;letter-spacing:1px}
/* Short windows leave the page area under 220px: tighter spacing keeps the tallest page inside it with room to spare */
@media(max-height:640px){.pc{gap:8px}.gi{padding:12px}}
/* The small site: its nav row over its page area. In Compare a copy of it, the twin, sits beside it. */
.box{display:flex;flex-direction:column;flex:1;min-height:0;min-width:0}
.twin,.cmap,.lbl{display:none}
.twin .nav-btn{display:inline-flex;align-items:center}
.lbl{padding:2px 7px;border-radius:5px;background:#111114;color:#f4f4f2;font:600 12px/1.25 var(--hb-font)}
/* See inside: the real pages stand at half a turn (script), and a map of the cube seen from above sits in the page area's
corner: the cube as a square with a side in each page's color, a dot where it turns, the eye of the viewer in front of it,
and a dashed outline where the cube rests. The script sizes and places everything from the page's own numbers. */
.stage[data-hb-mode="inside"] .cmap{display:flex}
.stage[data-hb-mode="inside"] .cmap .lbl,.stage[data-hb-mode="inside"] .legend .lbl{display:block}
.stage[data-hb-mode="inside"] .legend{display:flex}
/* The pages show their eyebrow, heading and text, not the grid or the figures: they would run under the map and its names */
.stage[data-hb-mode="inside"] .pgrid,.stage[data-hb-mode="inside"] .pstat{display:none}
.cmap{position:absolute;z-index:5;right:8px;bottom:8px;width:min(190px,calc(50% - 14px));flex-direction:column;gap:4px;padding:6px;
border-radius:10px;background:rgba(8,8,10,.94);border:1px solid var(--ui-border)}
/* The length of a turn sits in the page area's other corner, clear of the near edge in the middle; on a small box the map's
title does too */
.cmap.up{width:min(340px,calc(50% - 14px))}
.legend{display:none;position:absolute;z-index:5;left:8px;bottom:8px;max-width:calc(50% - 22px);flex-direction:column;align-items:flex-start;gap:4px}
/* A turn up and down leaves the new page's text in the lower left, so the legend moves to the upper right */
.legend.up{bottom:auto;top:8px;left:auto;right:8px;align-items:flex-end}
.draw{position:relative;flex:none}
.draw .lbl{position:absolute;left:0;top:0}
.sight{position:absolute}
.sq{position:absolute;box-sizing:border-box;border:3px solid;border-radius:2px;transform:translate(-50%,-50%)}
.sq.dash{border:1.5px dashed rgba(244,244,242,.5)}
.dot{position:absolute;width:8px;height:8px;margin:-4px 0 0 -4px;border-radius:50%;background:#f4f4f2}
.eye{position:absolute;width:18px;height:18px;margin:-9px 0 0 -9px;fill:#08080a;stroke:#f4f4f2;stroke-width:2;stroke-linecap:round;stroke-linejoin:round}
/* Compare: on the left the copy, which changes page at once; on the right the real site, which turns. At rest the real site
stands at half a turn, so the still picture shows the cube. */
.stage[data-hb-mode="compare"]{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:2px;background:#2a2a30}
.stage[data-hb-mode="compare"] .twin{display:flex}
.stage[data-hb-mode="compare"] .side{display:block}
/* Both halves show the page's eyebrow, heading and text, not its grid or its figures: the half's name sits at its bottom */
.stage[data-hb-mode="compare"] .pgrid,.stage[data-hb-mode="compare"] .pstat{display:none}
.side{position:absolute;bottom:10px;z-index:11}
.side.first{left:10px}
.side.second{left:calc(50% + 10px)}
@media(max-width:600px){
/* Turning up and down, the map sits in the lower right and the names in the upper right: the pages' text keeps to the left */
.stage[data-hb-mode="inside"] .cmap.up{width:calc(58% - 8px)}
.stage[data-hb-mode="inside"] .cmap.up~.page .pc{padding:20px calc(58% + 4px) 12px 12px}
.stage[data-hb-mode="inside"] .cmap.up~.page .ph{font-size:18px}
.stage[data-hb-mode="compare"] .mini-nav{gap:4px;padding:6px}
.stage[data-hb-mode="compare"] .nav-btn{padding:0 6px;font-size:12px;min-width:44px;justify-content:center}
.stage[data-hb-mode="compare"] .pc{padding:12px;gap:6px}
.stage[data-hb-mode="compare"] .ph{font-size:16px}
}
/* Phones and short windows (a phone held sideways too) leave the page area short: the page keeps only its eyebrow and heading */
@media(max-width:600px),(max-height:740px){
.stage[data-hb-mode="inside"] .pp{display:none}
}
@media(max-width:600px),(max-height:650px){
.stage[data-hb-mode="inside"] .pc{justify-content:flex-start}
.stage[data-hb-mode="compare"] .pp{display:none}
}
/* From 360px down the halves stack; a stacked half is short, so its page text starts at the top, clear of its name */
@media(max-width:360px){
.stage[data-hb-mode="compare"]{grid-template-columns:minmax(0,1fr);grid-template-rows:repeat(2,minmax(0,1fr))}
.stage[data-hb-mode="compare"] .side.first{bottom:calc(50% + 10px)}
.stage[data-hb-mode="compare"] .side.second{left:10px}
.stage[data-hb-mode="compare"] .pc{justify-content:flex-start}
}
</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="../page-curl/" rel="prev" aria-label="Previous: Page Curl"><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>Page Curl</span></a><a href="../pixelate-transition/" rel="next" aria-label="Next: Pixelate Transition"><span><span class="hb-dir">Next: </span>Pixelate Transition</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">03.16 · Page Transitions</p>
<h1>Cube Transition</h1>
<p class="hb-lede">The pages sit on a cube that turns to show the next. Best for photo stories.</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">Click it</h2><p>Click Work or About at the top of the box, 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">
<div class="box" id="box">
<nav class="mini-nav" id="nav" aria-label="Demo pages"></nav>
<div class="page-area" id="page-area">
<div class="legend" id="legend" aria-hidden="true">
<p class="lbl cap" id="c-title" data-hb-caption></p>
<p class="lbl cap" id="c-len" data-hb-caption></p>
</div>
<div class="cmap" id="cmap" aria-hidden="true">
<div class="draw" id="c-draw">
<i class="sight" id="c-sight"></i><i class="sq dash" id="c-dash"></i><i class="sq" id="c-cube"></i><i class="dot" id="c-dot"></i>
<svg class="eye" id="c-eye" viewBox="0 0 24 24"><path d="M2 12s4-7 10-7 10 7 10 7-4 7-10 7S2 12 2 12z"/><circle cx="12" cy="12" r="3"/></svg>
<span class="lbl cap" id="l-dot" data-hb-caption>Turns around its middle</span>
<span class="lbl cap" id="l-eye" data-hb-caption>You are here</span>
</div>
</div>
</div>
</div>
<p class="lbl side first" aria-hidden="true" data-hb-caption>Switches at once</p>
<p class="lbl side second" aria-hidden="true" data-hb-caption>Cube turns</p>
</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>
<button class="hb-play" type="button" id="btn-reset" data-hb-reset><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>Reset</button>
<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 map shows the cube from above: the pages are two of its sides, and it turns around its middle, half a page behind the screen. Click Work or About, or press Show me.</p>
<p data-hb-for="compare" hidden>Switches at once simply changes page; Cube turns swings the old page away as the next one swings in, two sides of one cube. Click Work or About, 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="axis-lbl">Turn 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>
</div>
<p class="hb-hint">Going back to an earlier page turns the other way.</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="1100" aria-pressed="false">Slow</button>
<button type="button" data-ms="750" class="on" aria-pressed="true">Normal</button>
<button type="button" data-ms="500" aria-pressed="false">Fast</button>
</div>
<p class="hb-hint">How long the cube takes to turn.</p>
</div>
<div class="hb-setting">
<p class="hb-setting-name" id="depth-lbl">Depth</p>
<div class="seg" id="depth-seg" role="group" aria-labelledby="depth-lbl">
<button type="button" data-f="3.2" aria-pressed="false">Shallow</button>
<button type="button" data-f="1.6" class="on" aria-pressed="true">Normal</button>
<button type="button" data-f="0.9" aria-pressed="false">Deep</button>
</div>
<p class="hb-hint">Deep brings the cube's edge closer as it turns.</p>
</div>
</div>
</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 cube transition to [the pages or slides you want to switch between]. Treat the current page and the next one as two sides of a cube: when the visitor changes page, turn the cube a quarter turn around its middle, which sits half a page behind the screen, so the old page swings away and the new one swings into place. Going back turns the cube the other way. Give the scene perspective, hide any side that faces away from the viewer and darken each side a little as it turns away. Animate only the turn itself so it stays smooth. If the visitor has reduced motion turned on, crossfade the pages instead. 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>Photo stories</li><li>Product tours</li><li>Slides</li><li>Onboarding</li></ul>
<h3>Avoid on</h3>
<ul class="hb-tags hb-avoid"><li>Text-heavy pages</li><li>Everyday navigation</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 PAGES=[
{name:'Home',c:'#6f9bff',bg:'linear-gradient(135deg,#0d1a2e,#192640)',html:`<div class="pc"><div class="pe">Creative Studio</div><p class="ph">Design without compromise.</p><p class="pp">We craft digital products that earn attention and keep it. Every pixel considered.</p></div>`},
{name:'Work',c:'#4fc98a',bg:'linear-gradient(135deg,#0d1f15,#152e1e)',html:`<div class="pc"><div class="pe">Selected Work</div><p class="ph">The Portfolio</p><div class="pgrid">${['Atlas','Orbit','Prism','Lumen','Frame','Echo'].map(n=>`<div class="gi">${n}</div>`).join('')}</div></div>`},
{name:'About',c:'#c07bff',bg:'linear-gradient(135deg,#1f0d26,#2e1540)',html:`<div class="pc"><div class="pe">Our Story</div><p class="ph">Built on conviction.</p><p class="pp">18 people who care unreasonably about craft. Independent since 2016.</p><div class="pstat"><div><b>140+</b><span>Projects</span></div><div><b>9</b><span>Years</span></div><div><b>3</b><span>Continents</span></div></div></div>`},
];
const box=document.getElementById('box'),stage=box.parentElement;
const nav=document.getElementById('nav'),area=document.getElementById('page-area'),slowTog=document.getElementById('slow-tog');
const motionOk=!window.matchMedia('(prefers-reduced-motion:reduce)').matches;
let current=0,animating=false,axis='Y',dur=750,depth=1.6,afterMove=null,wayBack=0,timers=[];
let mode='normal',posed=false,poseAnims=[],persp0='',runFrom=-1,turn=null;
const pages=[],dims=[],navBtns=[];
PAGES.forEach((p,i)=>{
const d=document.createElement('div');d.className='page';d.style.background=p.bg;d.innerHTML=p.html+'<i class="dim"></i>';area.appendChild(d);
pages.push(d);dims.push(d.querySelector('.dim'));
const b=document.createElement('button');b.type='button';b.className='nav-btn';b.textContent=p.name;
b.addEventListener('click',()=>navigate(i));nav.appendChild(b);navBtns.push(b);
});
// Compare's first half: the same small site, changing page at once. A copy built from the same pages, with no ids and no
// buttons, out of the Tab order and hidden from screen readers; it changes page the moment a turn of the real site starts (a
// click, Show me, Reset), so one input drives both halves.
const twin=document.createElement('div');
twin.className='box twin';twin.inert=true;twin.setAttribute('aria-hidden','true');
twin.innerHTML=`<div class="mini-nav">${PAGES.map(p=>`<span class="nav-btn">${p.name}</span>`).join('')}</div>`+
`<div class="page-area">${PAGES.map(p=>`<div class="page" style="background:${p.bg}">${p.html}</div>`).join('')}</div>`;
box.before(twin);
const twinPages=[...twin.querySelectorAll('.page')],twinNav=[...twin.querySelectorAll('.nav-btn')];
function showTwin(n){twinPages.forEach((el,i)=>el.classList.toggle('active',i===n));twinNav.forEach((b,i)=>b.classList.toggle('active',i===n))}
// Drops a timer's id once it fires, so `timers` only holds the ones still waiting.
function later(fn,wait){
const id=setTimeout(()=>{
const i=timers.indexOf(id);
if(i>-1)timers.splice(i,1);
fn();
},wait);
timers.push(id);
return id;
}
function cancel(id){
clearTimeout(id);
const i=timers.indexOf(id);
if(i>-1)timers.splice(i,1);
}
function updateNav(n){navBtns.forEach((b,i)=>{b.classList.toggle('active',i===n);b.setAttribute('aria-current',i===n?'page':'false')})}
// One page's resting look: its class alone shows or hides it, flat and unshaded, with no turn or fade left over (its
// background stays). A page that is not shown is also out of the Tab order and the accessibility tree (inert).
function rest(el,on){
el.classList.toggle('active',on);
el.inert=!on;
el.style.transition='';el.style.opacity='';el.style.zIndex='';
el.getAnimations({subtree:true}).forEach(a=>a.cancel());
}
// The resting state for page n, at once
function showPage(n){
clearPose();
cubeEl.getAnimations().forEach(a=>a.cancel());
pages.forEach((el,i)=>rest(el,i===n));
updateNav(n);
showTwin(n);
}
// Ends a change: the demo is idle again, and a Show me run goes on to its next step
function finish(){
animating=false;
const then=afterMove;afterMove=null;
if(then)then();else runFrom=-1;
pose();
}
// Stops everything at once and shows the resting state for `current`
function settle(){
timers.forEach(clearTimeout);timers=[];wayBack=0;afterMove=null;
animating=false;
showPage(current);
pose();
}
// The turn from page prev to page next, over d ms: both pages get the same 3D transform, and each darkens or clears as it goes
function swing(prev,next,d){
// Read when the turn starts. The cube is as deep as the side it turns across, and the camera sits that many times `depth` away.
const side=axis==='Y',size=side?area.clientWidth:area.clientHeight,half=(size/2).toFixed(1);
// A later page comes in from the right (sideways) or from below (up and down); going back turns the cube the other way
const end=(next>prev?1:-1)*(side?-90:90);
const face=a=>`translateZ(-${half}px) rotate${axis}(${a}deg) translateZ(${half}px)`;
const how={duration:d,easing:'cubic-bezier(.65,0,.35,1)',fill:'forwards'};
area.style.perspective=Math.round(size*depth)+'px';
const list=[pages[prev].animate([{transform:face(0)},{transform:face(end)}],how),
pages[next].animate([{transform:face(-end)},{transform:face(0)}],how),
dims[prev].animate([{opacity:0},{opacity:.65}],how),
dims[next].animate([{opacity:.65},{opacity:0}],how)];
if(mode==='inside')list.push(turnMap(prev,next,how));
return list;
}
function navigate(next,then){
if(next===current||animating)return;
clearPose();
const prev=current;current=next;updateNav(next);showTwin(next);
afterMove=then||null;animating=true;
const oldEl=pages[prev],newEl=pages[next];
newEl.classList.add('active'); // both sides are on show while the cube turns
if(!motionOk){
// Reduced motion: the new page fades in over the old one, nothing turns
newEl.style.zIndex='2';newEl.style.opacity='0';newEl.offsetHeight;
newEl.style.transition='opacity 300ms linear';newEl.style.opacity='1';
later(()=>{rest(oldEl,false);rest(newEl,true);finish()},350);
return;
}
// Three times as long in slow motion
const d=dur*(slowTog.checked?3:1);
turn={prev,next,d,list:swing(prev,next,d)};
later(()=>{rest(oldEl,false);rest(newEl,true);finish()},d+50);
}
// Show me: one visit to the next page, a hold of 1200ms, and the way back to where the run started
// A press while a run is under way (a mode pressed, Show me twice) starts it again from the page where it began
function showMe(){
if(runFrom<0)runFrom=current;
const start=current=runFrom;
settle();
navigate((start+1)%PAGES.length,()=>{wayBack=later(()=>{wayBack=0;navigate(start)},1200)});
}
function reset(){current=0;runFrom=-1;settle()}
document.getElementById('btn-demo').addEventListener('click',showMe);
document.getElementById('btn-reset').addEventListener('click',reset);
// The visitor took over: cancel what the run has not started yet. A turn already under way finishes on its own.
document.addEventListener('hb:input',()=>{const held=wayBack;afterMove=null;cancel(wayBack);wayBack=0;if(!animating)runFrom=-1;if(held)pose()});
// See inside's map: the cube seen from above (from the side for a turn up and down) in the page area's corner. The cube is drawn
// as a square with a side in each page's color (the page in front, and the one it turns to), a dot where it turns, and the eye
// of the viewer in front of it: `depth` sides from the front, so Depth changes how big the cube comes out.
const cmap=document.getElementById('cmap'),legend=document.getElementById('legend'),draw=document.getElementById('c-draw'),cubeEl=document.getElementById('c-cube');
const dashEl=document.getElementById('c-dash'),sightEl=document.getElementById('c-sight'),dotEl=document.getElementById('c-dot'),eyeEl=document.getElementById('c-eye');
const capTitle=document.getElementById('c-title'),capLen=document.getElementById('c-len'),capDot=document.getElementById('l-dot'),capEye=document.getElementById('l-eye');
const phone=window.matchMedia('(max-width:600px),(max-height:500px)');
const say=(el,t)=>{if(el.textContent!==t)el.textContent=t};
const hit=(a,b)=>a[0]<b[2]&&a[2]>b[0]&&a[1]<b[3]&&a[3]>b[1];
// How long one turn takes, in a beginner's words
function about(ms){
if(ms<650)return 'half a second';
if(ms<950)return 'three quarters of a second';
if(ms<1300)return 'a second';
if(ms<1900)return 'a second and a half';
return ['two','three','four'][Math.round(ms/1000)-2]+' seconds';
}
function drawMap(prev,next){
cubeEl.getAnimations().forEach(a=>a.cancel());
const above=axis==='Y',sign=next>prev?1:-1,ah=area.clientHeight;
say(capTitle,phone.matches?(above?'From above: two sides of a cube':'From the side: two sides of a cube')
:(above?'Seen from above: the pages are two sides of a cube':'Seen from the side: the pages are two sides of a cube'));
say(capLen,(phone.matches?'One turn: about ':'One turn takes about ')+about(dur*(slowTog.checked?3:1)));
// The title heads the map where the page area is tall enough, and joins the length of a turn in the other corner where it is
// not. A turn up and down puts the map in the half below the near edge, which runs across the middle, so its title always joins.
legend.classList.toggle('up',!above);cmap.classList.toggle('up',!above);
const home=above&&!phone.matches&&ah>=250?cmap:legend;
if(capTitle.parentNode!==home)home.prepend(capTitle);
let M=Math.round(Math.max(72,Math.min(132,ah*.45)));
draw.style.height=M+'px';
const over=cmap.offsetHeight-(above?ah-16:ah/2-14); // a short stage: the map gives back what the card is too tall by
if(over>0){M=Math.max(56,M-over);draw.style.height=M+'px'}
const W=draw.clientWidth;
const OLD=PAGES[prev].c,NEW=PAGES[next].c,F='rgba(244,244,242,.3)';
cubeEl.style.borderColor=(above?(sign>0?[F,NEW,OLD,F]:[F,F,OLD,NEW]):(sign>0?[F,F,NEW,OLD]:[NEW,F,F,OLD])).join(' ');
const at=(el,p,w)=>{el.style.left=p.x+'px';el.style.top=p.y+'px';if(w){el.style.width=el.style.height=w+'px'}};
capEye.style.whiteSpace='nowrap';capEye.style.width='max-content';
const ew=capEye.offsetWidth,wrapMin=above?60:100;
let taken;
// The two names sit beside what they name, on the side with room: the first spot that is inside the map and clear of the
// cube, the eye and the other name. It tells whether it found one.
const put=(el,ob,order)=>{
for(const k of order)for(const wrap of [false,true]){
// A name that does not fit on one line wraps into the room beside what it names
const room=k==='r'?W-ob[2]-4:k==='l'?ob[0]-4:100;
el.style.whiteSpace=wrap?'normal':'nowrap';el.style.width=wrap?Math.max(wrapMin,Math.min(110,room))+'px':'max-content';
const w=el.offsetWidth,h=el.offsetHeight,cx=(ob[0]+ob[2])/2,cy=(ob[1]+ob[3])/2;
const spot={r:[ob[2]+4,cy-h/2],l:[ob[0]-4-w,cy-h/2],b:[cx-w/2,ob[3]+4],a:[cx-w/2,ob[1]-4-h],B:[0,taken[0][3]+4]};
const side=k==='r'||k==='l';
const x=Math.max(0,Math.min(W-w,spot[k][0])),y=side?Math.max(0,Math.min(M-h,spot[k][1])):spot[k][1],box=[x,y,x+w,y+h];
el.style.left=x+'px';el.style.top=y+'px';
if(y>=0&&y+h<=M&&!taken.some(t=>hit(box,t))){taken.push(box);return true}
}
return false;
};
// Draws the cube s wide with the eye in front of it, and tells whether both names found a place
const lay=(s,ex,eyeAt)=>{
const r=.707*s+2,E=above?{x:r+3,y:M-11}:{x:ex,y:M/2},C=above?{x:E.x,y:E.y-(depth+.5)*s}:{x:E.x+(depth+.5)*s,y:E.y};
if(!above&&C.x+r>W)return false;
at(dashEl,C,s);at(cubeEl,C,s);at(dotEl,C);at(eyeEl,E);
// A dotted line from the eye to the middle of the cube: where you look from
sightEl.style.cssText=above?`left:${C.x}px;top:${C.y}px;height:${E.y-C.y}px;border-left:1px dotted rgba(244,244,242,.4)`
:`left:${E.x}px;top:${C.y}px;width:${C.x-E.x}px;border-top:1px dotted rgba(244,244,242,.4)`;
taken=[[C.x-r,C.y-r,C.x+r,C.y+r],[E.x-10,E.y-10,E.x+10,E.y+10]];
const a=put(capEye,taken[1],eyeAt),b=put(capDot,taken[0],'rbal');
return a&&b;
};
if(above)lay(Math.min((M-10)/(depth+1.207),W*.3),0,'rlba');
else{ // the side view is short and wide: the biggest cube whose two names still fit. A wide card may put the eye in far enough
// for its name to stand under it or beside it; a narrow one puts that name under the whole row.
const eyes=W<220?[[9,'bB']]:[[Math.ceil(ew/2)+1,'b'],[ew+14,'l']];
let s=Math.min((W-13)/(depth+1.207),(M-4)/1.414);
while(s>12&&!eyes.some(e=>lay(s,...e)))s-=3;
}
}
// The map's cube turns as the pages do: the same length and curve, started in the same step, clockwise for a later page
function turnMap(prev,next,how){
drawMap(prev,next);
const rot=a=>`translate(-50%,-50%) rotate(${a}deg)`;
return cubeEl.animate([{transform:rot(0)},{transform:rot((next>prev?1:-1)*90)}],how);
}
// At rest in See inside and Compare the real cube stands half way through its turn to the next page: the turn's own animations,
// held at their middle. A turn lifts the pose, and it comes back when no turn or way back is pending.
function clearPose(){
if(!posed)return;
posed=false;poseAnims.forEach(a=>a.cancel());poseAnims=[];
pages.forEach((el,i)=>{if(i!==current)el.classList.remove('active')});
area.style.perspective=persp0;
}
function pose(){
clearPose();
if(mode!=='normal'&&!animating&&!wayBack){
const next=(current+1)%PAGES.length;
persp0=area.style.perspective;
pages[next].classList.add('active');
poseAnims=swing(current,next,dur);
poseAnims.forEach(a=>{a.pause();a.currentTime=dur/2});
posed=true;
}else if(mode==='inside'&&!animating)drawMap(current,(current+1)%PAGES.length);
notes();
}
// Under reduced motion both views are still pictures, and their notes say so
const noteIn=document.querySelector('[data-hb-for="inside"]'),noteCmp=document.querySelector('[data-hb-for="compare"]');
const wordsIn=noteIn.textContent,wordsCmp=noteCmp.textContent;
function notes(){
if(mode==='normal')return;
const from=axis==='Y'?'above':'the side',still=!motionOk&&posed;
say(noteIn,still?`Shown still at half a turn: the two pages meet at the cube's near edge, and the map shows the cube from ${from}, turned half way.`
:wordsIn.replace('from above','from '+from));
say(noteCmp,still?'Shown still: Switches at once shows the page as it is; Cube turns is caught half way to the next page, its two pages meeting at an edge.'
:motionOk?wordsCmp:'Switches at once simply changes page; with reduced motion, Cube turns fades the next page in instead of turning. Click Work or About, or press Show me.');
}
// The mode switch: draws the mode at once. The shared script then presses Show me (not under reduced motion), which plays it.
// A turn under way when a mode or a resize changes the box (Compare's half, or the whole box again) goes on from the same
// moment, aimed again at the box's new size
function reaim(){
if(!animating||!motionOk||!turn)return;
const t=turn.list[0].currentTime;if(t===null)return;
turn.list.forEach(a=>a.cancel());
turn.list=swing(turn.prev,turn.next,turn.d);
turn.list.forEach(a=>{a.currentTime=t});
}
document.addEventListener('hb:mode',e=>{mode=e.detail.mode;reaim();pose()});
addEventListener('resize',()=>{if(mode!=='normal'){reaim();pose()}});
if(document.fonts)document.fonts.ready.then(()=>{if(mode==='inside')pose()});
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);
pose();
}));
}
choices('axis-seg',d=>{axis=d.axis});
choices('speed-seg',d=>{dur=+d.ms});
choices('depth-seg',d=>{depth=+d.f});
slowTog.addEventListener('change',pose);
showPage(0);
</script>
</body>
</html>