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
feat: Heart / Like Burst shows the paths the pieces fly and the rings the heart pops between (See inside) and Color only beside Pops and bursts (Compare)
matine7afdc6da4b4
diff --git a/animations/04-micro-interactions/heart-burst/index.html b/animations/04-micro-interactions/heart-burst/index.htmlindex 86a12d6d..3ab87bcd 100644--- a/animations/04-micro-interactions/heart-burst/index.html+++ b/animations/04-micro-interactions/heart-burst/index.html@@ -35,6 +35,27 @@.count{font-size:12px;color:var(--ui-muted);z-index:2}.count b{color:var(--ui-text)}@media(prefers-reduced-motion:reduce){.like-btn.pop .heart{animation:none}}+ /* See inside and Compare: words on a dark backing over the canvas (the script places See inside's round the heart) */+ .ring,.cap,.twin{display:none}+ .cap{position:absolute;z-index:3;width:max-content;max-width:var(--w,240px);padding:4px 9px;border-radius:6px;background:rgba(11,11,13,.9);+ color:#f4f4f2;font:600 13px/17px var(--hb-font);pointer-events:none}+ /* See inside: dashed rings round the heart at the pop's smallest and biggest sizes (the script sizes them from its keyframes) */+ .ring{position:absolute;left:50%;top:50%;border:1.5px dashed rgba(244,244,242,.75);border-radius:50%;transform:translate(-50%,-50%);pointer-events:none}+ .stage[data-hb-mode="inside"] .ring,.stage[data-hb-mode="inside"] .cap.in{display:block}+ /* Compare: the scene twice, side by side at every width: on the left a copy that only changes color, on the right the heart itself */+ .stage[data-hb-mode="compare"]{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));align-content:center;justify-items:center;gap:20px 0}+ .stage[data-hb-mode="compare"]::after{content:'';position:absolute;top:0;bottom:0;left:50%;border-left:1px solid rgba(244,244,242,.14)}+ .stage[data-hb-mode="compare"] .twin{display:flex;grid-area:1/1/3/2;flex-direction:column;align-items:center;gap:20px}+ .stage[data-hb-mode="compare"] .like-wrap{grid-area:1/2}+ .stage[data-hb-mode="compare"]>.count{grid-area:2/2}+ .stage[data-hb-mode="compare"] .cap.half{display:block;top:10px}+ .twin .heart{margin:16px}.twin.on .heart{color:var(--like)}+ .half.first{left:10px}.half.second{left:calc(50% + 10px)}+ /* The still both views rest on, a quarter of a second into a like: the hearts filled, the real one held at that point of its pop */+ .stage[data-hb-mode="inside"].posed .heart,.stage[data-hb-mode="compare"].posed .heart{color:var(--like)}+ .stage[data-hb-mode="inside"].posed .like-btn path,.stage[data-hb-mode="compare"].posed .like-btn path{transform-box:view-box;+ transform-origin:12px 12px;animation:pop .5s cubic-bezier(.22,1,.36,1) -.25s paused}+ @media(max-width:600px){.cap{padding:3px 7px;font-size:12px;line-height:16px}}</style><link rel="stylesheet" href="../../../assets/css/demo-page.css?v=10"><script src="../../../assets/js/demo-page.js?v=10" defer></script>@@ -57,19 +78,35 @@<span class="hb-num" aria-hidden="true">1</span><div><h2 id="hb-watch-title">Click it</h2><p>Click or tap the heart to like it and again to unlike it, 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"><canvas id="cv" aria-hidden="true"></canvas><div class="like-wrap"><button class="like-btn" type="button" aria-pressed="false" aria-label="Like"><svg class="heart" viewBox="0 0 24 24" aria-hidden="true"><path fill="currentColor" d="M12 21S3.25 15.4 3.25 9.6C3.25 6.9 5.2 5 7.7 5c1.8 0 3.3 1 4.3 2.7C13 6 14.5 5 16.3 5c2.5 0 4.45 1.9 4.45 4.6C20.75 15.4 12 21 12 21z"/></svg></button>+ <span class="ring" aria-hidden="true"></span><span class="ring" aria-hidden="true"></span></div><div class="count">Likes <b id="count">128</b></div>+ <p class="cap in up" aria-hidden="true" data-hb-caption>Each piece flies out, a little upward</p>+ <p class="cap in end" aria-hidden="true" data-hb-caption>Gravity bends its path down as it fades</p>+ <p class="cap in rings" aria-hidden="true" data-hb-caption>The heart squashes to the inner ring, swells to the outer, then settles</p>+ <p class="cap in time" aria-hidden="true" data-hb-caption>All over in about three quarters of a second</p>+ <p class="cap half first" aria-hidden="true" data-hb-caption>Color only</p>+ <p class="cap half second" aria-hidden="true" data-hb-caption>Pops and bursts</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><label class="hb-toggle"><input class="hb-switch" type="checkbox" role="switch" id="slow-tog" data-hb-slowmo="css" autocomplete="off"><span>Slow motion</span></label></div>+ <div class="hb-mode-notes" aria-live="polite">+ <p data-hb-for="inside" hidden>Inside, the lines are the paths the pieces fly, pulled down as they fade; the rings show how the heart squashes and swells. Click the heart, or press Show me.</p>+ <p data-hb-for="compare" hidden>Shown just after a like: Color only fills the heart; Pops and bursts also pops it and sprays small hearts. Click the heart, or press Show me.</p>+ </div></section><section class="hb-step hb-try" aria-labelledby="hb-try-title">@@ -143,26 +180,34 @@slowTog=document.getElementById('slow-tog'),reduce=window.matchMedia('(prefers-reduced-motion: reduce)');const FRAME=1000/60; // one frame of a 60 Hz screen, in ms: every step below is measured in theselet liked=false,count=128,particles=[],raf=null,last=null,dpr=1,pCount=18,spread=90,runTimers=[];+ let mode='normal',posed=false,poseTimer=0,kept=null; // See inside and Compare (see the end of the script)// The canvas has one pixel per screen pixel (two at most per CSS pixel), so the hearts stay sharp on dense screens.+ // Resizing wipes it, so a mode's still is drawn and its words are placed again.function resize(){dpr=Math.min(window.devicePixelRatio||1,2);cv.width=Math.round(stage.clientWidth*dpr);cv.height=Math.round(stage.clientHeight*dpr);ctx.setTransform(dpr,0,0,dpr,0,0);+ if(mode!=='normal'){draw();place();}}resize();new ResizeObserver(resize).observe(stage);+ // A piece of a burst from x, y in a random direction (r gives the random numbers: Math.random for a real burst, a fixed series+ // for the still), launched at the speed of How far they fly with a small upward lean; o keeps its start, for its path+ function piece(i,x,y,r){+ const a=r()*Math.PI*2, v=spread*(0.5+r()*0.5)/12, vx=Math.cos(a)*v, vy=Math.sin(a)*v-1;+ return {x,y,vx,vy,life:1,size:4+r()*5,hue:['#ff5470','#ff9d5c','#ffd166','#ff85a1'][i%4],heart:r()>0.4,o:[x,y,vx,vy]};+ }+ // Where a burst starts: the heart's center, in the stage+ function origin(){const b=btn.getBoundingClientRect(),s=stage.getBoundingClientRect();return [b.left+b.width/2-s.left,b.top+b.height/2-s.top]}function spawn(){if(dpr!==Math.min(window.devicePixelRatio||1,2))resize();- const b=btn.getBoundingClientRect(),s=stage.getBoundingClientRect();- const ox=b.left+b.width/2-s.left, oy=b.top+b.height/2-s.top;- for(let i=0;i<pCount;i++){- const a=Math.random()*Math.PI*2, v=spread*(0.5+Math.random()*0.5)/12;- particles.push({x:ox,y:oy,vx:Math.cos(a)*v,vy:Math.sin(a)*v-1,life:1,size:4+Math.random()*5,- hue:['#ff5470','#ff9d5c','#ffd166','#ff85a1'][i%4],heart:Math.random()>0.4});- }+ const [ox,oy]=origin();+ for(let i=0;i<pCount;i++)particles.push(piece(i,ox,oy,Math.random));if(!raf){last=null;raf=requestAnimationFrame(tick)}}+ // One step of a piece, h 60 Hz frames long: it moves, gravity pulls it down, drag slows it sideways, and it fades+ function step(p,h,drag){p.x+=p.vx*h;p.y+=p.vy*h;p.vy+=0.12*h;p.vx*=drag;p.life-=0.022*h}function tick(ts){ctx.clearRect(0,0,cv.width,cv.height);particles=particles.filter(p=>p.life>0);@@ -172,14 +217,21 @@// Slow motion: every piece moves a third of its usual step. It is read every frame, so it applies from the next one.// A step over 1.5 frames (a 30 Hz screen) is taken in two halves, which keeps the arc close to the one a 60 Hz screen draws.const k=dt/FRAME*(slowTog.checked?1/3:1),parts=k>1.5?2:1,h=k/parts,drag=0.98**h;+ ctx.save();+ if(mode==='compare')half(); // Compare draws the burst in its second half only+ if(mode==='inside')particles.forEach(trail); // See inside draws each piece's path under the piecesfor(const p of particles){- for(let i=0;i<parts;i++){p.x+=p.vx*h;p.y+=p.vy*h;p.vy+=0.12*h;p.vx*=drag;p.life-=0.022*h}- ctx.globalAlpha=Math.max(p.life,0);ctx.fillStyle=p.hue;- if(p.heart){drawHeart(p.x,p.y,p.size);}- else{ctx.beginPath();ctx.arc(p.x,p.y,p.size*0.5,0,Math.PI*2);ctx.fill();}+ for(let i=0;i<parts;i++)step(p,h,drag);+ dot(p);}- ctx.globalAlpha=1;+ ctx.restore();raf=particles.length?requestAnimationFrame(tick):null;+ if(!raf)settle(HOLD);+ }+ function dot(p){+ ctx.globalAlpha=Math.max(p.life,0);ctx.fillStyle=p.hue;+ if(p.heart){drawHeart(p.x,p.y,p.size);}+ else{ctx.beginPath();ctx.arc(p.x,p.y,p.size*0.5,0,Math.PI*2);ctx.fill();}}function drawHeart(x,y,s){ctx.save();ctx.translate(x,y);ctx.scale(s/24,s/24);ctx.beginPath();@@ -189,16 +241,19 @@// Liking fills the heart and, unless the visitor asks for reduced motion, pops it and bursts the pieces; unliking only takes the color away.// The click and Show me both come through here.+ // In See inside and Compare the still goes first, so the like or unlike plays from the real state, and the copy follows.function setLiked(on){if(on===liked)return;+ lift();liked=on;- btn.classList.toggle('on',liked);+ btn.classList.toggle('on',liked);twin.classList.toggle('on',liked);btn.setAttribute('aria-pressed',liked);if(liked){count++;if(!reduce.matches){btn.classList.remove('pop');void btn.offsetWidth;btn.classList.add('pop');spawn();}}else{count--;}- countEl.textContent=count;+ countEl.textContent=twinNum.textContent=count;+ settle(HOLD);}btn.addEventListener('click',()=>setLiked(!liked));@@ -210,16 +265,22 @@}function running(){return runTimers.length>0}function stopRun(){runTimers.forEach(clearTimeout);runTimers=[]}- // A run starts from the arrival state, put there without animating: the transition is turned off, the state is set, a reflow makes it- // stick, and the transition comes back. A burst still in the air goes too.+ // A run starts from the arrival state, put there without animating (see showState). A burst still in the air goes too.function toRest(){- heart.style.transition='none';- btn.classList.remove('on','pop');- btn.setAttribute('aria-pressed','false');- liked=false;count=128;countEl.textContent=count;+ lift();+ btn.classList.remove('pop');+ liked=false;count=128;particles=[];ctx.clearRect(0,0,cv.width,cv.height);+ showState();+ }+ // Shows liked, the count and a mode's still at once on the heart, Compare's copy and both counts: the color transition is turned+ // off, the state is set, a reflow makes it stick, and the transition comes back.+ function showState(){+ heart.style.transition=twinHeart.style.transition='none';+ btn.classList.toggle('on',liked);twin.classList.toggle('on',liked);btn.setAttribute('aria-pressed',liked);+ countEl.textContent=twinNum.textContent=count;stage.classList.toggle('posed',posed);void btn.offsetWidth;- heart.style.transition='';+ heart.style.transition=twinHeart.style.transition='';}// The heart is liked after 300ms of rest, and unliked once the 750ms burst and 950ms more of rest have passed.document.getElementById('btn-demo').addEventListener('click',()=>{@@ -229,7 +290,7 @@later(()=>setLiked(false),750,1250);});// The visitor pressed, typed, scrolled or touched inside the stage: the run stops and the heart stays as it is.- document.addEventListener('hb:input',()=>{if(running())stopRun()});+ document.addEventListener('hb:input',()=>{if(running()){stopRun();settle(HOLD)}});function choices(id,pick){const buttons=document.querySelectorAll('#'+id+' button');@@ -238,8 +299,96 @@pick(b.dataset);}));}- choices('num-seg',d=>{pCount=+d.n});- choices('far-seg',d=>{spread=+d.px});+ // A setting shows at the next like, and at once in a mode's still and words+ choices('num-seg',d=>{pCount=+d.n;redraw()});+ choices('far-seg',d=>{spread=+d.px;redraw()});++ // See inside and Compare. HOLD: how long the end of a like stays in view before the still comes back (ms). POSE: the still's moment,+ // a quarter of a second into a like, in 60 Hz steps (as the heart's held pop in the style). SEED: the fixed series of random numbers+ // the still's burst comes from, so every still is the same. REACH: how far the heart reaches from its center, as a share of its box.+ const HOLD=700,POSE=15,SEED=347,REACH=.38;+ const [capUp,capEnd,capRings,capTime]=stage.querySelectorAll('.cap.in');+ // The rings, at the pop's smallest and biggest sizes (from its keyframes in the style above); STEPS: the 60 Hz steps a piece lasts+ const sizes=[...[...document.styleSheets[0].cssRules].find(r=>r.name==='pop').cssRules].map(k=>parseFloat(k.style.transform.replace(/[^\d.]/g,'')));+ const HIGH=Math.max(...sizes),STEPS=(()=>{const q={x:0,y:0,vx:0,vy:0,life:1};let n=0;while(q.life>0){step(q,1,1);n++}return n})();+ stage.querySelectorAll('.ring').forEach((el,i)=>{el.style.width=el.style.height=2*REACH*heart.clientWidth*[Math.min(...sizes),HIGH][i]+'px'});+ // Compare's first half: a copy of the heart and its count that only changes color, out of reach of the keyboard and screen readers+ const twin=document.createElement('div'),twinHeart=heart.cloneNode(true),twinCount=countEl.parentElement.cloneNode(true),twinNum=twinCount.firstElementChild;+ twin.className='twin';twin.inert=true;twin.setAttribute('aria-hidden','true');twinNum.removeAttribute('id');twin.append(twinHeart,twinCount);stage.append(twin);+ // Under reduced motion both views are still pictures, and their notes say so (the page's own words otherwise)+ const STILL={inside:'Inside, shown still: the lines are the paths the pieces would fly and the rings how the heart would pop. With reduced motion on, a like only fills the heart.',+ compare:'Shown still, just after a like: Color only fills the heart; Pops and bursts also pops it and sprays small hearts. With reduced motion on, both only fill.'};+ const noteTexts=[...document.querySelectorAll('[data-hb-for]')].map(n=>[n,n.textContent]);+ function noteWords(){for(const [n,t] of noteTexts)n.textContent=reduce.matches?STILL[n.dataset.hbFor]:t}+ noteWords();reduce.addEventListener('change',noteWords);++ function fixed(){let s=SEED;return()=>{s=s+0x6D2B79F5|0;let t=Math.imul(s^s>>>15,1|s);t=t+Math.imul(t^t>>>7,61|t)^t;return((t^t>>>14)>>>0)/4294967296}}+ function still(){const r=fixed(),[x,y]=origin();return Array.from({length:pCount},(_,i)=>piece(i,x,y,r))}+ function half(){const w=stage.clientWidth;ctx.beginPath();ctx.rect(w/2,0,w/2,stage.clientHeight);ctx.clip()}+ // A piece's whole path: the same step run ahead in 60 Hz steps until it has faded, worked out once+ function pathOf(p){+ if(!p.path){const q={x:p.o[0],y:p.o[1],vx:p.o[2],vy:p.o[3],life:1};p.path=[p.o];while(q.life>0){step(q,1,.98);p.path.push([q.x,q.y])}}+ return p.path;+ }+ // See inside: the path as a faint line out of the heart, with a small ring where the piece fades+ function trail(p){+ const pts=pathOf(p),[x,y]=pts[pts.length-1];+ ctx.lineWidth=1.25;ctx.strokeStyle=p.hue;ctx.globalAlpha=.4;ctx.beginPath();for(const [px,py] of pts)ctx.lineTo(px,py);ctx.stroke();+ ctx.globalAlpha=.85;ctx.beginPath();ctx.arc(x,y,3,0,Math.PI*2);ctx.stroke();+ }+ // The canvas at rest in a mode: the still's burst POSE steps in, each piece at its strength then, over every path of it in See+ // inside, in the second half only in Compare. A look only: liked, the count and a real burst's pieces are never touched.+ function draw(){+ ctx.clearRect(0,0,cv.width,cv.height);+ if(!posed)return;+ const plan=still();+ ctx.save();+ if(mode==='compare')half();else plan.forEach(trail);+ for(const p of plan){for(let n=0;n<POSE;n++)step(p,1,.98);dot(p)}+ ctx.restore();+ }+ // Puts the still on or takes it off at once (its class holds the heart filled and part-way into its pop)+ function pose(on){posed=on;showState();draw()}+ function lift(){clearTimeout(poseTimer);poseTimer=0;if(posed)pose(false)}+ // The still comes back in See inside and Compare once nothing goes on (no piece in the air, no Show me step waiting): after a+ // change it waits HOLD first, so the end of the like is seen; a mode press shows it at once.+ function settle(wait){+ clearTimeout(poseTimer);poseTimer=0;+ if(mode!=='normal'&&!raf&&!running()){if(wait)poseTimer=setTimeout(()=>settle(0),wait);else pose(true)}+ }+ function redraw(){if(posed)draw();place()}+ // See inside's words round the heart as it is now, 8px or more inside the box: the upward flight above it on the left, the rings'+ // beside them, the time (three times as long in Slow motion) below it on the right, and gravity's under the end of the still's+ // farthest path that ends low on the left inside the box (else in the lower left corner)+ function place(){+ const s=STEPS*FRAME*(slowTog.checked?3:1)/1000;+ capTime.textContent='All over in about '+(s<.9?'three quarters of a second':s<1.5?'a second':s<2.5?'two seconds':'three seconds');+ if(mode!=='inside')return;+ const W=stage.clientWidth,H=stage.clientHeight,[x,y]=origin(),R=REACH*heart.clientWidth*HIGH,m=8;+ const put=(el,w,left,top)=>{+ el.style.setProperty('--w',Math.max(w,100)+'px');+ const ew=el.offsetWidth,eh=el.offsetHeight;+ el.style.left=Math.max(m,Math.min(left(ew,eh),W-m-ew))+'px';el.style.top=Math.max(m,Math.min(top(ew,eh),H-m-eh))+'px';+ };+ put(capRings,Math.min(250,W-m-x-R-12),()=>x+R+12,(w,h)=>y-h/2);+ put(capUp,Math.min(250,x-16-m),w=>x-16-w,()=>m);+ put(capTime,Math.min(320,W-m-x-16),()=>x+16,(w,h)=>H-m-h);+ const e=still().map(p=>{const pts=pathOf(p);return pts[pts.length-1]}).filter(([ex,ey])=>ex<x-R&&ex>m+20&&ey>y+R&&ey<H-m-40).sort((a,b)=>a[0]-b[0])[0];+ put(capEnd,Math.min(280,x-m),w=>e?e[0]-w/2:m,(w,h)=>e?e[1]+10:H-m-h);+ }+ // The mode switch: the still at once when nothing goes on, the words placed. The shared script then presses Show me (not under+ // reduced motion), which plays a like from the arrival state. So leaving Normal keeps its own state (liked, the count, copies of+ // the pieces in the air), and Normal takes the still off and puts that state back as it was, a burst going on from where it was.+ document.addEventListener('hb:mode',e=>{+ const was=mode;mode=e.detail.mode;+ if(mode!=='normal'){if(was==='normal')kept={liked,count,pieces:particles.map(p=>({...p}))};settle(0);place();return}+ lift();+ if(!kept)return;+ stopRun();({liked,count}=kept);particles=kept.pieces;kept=null;showState();+ if(particles.length&&!raf){last=null;raf=requestAnimationFrame(tick)}+ });+ slowTog.addEventListener('change',place);+ document.fonts.ready.then(place);</script></body></html>