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: Depth-Map Photo (06.20)
matin03a8ec2cd6ca
diff --git a/README.md b/README.mdindex 6ddc499d..33b67605 100644--- a/README.md+++ b/README.md@@ -210,6 +210,7 @@ All 129 techniques, each linked to its live demo.- **[Morphing Blob](animations/06-3d-advanced/morphing-blob/)** — Blobs melt together, and one drop chases your pointer. Best for hero sections.- **[3D Flip Card](animations/06-3d-advanced/flip-card-3d/)** — A card turns over in 3D to show its back. Best for profile and product cards.- **[3D Carousel](animations/06-3d-advanced/carousel-3d/)** — Cards stand in a ring that spins in 3D as you drag it. Best for image galleries.+- **[Depth-Map Photo](animations/06-3d-advanced/depth-map-photo/)** — A flat picture turns 3D as you point: near parts shift more than far ones. Best for hero images.</details>diff --git a/animations/06-3d-advanced/README.md b/animations/06-3d-advanced/README.mdindex d0313427..94843c32 100644--- a/animations/06-3d-advanced/README.md+++ b/animations/06-3d-advanced/README.md@@ -25,6 +25,7 @@ WebGL, shaders, particles, 3D transforms, and the performance-sensitive effects| [Morphing Blob](morphing-blob/) | Blobs melt together, and one drop chases your pointer. Best for hero sections. || [3D Flip Card](flip-card-3d/) | A card turns over in 3D to show its back. Best for profile and product cards. || [3D Carousel](carousel-3d/) | Cards stand in a ring that spins in 3D as you drag it. Best for image galleries. |+| [Depth-Map Photo](depth-map-photo/) | A flat picture turns 3D as you point: near parts shift more than far ones. Best for hero images. |## Key conceptsdiff --git a/animations/06-3d-advanced/carousel-3d/index.html b/animations/06-3d-advanced/carousel-3d/index.htmlindex abaac06d..e41e6a03 100644--- a/animations/06-3d-advanced/carousel-3d/index.html+++ b/animations/06-3d-advanced/carousel-3d/index.html@@ -62,7 +62,7 @@<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="../flip-card-3d/" rel="prev" aria-label="Previous: 3D Flip Card"><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>3D Flip Card</span></a></span>+ <span class="hb-pager"><a href="../flip-card-3d/" rel="prev" aria-label="Previous: 3D Flip Card"><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>3D Flip Card</span></a><a href="../depth-map-photo/" rel="next" aria-label="Next: Depth-Map Photo"><span><span class="hb-dir">Next: </span>Depth-Map Photo</span><svg class="hb-ic" viewBox="0 0 24 24" aria-hidden="true"><path d="m9 18 6-6-6-6"/></svg></a></span></nav><main class="hb-page"><header class="hb-head">diff --git a/animations/06-3d-advanced/depth-map-photo/README.md b/animations/06-3d-advanced/depth-map-photo/README.mdnew file mode 100644index 00000000..471676fe--- /dev/null+++ b/animations/06-3d-advanced/depth-map-photo/README.md@@ -0,0 +1,69 @@+# Depth-Map Photo++## What it is+A depth-map photo makes a flat picture look three-dimensional when you point at it. Beside the picture sits a grayscale depth map of the same size, white where things are near and black where they are far, and as the pointer moves, each part of the picture shifts by an amount set by its gray. Near parts slide further than far ones, and the eye reads the difference as depth, the way it does when you move your head.++## When to use it+- Hero images and page headers that invite the pointer to explore+- Travel, landscape and portfolio photos with a clear foreground and background+- Album art, posters and book covers+- Product shots where the product stands in front of a plain background++## How it works+Two pictures go to the graphics chip as textures: the photo and its depth map. The demo draws both itself on 2D canvases, from the same six shapes (sky, mountains, hills, meadow, tree and ground): once in color, and once with each shape filled with its gray. It paints them a little larger than the stage, so the largest shift never shows an edge. Then it grows the near shapes in the depth map by a few pixels and blurs the map a touch:++```js+b.drawImage(depth, 0, 0);+b.globalCompositeOperation = 'lighten'; // keep the lighter (nearer) value of each pixel+for (let i = 0; i < 16; i++) b.drawImage(depth, Math.cos(i * Math.PI / 8) * r, Math.sin(i * Math.PI / 8) * r);+b.globalCompositeOperation = 'source-over';+b.filter = 'blur(2px)';+b.drawImage(b.canvas, 0, 0);+```++A fragment shader then draws every pixel of the stage. A spot of the picture at depth `t` moves by the pointer's offset times `t − focus`, where focus is the depth that holds still (the hills, at 0.4). To draw a pixel the shader works backward: it tries depths from the nearest to the farthest, looks up the depth map at the spot each try would come from, and stops at the first spot that is at least as near as the try. So the nearest surface wins, as it covers what is behind it, and the last step is refined between the two tries:++```glsl+float t = 1., h = texture2D(uDep, uv + uOff * (1. - uFocus)).r - 1., tp = t, hp = h;+for (int i = 0; i < 20; i++) {+ if (h >= 0.) break;+ tp = t; hp = h; t -= .05;+ h = texture2D(uDep, uv + uOff * (t - uFocus)).r - t;+}+if (hp < 0. && h >= 0.) t = mix(tp, t, hp / (hp - h));+vec2 p = uv + uOff * (t - uFocus);+gl_FragColor = vec4(texture2D(uImg, p).rgb, 1.); // Show the depth map mixes in the map's gray here+```++Where a near shape moves aside, it uncovers a strip the photo never had, and the search fills it by stretching the pixels at the shape's edge. Because the near shapes were grown in the depth map, those edge pixels are background, so the strip fills with background instead of a smear of the tree.++The view glides toward the pointer by elapsed time, so it moves at the same speed at any frame rate:++```js+const k = 1 - Math.pow(1 - 0.1, dt / FRAME); // 10% of the gap every 60th of a second+sx += (ax - sx) * k; sy += (ay - sy) * k; // a: where the pointer aims, s: where the view is (-1 to 1)+gl.uniform2f(uOff, O * sx / SW, -0.5 * O * sy / SH); // O: the depth strength times the stage's width+```++Pointer Events make a mouse, a pen and a finger aim the view alike; a mouse that leaves or a finger that lifts sends it back to the middle. Show me moves the view around a figure of eight for three seconds and back to the middle. Without WebGL, the demo draws the six shapes on a 2D canvas every frame instead, each moved by its own depth, the way 2.5D layers move. Under reduced motion the picture does not follow the pointer, and Show me shows the view from one side for 1.2 seconds, with no movement in between, then the view from the front.++## Key parameters+| Parameter | Default | Effect |+|-----------|---------|--------|+| Depth strength | Medium | How far the nearest part slides against the farthest when the pointer reaches the edge of the picture: subtle is 2%, medium 4% and strong 6% of the picture's width; up and down move half as far |+| Show the depth map | off | Shows the gray depth map in place of the picture, moving the same way: white is near and black is far |++## Production notes+- **Getting a depth map**: depth-estimation models (MiDaS, Depth Anything) make one from any photo, phones save one with portrait-mode photos, and an image editor can paint one by hand, one gray shape per layer. Save it as a grayscale image the same size as the photo.+- **Edges**: where a near object moves, it uncovers background the photo never had. Keep the strength low, grow the near shapes in the depth map by a few pixels and blur it a little; a hand-made map with clean outlines helps most.+- **Textures**: use linear filtering and clamp-to-edge wrapping, which lets WebGL 1 take an image of any size without mipmaps. Flip the image on upload (`UNPACK_FLIP_Y_WEBGL`), and serve images from the same origin or with CORS headers, or WebGL refuses to read them.+- **Tilt on phones**: the phone's own tilt (`deviceorientation`) can drive the shift instead of a finger; iOS asks the visitor for permission first.+- **Performance**: the shader reads the depth map about twenty times per pixel, which is cheap for a graphics chip. The demo caps the pixel density at 2 (1.5 on phones) and draws only while the view moves.+- **Context loss**: a GPU reset or a restored tab fires `webglcontextlost`; call `preventDefault()` on it, and rebuild the shader and upload the textures again on `webglcontextrestored`.+- **Libraries**: Three.js runs the same shader in a `ShaderMaterial`, or pushes a mesh out by the depth map; PixiJS has a `DisplacementFilter`; Facebook's 3D photos turn the depth map into a mesh and fill in the hidden background.++## See also+- [2.5D / Pseudo-3D](../2-5d-pseudo-3d/) — flat layers that slide by different amounts+- [Image Distortion on Hover](../image-distortion-hover/) — a shader that moves pixels around the pointer+- [Parallax 3D Tilt](../parallax-3d-tilt/) — a card leans toward the pointer+- [3D Carousel](../carousel-3d/) — cards in a ring that turns in 3Ddiff --git a/animations/06-3d-advanced/depth-map-photo/index.html b/animations/06-3d-advanced/depth-map-photo/index.htmlnew file mode 100644index 00000000..9039b7c8--- /dev/null+++ b/animations/06-3d-advanced/depth-map-photo/index.html@@ -0,0 +1,315 @@+<!DOCTYPE html>+<html lang="en">+<head>+ <meta charset="UTF-8">+ <meta name="viewport" content="width=device-width, initial-scale=1.0">+ <title>Depth-Map Photo — Animation Handbook</title>+ <meta name="description" content="A flat picture turns 3D as you point: near parts shift more than far ones. Best for hero images.">+ <link rel="canonical" href="https://matinmonshizadeh.github.io/animation-handbook/animations/06-3d-advanced/depth-map-photo/">+ <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="Depth-Map Photo — Animation Handbook">+ <meta property="og:description" content="A flat picture turns 3D as you point: near parts shift more than far ones. Best for hero images.">+ <meta property="og:url" content="https://matinmonshizadeh.github.io/animation-handbook/animations/06-3d-advanced/depth-map-photo/">+ <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="Depth-Map Photo — Animation Handbook">+ <meta name="twitter:description" content="A flat picture turns 3D as you point: near parts shift more than far ones. Best for hero images.">+ <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": "Depth-Map Photo", "name": "Depth-Map Photo", "description": "A flat picture turns 3D as you point: near parts shift more than far ones. Best for hero images.", "url": "https://matinmonshizadeh.github.io/animation-handbook/animations/06-3d-advanced/depth-map-photo/", "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, Depth-Map Photo"}</script>+ <style>+ :root{--ui-accent:#3fd6c4}+ *,*::before,*::after{box-sizing:border-box;margin:0;padding:0}+ .stage{position:relative;background:#0b0b0d}+ /* A finger dragged on the picture moves the view in both directions, so the picture keeps the touch to itself */+ canvas{display:block;width:100%;height:100%;touch-action:none}+ </style>+ <link rel="stylesheet" href="../../../assets/css/demo-page.css?v=6">+ <script src="../../../assets/js/demo-page.js?v=6" 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="../carousel-3d/" rel="prev" aria-label="Previous: 3D Carousel"><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>3D Carousel</span></a></span>+</nav>+<main class="hb-page">+ <header class="hb-head">+ <p class="hb-cat">06.20 · 3D & Advanced</p>+ <h1>Depth-Map Photo</h1>+ <p class="hb-lede">A flat picture turns 3D as you point: near parts shift more than far ones. Best for hero images.</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 picture, drag a finger across it, or press Show me.</p></div>+ </div>+ <div class="stage" id="stage">+ <canvas id="cvs" role="img" aria-label="A drawn sunset landscape: a low sun, far mountains, hills, a meadow, and a tree and a rock in front. As the pointer moves, the near parts shift more than the far ones."></canvas>+ </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>+ </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="str-lbl">Depth strength</p>+ <div class="seg" id="str-seg" role="group" aria-labelledby="str-lbl">+ <button type="button" data-str=".02" aria-pressed="false">Subtle</button>+ <button type="button" data-str=".04" class="on" aria-pressed="true">Medium</button>+ <button type="button" data-str=".06" aria-pressed="false">Strong</button>+ </div>+ <p class="hb-hint">How far the near parts slide against the far ones.</p>+ </div>+ <div class="hb-setting">+ <label class="hb-switch-row"><span>Show the depth map</span><input class="hb-switch" type="checkbox" role="switch" id="map-tog" autocomplete="off"></label>+ <p class="hb-hint">The gray picture behind the effect: white is near, black is far.</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 depth effect to [the photo you want to bring to life]. Make a grayscale depth map the same size as the photo, white for near parts and black for far ones, and blur it slightly. Draw the photo with a WebGL shader that reads each pixel from a spot shifted by the pointer's position times that pixel's depth, so near parts move more than far ones and the flat photo looks three-dimensional. Zoom in a little so the edges never show, and let the view glide toward the pointer and back to the middle when it leaves. On touch screens, dragging a finger should do the same. If the visitor has reduced motion turned on, keep the photo still. 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>+ </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>Hero images</li><li>Portfolio photos</li><li>Travel stories</li><li>Album art</li></ul>+ <h3>Avoid on</h3>+ <ul class="hb-tags hb-avoid"><li>Photos with text</li><li>Small thumbnails</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="#top">Back to top ↑</a></footer>+<script>+const VS='attribute vec2 a;varying vec2 v;void main(){v=a*.5+.5;gl_Position=vec4(a,0.,1.);}';+// Each screen pixel shows the spot of the picture that the shift sends to it. A spot at depth t would come from uv+uOff*(t-uFocus),+// so the loop tries depths from the nearest (1) to the farthest (0) and stops at the first spot whose own depth is at least the+// one tried: the nearest surface wins, as it covers what is behind it. The last step is then refined between the two tries.+// uOff is the shift for a whole step of depth (texture units), uFocus the depth that holds still.+const FS=`precision mediump float;varying vec2 v;uniform sampler2D uImg,uDep;uniform vec2 uOff,uZoom;uniform float uFocus,uMap;+void main(){+ vec2 uv=.5+(v-.5)*uZoom;+ float t=1.,h=texture2D(uDep,uv+uOff*(1.-uFocus)).r-1.,tp=t,hp=h;+ for(int i=0;i<20;i++){+ if(h>=0.)break;+ tp=t;hp=h;t-=.05;+ h=texture2D(uDep,uv+uOff*(t-uFocus)).r-t;+ }+ if(hp<0.&&h>=0.)t=mix(tp,t,hp/(hp-h));+ vec2 p=uv+uOff*(t-uFocus);+ gl_FragColor=vec4(mix(texture2D(uImg,p).rgb,vec3(texture2D(uDep,p).r),uMap),1.);+}`;+const stage=document.getElementById('stage');+let cvs=document.getElementById('cvs');+const reduce=matchMedia('(prefers-reduced-motion:reduce)');+const PHONE=matchMedia('(max-width:600px),(max-height:500px)'); // phones: up to 600px wide, or 500px tall when held sideways+const FRAME=1000/60,K=.1,RUN_MS=3000,FOCUS=.4,MAXSTR=.06; // the hills (depth .45) hold almost still+let gl=null,g2=null,U={},W=0,H=0,SW=0,SH=0;+let STR=.04,MAP=0,ax=0,ay=0,sx=0,sy=0,run=null,raf=0,lastT=null,holdTimer=0; // a: where the pointer aims, s: where the view is (-1 to 1)++// The picture, far to near, as [depth, draw]. draw(g, w, h, c, m, dm) paints one layer; c(color) gives the color, or in the depth+// map (dm) the layer's gray; m is the shorter side, so round things stay round on a stage of any shape.+const gray=d=>{const n=Math.round(d*255);return `rgb(${n},${n},${n})`;};+const dot=(g,x,y,r)=>{g.beginPath();g.arc(x,y,r,0,7);g.fill();};+function hill(g,w,h,y0,amp,f,ph){g.beginPath();g.moveTo(0,h);for(let i=0;i<=48;i++)g.lineTo(i/48*w,(y0+amp*Math.sin(i/48*f+ph))*h);g.lineTo(w,h);g.fill();}+const LAYERS=[+ [0,(g,w,h,c,m,dm)=>{ // sky and sun+ const s=g.createLinearGradient(0,0,0,h*.68);+ [[0,'#1b2452'],[.45,'#4c3a7a'],[.78,'#c96a78'],[1,'#f4b16c']].forEach(([t,col])=>s.addColorStop(t,c(col)));+ g.fillStyle=s;g.fillRect(0,0,w,h);+ if(!dm){const r=g.createRadialGradient(w*.7,h*.32,0,w*.7,h*.32,m*.32);r.addColorStop(0,'rgba(255,224,170,.5)');r.addColorStop(1,'rgba(255,224,170,0)');g.fillStyle=r;g.fillRect(0,0,w,h);}+ g.fillStyle=c('#fff1cf');dot(g,w*.7,h*.32,m*.065);+ }],+ [.2,(g,w,h,c)=>{ // far mountains+ g.fillStyle=c('#6d5a96');g.beginPath();g.moveTo(0,h);+ [[0,.55],[.07,.47],[.14,.52],[.24,.38],[.33,.49],[.42,.43],[.5,.5],[.6,.4],[.7,.49],[.79,.42],[.88,.5],[.95,.46],[1,.52]].forEach(([x,y])=>g.lineTo(x*w,y*h));+ g.lineTo(w,h);g.fill();+ }],+ [.45,(g,w,h,c)=>{g.fillStyle=c('#3f5f86');hill(g,w,h,.62,.035,7,.6);}], // hills+ [.65,(g,w,h,c)=>{g.fillStyle=c('#2f6150');hill(g,w,h,.72,.03,5,2.2);}], // meadow+ [.85,(g,w,h,c,m)=>{ // tree+ const x=w*.25;g.fillStyle=c('#3b2a22');g.fillRect(x-m*.016,h*.55,m*.032,h*.33);+ g.fillStyle=c('#23503f');dot(g,x,h*.47,m*.13);dot(g,x-m*.1,h*.54,m*.1);dot(g,x+m*.1,h*.54,m*.1);+ g.fillStyle=c('#2f6a52');dot(g,x-m*.035,h*.43,m*.07);+ }],+ [.92,(g,w,h,c,m,dm)=>{ // ground, nearer toward the bottom, and a rock+ const s=g.createLinearGradient(0,h*.8,0,h);s.addColorStop(0,dm?gray(.88):'#1f3e2c');s.addColorStop(1,dm?gray(1):'#0d1f15');+ g.fillStyle=s;hill(g,w,h,.84,.012,9,1);+ g.fillStyle=c('#4a4658',1);g.beginPath();g.ellipse(w*.76,h*.91,m*.11,m*.06,0,0,7);g.fill();+ g.fillStyle=c('#615b70',1);g.beginPath();g.ellipse(w*.75,h*.89,m*.07,m*.03,0,0,7);g.fill();+ }]+];+const colorOf=(d,dm)=>(col,dd)=>dm?gray(dd??d):col;++function initGL(){+ gl=cvs.getContext('webgl',{alpha:false});+ if(!gl)return false;+ const sh=(t,s)=>{const x=gl.createShader(t);gl.shaderSource(x,s);gl.compileShader(x);if(!gl.getShaderParameter(x,gl.COMPILE_STATUS))throw new Error(gl.getShaderInfoLog(x));return x;};+ try{+ const p=gl.createProgram();gl.attachShader(p,sh(gl.VERTEX_SHADER,VS));gl.attachShader(p,sh(gl.FRAGMENT_SHADER,FS));gl.linkProgram(p);+ if(!gl.getProgramParameter(p,gl.LINK_STATUS))throw new Error(gl.getProgramInfoLog(p));+ gl.useProgram(p);U={};['uImg','uDep','uOff','uZoom','uFocus','uMap'].forEach(n=>{U[n]=gl.getUniformLocation(p,n);});+ gl.bindBuffer(gl.ARRAY_BUFFER,gl.createBuffer());gl.bufferData(gl.ARRAY_BUFFER,new Float32Array([-1,-1,1,-1,-1,1,1,1]),gl.STATIC_DRAW);+ const a=gl.getAttribLocation(p,'a');gl.enableVertexAttribArray(a);gl.vertexAttribPointer(a,2,gl.FLOAT,false,0,0);+ [0,1].forEach(i=>{ // unit 0: the picture, unit 1: the depth map+ gl.activeTexture(gl.TEXTURE0+i);gl.bindTexture(gl.TEXTURE_2D,gl.createTexture());+ [gl.TEXTURE_MIN_FILTER,gl.TEXTURE_MAG_FILTER].forEach(f=>gl.texParameteri(gl.TEXTURE_2D,f,gl.LINEAR));+ [gl.TEXTURE_WRAP_S,gl.TEXTURE_WRAP_T].forEach(f=>gl.texParameteri(gl.TEXTURE_2D,f,gl.CLAMP_TO_EDGE));+ });+ gl.uniform1i(U.uImg,0);gl.uniform1i(U.uDep,1);gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL,true);+ return true;+ }catch(e){gl=null;return false;}+}+// Without WebGL (or if its shader fails) a fresh canvas draws the six layers in 2D, each moved by its own depth+function init2d(){const c=cvs.cloneNode(false);cvs.replaceWith(c);cvs=c;g2=cvs.getContext('2d');}++// The picture and its depth map are painted a little larger than the canvas (SW x SH), so the largest shift never shows an edge.+// Near shapes in the depth map are grown a little (the lighter of shifted copies), so a strip of background travels with each+// one and fills what it uncovers; then the map is blurred a touch, so its steps do not show as jagged edges.+function upload(){+ const make=dm=>{const c=document.createElement('canvas');c.width=SW;c.height=SH;const g=c.getContext('2d'),m=Math.min(SW,SH);+ LAYERS.forEach(([d,draw])=>draw(g,SW,SH,colorOf(d,dm),m,dm));return c;};+ const dep=make(true),map=document.createElement('canvas');map.width=SW;map.height=SH;+ const b=map.getContext('2d'),r=SW/150;+ b.drawImage(dep,0,0);b.globalCompositeOperation='lighten';+ for(let i=0;i<16;i++)b.drawImage(dep,Math.cos(i*Math.PI/8)*r*(i%2?.5:1),Math.sin(i*Math.PI/8)*r*(i%2?.5:1));+ b.globalCompositeOperation='source-over';b.filter=`blur(${Math.max(1,Math.round(SW/500))}px)`;b.drawImage(map,0,0);+ gl.activeTexture(gl.TEXTURE0);gl.texImage2D(gl.TEXTURE_2D,0,gl.RGBA,gl.RGBA,gl.UNSIGNED_BYTE,make(false));+ gl.activeTexture(gl.TEXTURE1);gl.texImage2D(gl.TEXTURE_2D,0,gl.RGBA,gl.RGBA,gl.UNSIGNED_BYTE,map);+}+// Setting the canvas size clears it, so nothing happens unless the size really changed. Pixel density is capped at 2, and at+// 1.5 on phones, where every extra pixel costs.+function layout(){+ const dpr=Math.min(devicePixelRatio||1,PHONE.matches?1.5:2);+ const w=Math.max(1,Math.round(stage.clientWidth*dpr)),h=Math.max(1,Math.round(stage.clientHeight*dpr));+ if(w===W&&h===H)return false;+ W=cvs.width=w;H=cvs.height=h;+ const z=Math.min(1/(1+2*MAXSTR*(1-FOCUS)),H/(H+MAXSTR*(1-FOCUS)*W)); // room for the strongest shift on every side+ SW=Math.ceil(W/z);SH=Math.ceil(H/z);+ if(gl){gl.viewport(0,0,W,H);upload();}+ return true;+}+// The nearest part moves STR of the picture's width against the farthest one at the edge; up and down move half as far.+function draw(){+ const O=STR*W;+ if(gl){+ gl.uniform2f(U.uOff,O*sx/SW,-.5*O*sy/SH);gl.uniform2f(U.uZoom,W/SW,H/SH);gl.uniform1f(U.uFocus,FOCUS);gl.uniform1f(U.uMap,MAP);+ gl.drawArrays(gl.TRIANGLE_STRIP,0,4);+ }else{+ const m=Math.min(SW,SH);+ LAYERS.forEach(([d,paint])=>{const k=d-FOCUS;g2.setTransform(1,0,0,1,(W-SW)/2-O*sx*k,(H-SH)/2-.5*O*sy*k);paint(g2,SW,SH,colorOf(d,MAP),m,MAP);});+ }+}++// The loop runs only while the view moves. Show me drives it along a figure of eight by its own clock; otherwise the view+// closes 10% of the gap to the pointer every 60th of a second.+function wake(){if(!raf){lastT=null;raf=requestAnimationFrame(tick);}}+function tick(ts){+ raf=0;+ const dt=lastT===null?0:Math.min(ts-lastT,50);lastT=ts;+ let more=false;+ if(run){+ if(run.t0===null)run.t0=ts;+ const p=Math.min(1,(ts-run.t0)/RUN_MS),e=p*p*(3-2*p);+ sx=.9*Math.sin(2*Math.PI*e);sy=.5*Math.sin(4*Math.PI*e);+ if(p<1)more=true;else{run=null;sx=sy=ax=ay=0;}+ }else{+ const k=1-Math.pow(1-K,dt/FRAME);+ sx+=(ax-sx)*k;sy+=(ay-sy)*k;+ if(Math.abs(ax-sx)+Math.abs(ay-sy)<.002){sx=ax;sy=ay;}else more=true;+ }+ draw();+ if(more)raf=requestAnimationFrame(tick);+}+document.addEventListener('visibilitychange',()=>{lastT=null;});++// Show me: three seconds around a figure of eight, back to the middle. Under reduced motion the picture never moves: it shows+// the view from one side for 1.2 s, then the view from the front again.+function stopHold(){clearTimeout(holdTimer);holdTimer=0;}+function still(x,y){run=null;sx=ax=x;sy=ay=y;cancelAnimationFrame(raf);raf=0;draw();}+document.getElementById('btn-demo').addEventListener('click',()=>{+ stopHold();+ if(reduce.matches){still(.9,-.4);holdTimer=setTimeout(()=>{holdTimer=0;still(0,0);},1200);return;}+ run={t0:null};wake();+});+// The visitor pressed, typed, scrolled or touched inside the stage: a run under way stops and the view glides back to the+// middle, unless the same press aims it somewhere (that comes next).+document.addEventListener('hb:input',()=>{+ if(holdTimer){stopHold();still(0,0);}+ if(run){run=null;ax=ay=0;wake();}+});++// Pointer Events, so a mouse, a pen and a finger all aim the view. Hovering sends no hb:input, so the visitor's own pointer+// ends a run here and takes over. A mouse that leaves, or a finger that lifts, sends the view back to the middle.+const clamp=v=>Math.max(-1,Math.min(1,v));+function aim(e){+ if(reduce.matches)return;+ const r=stage.getBoundingClientRect();+ ax=clamp((e.clientX-r.left)/r.width*2-1);ay=clamp((e.clientY-r.top)/r.height*2-1);wake();+}+const toMiddle=()=>{if(!run&&!reduce.matches){ax=ay=0;wake();}};+stage.addEventListener('pointerdown',aim);+stage.addEventListener('pointermove',e=>{if(e.isTrusted&&run&&!reduce.matches)run=null;aim(e);});+stage.addEventListener('pointerleave',toMiddle);+stage.addEventListener('pointerup',e=>{if(e.pointerType!=='mouse')toMiddle();});+stage.addEventListener('pointercancel',toMiddle);++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);+ }));+}+choices('str-seg',d=>{STR=+d.str;if(!raf)draw();});+document.getElementById('map-tog').addEventListener('change',e=>{+ MAP=e.target.checked?1:0;if(!raf)draw();+ cvs.setAttribute('aria-label',MAP?'The depth map of the landscape in gray: the sky is black, and the mountains, hills, meadow, tree and ground get lighter the nearer they are.':+ 'A drawn sunset landscape: a low sun, far mountains, hills, a meadow, and a tree and a rock in front. As the pointer moves, the near parts shift more than the far ones.');+});++if(!initGL())init2d();+layout();draw();+addEventListener('resize',()=>{if(layout())draw();});+if(gl){+ // A GPU reset or a restored tab loses the context; the textures are painted and uploaded again when it comes back+ cvs.addEventListener('webglcontextlost',e=>{e.preventDefault();cancelAnimationFrame(raf);raf=0;});+ cvs.addEventListener('webglcontextrestored',()=>{if(initGL()){W=H=0;layout();draw();}});+}+</script>+</body>+</html>diff --git a/index.html b/index.htmlindex 5abe7672..e83e2d5d 100644--- a/index.html+++ b/index.html@@ -792,6 +792,17 @@ button,input{font:inherit;color:inherit}.pv-carousel3d .rg i::before{border:1px solid rgba(255,255,255,.18);background:radial-gradient(circle at 70% 28%,hsl(calc(var(--k) * 60) 90% 88%) 0 10%,transparent 11%),radial-gradient(130% 55% at 25% 108%,hsl(calc(var(--k) * 60) 42% 20%) 0 60%,transparent 61%),linear-gradient(hsl(calc(var(--k) * 60) 62% 62%),hsl(calc(var(--k) * 60 + 30) 55% 40%))}.pv-carousel3d .rg i::after{transform:rotateY(180deg);border:1px solid hsl(calc(var(--k) * 60) 28% 30%);background:hsl(calc(var(--k) * 60) 30% 15%)}@keyframes d-car3d{0%,11.7%{transform:rotateY(0)}16.7%,28.3%{transform:rotateY(-60deg)}33.3%,45%{transform:rotateY(-120deg)}50%,61.7%{transform:rotateY(-180deg)}66.7%,78.3%{transform:rotateY(-240deg)}83.3%,95%{transform:rotateY(-300deg)}100%{transform:rotateY(-360deg)}}+/* the demo's landscape in layers that slide by their depth (--k): the hills hold still, the sun and mountains drift a little+ with the view and the tree and ground slide the other way; each layer reaches past the edges it could uncover */+.pv-depthmap{background:linear-gradient(#1b2452,#4c3a7a 30%,#c96a78 52%,#f4b16c 68%);overflow:hidden;container-type:size}+.pv-depthmap i{position:absolute;animation:d-dmap 5s ease-in-out infinite}+.pv-depthmap .sun{left:63%;top:20%;width:11cqw;aspect-ratio:1;border-radius:50%;background:#fff1cf;box-shadow:0 0 6cqw 2cqw rgba(255,224,170,.4)}+.pv-depthmap .mt{inset:0 -8%;background:#6d5a96;clip-path:polygon(0 55%,7% 47%,14% 52%,24% 38%,33% 49%,42% 43%,50% 50%,60% 40%,70% 49%,79% 42%,88% 50%,95% 46%,100% 52%,100% 100%,0 100%)}+.pv-depthmap .hl{left:-15%;right:-15%;top:60%;bottom:-10%;border-radius:50% 50% 0 0/22% 22% 0 0;background:#3f5f86}+.pv-depthmap .md{left:-20%;right:-10%;top:70%;bottom:-10%;border-radius:60% 40% 0 0/30% 26% 0 0;background:#2f6150}+.pv-depthmap .tr{left:12%;top:24%;width:26cqw;height:62%;background:radial-gradient(circle 4cqw at 42% 26%,#2f6a52 98%,transparent),radial-gradient(circle 7cqw at 50% 30%,#23503f 98%,transparent),radial-gradient(circle 5.4cqw at 29% 42%,#23503f 98%,transparent),radial-gradient(circle 5.4cqw at 71% 42%,#23503f 98%,transparent),linear-gradient(#3b2a22,#3b2a22) 50% 100%/2cqw 62% no-repeat}+.pv-depthmap .gd{left:-10%;right:-10%;top:83%;bottom:-10%;border-radius:50% 50% 0 0/22% 22% 0 0;background:radial-gradient(ellipse 9cqw 4.6cqw at 72% 48%,#4a4658 98%,transparent),linear-gradient(#1f3e2c,#0d1f15)}+@keyframes d-dmap{0%,100%{transform:translate(calc(var(--k) * 7cqw),calc(var(--k) * -1.2cqw))}50%{transform:translate(calc(var(--k) * -7cqw),calc(var(--k) * 1.2cqw))}}/* ── bespoke: 07 Ambient & Background ── */.pv-grain2{background:radial-gradient(circle at 50% 40%,#1a1710,#08080a);overflow:hidden}@@ -1020,7 +1031,7 @@ button,input{font:inherit;color:inherit}<section class="wrap home-hero" aria-labelledby="hero-title"><span class="float fl1" aria-hidden="true"></span><span class="float fl2" aria-hidden="true"></span><span class="float fl3" aria-hidden="true"></span><span class="float fl4" aria-hidden="true"></span><span class="float fl5" aria-hidden="true"></span><span class="float fl6" aria-hidden="true"></span>- <p class="pill"><span class="pill-dot" aria-hidden="true"></span>130 free animations · no coding needed</p>+ <p class="pill"><span class="pill-dot" aria-hidden="true"></span>131 free animations · no coding needed</p><h1 class="h1" id="hero-title">What do you want to animate?</h1><p class="sub">Pick a place, or describe it in your own words. Every animation plays live, and each one comes with a ready-made prompt for your AI assistant.</p><form class="search" id="search-form" role="search" action="./" method="get">@@ -1077,8 +1088,8 @@ button,input{font:inherit;color:inherit}<p class="empty-s">Try a simpler word, or pick one of these:</p><p class="pop"><button type="button" data-q="fade in">fade in</button><button type="button" data-q="typing text">typing text</button><button type="button" data-q="loading spinner">loading spinner</button><button type="button" data-q="parallax">parallax</button><button type="button" data-q="confetti">confetti</button></p></div>- <div class="more" id="more"><button type="button" class="bigbtn" id="more-btn"><span id="more-label">Browse all 130 animations</span><svg class="i" viewBox="0 0 24 24" aria-hidden="true"><path d="M12 5v14M6 13l6 6 6-6"/></svg></button></div>- <noscript><p class="noscript">This page shows its animations with JavaScript. All 130 are still easy to reach: see the <a href="https://github.com/matinmonshizadeh/animation-handbook#categories">category list on GitHub</a> or the <a href="sitemap.xml">full sitemap</a>. Each demo is a page of its own under <code>/animations/<category>/<name>/</code>.</p></noscript>+ <div class="more" id="more"><button type="button" class="bigbtn" id="more-btn"><span id="more-label">Browse all 131 animations</span><svg class="i" viewBox="0 0 24 24" aria-hidden="true"><path d="M12 5v14M6 13l6 6 6-6"/></svg></button></div>+ <noscript><p class="noscript">This page shows its animations with JavaScript. All 131 are still easy to reach: see the <a href="https://github.com/matinmonshizadeh/animation-handbook#categories">category list on GitHub</a> or the <a href="sitemap.xml">full sitemap</a>. Each demo is a page of its own under <code>/animations/<category>/<name>/</code>.</p></noscript></section><section class="how" id="how" aria-labelledby="how-title">@@ -1096,7 +1107,7 @@ button,input{font:inherit;color:inherit}<footer class="wrap foot"><a class="brand" href="./"><svg class="mark" viewBox="0 0 32 32" aria-hidden="true"><circle class="ring" cx="11.16" cy="20.84" r="6.1"/><circle class="ring" cx="15.12" cy="16.88" r="6.1"/><circle class="ring" cx="18.51" cy="13.49" r="6.1"/><circle class="ball" cx="21.2" cy="10.8" r="6.6"/></svg><span>Animation Handbook</span></a>- <p class="foot-t">130 web animations with live demos and copyable prompts.</p>+ <p class="foot-t">131 web animations with live demos and copyable prompts.</p><nav class="nav" aria-label="Footer"><a class="lnk" href="https://github.com/matinmonshizadeh/animation-handbook" target="_blank" rel="noopener noreferrer">GitHub</a><a class="lnk" href="#top">Back to top</a></nav></footer><div class="toast" id="toast" role="status" aria-live="polite"><span class="ok" aria-hidden="true"><svg class="i" viewBox="0 0 24 24"><path d="M5 12.5l4.5 4.5L19 7.5"/></svg></span><span class="toast-t"></span></div>@@ -1265,6 +1276,7 @@ const CATS=[['morphing-blob','Morphing Blob','Blobs melt together, and one drop chases your pointer. Best for hero sections.'],['flip-card-3d','3D Flip Card','A card turns over in 3D to show its back. Best for profile and product cards.'],['carousel-3d','3D Carousel','Cards stand in a ring that spins in 3D as you drag it. Best for image galleries.'],+ ['depth-map-photo','Depth-Map Photo','A flat picture turns 3D as you point: near parts shift more than far ones. Best for hero images.'],]},{@@ -1298,7 +1310,7 @@ const PV={'svg-line-draw':'linedraw','scrollspy-nav':'spy','scroll-background-color':'bgblend','hamburger-menu-toggle':'hamb','theme-toggle-morph':'thememorph','copy-to-clipboard':'copyfx','star-rating':'stars','toast-notification':'toast','segmented-control':'segct','pull-to-refresh':'pullref',- 'flip-card-3d':'flip3d','carousel-3d':'carousel3d','matrix-rain':'matrix','plasma':'plasmapv',+ 'flip-card-3d':'flip3d','carousel-3d':'carousel3d','depth-map-photo':'depthmap','matrix-rain':'matrix','plasma':'plasmapv','parallax-depth-of-field':'dof','parallax-scrolling':'plx','reverse-scrolling-columns':'revcol','cover-card-to-fixed-header':'cover','fly-in-fly-out-contact-list':'flylist','stacking-cards':'stack','scroll-trigger':'trigger','scrub-animation':'scrub','pin-animation':'pin','snap-scrolling':'snap',@@ -1454,6 +1466,7 @@ const PLACES={'morphing-blob':['bg'],'flip-card-3d':['imgcard'],'carousel-3d':['imgcard'],+ 'depth-map-photo':['imgcard','intro'],// 07'animated-gradient-background':['bg'],'mesh-gradient':['bg'],@@ -1485,6 +1498,7 @@ function pvMarkup(k){case 'sig5': return '<span class="s5 anim"></span><span class="s5 anim"></span><span class="s5 anim"></span>';case 'sig6': return '<div class="cube anim"><span class="face f1"></span><span class="face f2"></span><span class="face f3"></span><span class="face f4"></span><span class="face f5"></span><span class="face f6"></span></div>';case 'carousel3d': return '<div class="sc"><div class="tl"><div class="rg anim">'+[0,1,2,3,4,5].map(k=>'<i style="--k:'+k+'"></i>').join('')+'</div></div></div>';+ case 'depthmap': return [['sun',-.4],['mt',-.2],['hl',.05],['md',.25],['tr',.45],['gd',.55]].map(([c,k])=>'<i class="'+c+' anim" style="--k:'+k+'"></i>').join('');case 'sig7': return '<span class="s7 anim"></span>';case 'aurora': return '<span class="band b1 anim"></span><span class="band b2 anim"></span><span class="band b3 anim"></span>';case 'mesh': return '<span class="m m1 anim"></span><span class="m m2 anim"></span><span class="m m3 anim"></span>';diff --git a/sitemap.xml b/sitemap.xmlindex 3fff7d41..60c03bda 100644--- a/sitemap.xml+++ b/sitemap.xml@@ -114,6 +114,7 @@<url><loc>https://matinmonshizadeh.github.io/animation-handbook/animations/06-3d-advanced/morphing-blob/</loc><lastmod>2026-07-14</lastmod><changefreq>monthly</changefreq><priority>0.7</priority></url><url><loc>https://matinmonshizadeh.github.io/animation-handbook/animations/06-3d-advanced/flip-card-3d/</loc><lastmod>2026-07-14</lastmod><changefreq>monthly</changefreq><priority>0.7</priority></url><url><loc>https://matinmonshizadeh.github.io/animation-handbook/animations/06-3d-advanced/carousel-3d/</loc><lastmod>2026-10-01</lastmod><changefreq>monthly</changefreq><priority>0.7</priority></url>+ <url><loc>https://matinmonshizadeh.github.io/animation-handbook/animations/06-3d-advanced/depth-map-photo/</loc><lastmod>2026-10-01</lastmod><changefreq>monthly</changefreq><priority>0.7</priority></url><url><loc>https://matinmonshizadeh.github.io/animation-handbook/animations/07-ambient-background/animated-gradient-background/</loc><lastmod>2026-07-14</lastmod><changefreq>monthly</changefreq><priority>0.7</priority></url><url><loc>https://matinmonshizadeh.github.io/animation-handbook/animations/07-ambient-background/mesh-gradient/</loc><lastmod>2026-07-14</lastmod><changefreq>monthly</changefreq><priority>0.7</priority></url><url><loc>https://matinmonshizadeh.github.io/animation-handbook/animations/07-ambient-background/aurora/</loc><lastmod>2026-07-14</lastmod><changefreq>monthly</changefreq><priority>0.7</priority></url>