Thanos Snap
A single line and paragraph become tiny pieces of dust, then drift away from left to right.
Copy this whole file into a React or Next.js project and render <ThanosSnapDemo />. It uses React and browser APIs only. The live demo above renders this exact file, so the copy button gives you the same component you just tried.
"use client";
import { useEffect, useRef, useState } from "react";
type DustOptions = {
duration: number;
layers?: number;
delay?: number;
restore?: boolean;
};
// This function also powers the full-page search results example.
export function animateDust(
content: HTMLElement,
{ duration, layers = 24, delay = 0, restore = false }: DustOptions,
) {
const parent = content.parentElement;
const width = Math.ceil(content.offsetWidth);
const height = Math.ceil(content.offsetHeight);
if (!parent || !width || !height) {
return { animations: [] as Animation[], copies: [] as HTMLElement[] };
}
const scale = Math.min(window.devicePixelRatio || 1, 2);
const pixelWidth = Math.ceil(width * scale);
const pixelHeight = Math.ceil(height * scale);
const masks = Array.from({ length: layers }, () => {
const canvas = document.createElement("canvas");
canvas.width = pixelWidth;
canvas.height = pixelHeight;
return canvas;
});
const contexts = masks.map((mask) => mask.getContext("2d"));
contexts.forEach((context) => { if (context) context.fillStyle = "white"; });
for (let y = 0; y < pixelHeight; y++) {
for (let x = 0; x < pixelWidth; x++) {
const index = Math.max(0, Math.min(layers - 1, Math.floor(
layers * (0.1 + 0.8 * x / pixelWidth) + (Math.random() - 0.5) * layers / 6,
)));
contexts[index]?.fillRect(x, y, 1, 1);
}
}
const copies: HTMLElement[] = [];
const animations: Animation[] = [];
masks.forEach((mask, index) => {
const copy = content.cloneNode(true) as HTMLElement;
const url = `url(${mask.toDataURL()})`;
copy.dataset.dustLayer = "";
copy.removeAttribute("data-snap-target");
copy.setAttribute("aria-hidden", "true");
copy.querySelectorAll("a, button, input").forEach((item) => item.setAttribute("tabindex", "-1"));
Object.assign(copy.style, {
position: "absolute",
inset: "0",
width: `${width}px`,
height: `${height}px`,
visibility: "visible",
pointerEvents: "none",
maskImage: url,
maskSize: `${width}px ${height}px`,
});
copy.style.setProperty("-webkit-mask-image", url);
copy.style.setProperty("-webkit-mask-size", `${width}px ${height}px`);
parent.appendChild(copy);
const angle = (Math.random() - 0.5) * Math.PI * 2;
const distance = 50 + Math.random() * 40;
const scattered = {
opacity: 0,
transform: `translate(${Math.cos(angle) * distance}px, ${Math.sin(angle) * distance}px) rotate(${(Math.random() - 0.5) * 15}deg)`,
};
const whole = { opacity: 1, transform: "translate(0, 0) rotate(0deg)" };
animations.push(copy.animate(restore ? [scattered, whole] : [whole, scattered], {
duration: 1_100,
delay: delay + index / layers * duration,
easing: "ease-out",
fill: "both",
}));
copies.push(copy);
});
return { animations, copies };
}
export function ThanosSnapDemo() {
const contentRef = useRef<HTMLDivElement>(null);
const animationsRef = useRef<Animation[]>([]);
const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const [status, setStatus] = useState<"ready" | "dissolving" | "gone">("ready");
useEffect(() => {
const content = contentRef.current;
return () => {
if (timeoutRef.current) clearTimeout(timeoutRef.current);
animationsRef.current.forEach((animation) => animation.cancel());
content?.parentElement?.querySelectorAll("[data-dust-layer]").forEach((copy) => copy.remove());
};
}, []);
const reset = () => {
if (timeoutRef.current) clearTimeout(timeoutRef.current);
animationsRef.current.forEach((animation) => animation.cancel());
animationsRef.current = [];
contentRef.current?.parentElement?.querySelectorAll("[data-dust-layer]").forEach((copy) => copy.remove());
if (contentRef.current) contentRef.current.style.visibility = "visible";
setStatus("ready");
};
const snap = () => {
const content = contentRef.current;
if (!content || status !== "ready") return;
if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) {
content.style.visibility = "hidden";
setStatus("gone");
return;
}
const { animations, copies } = animateDust(content, { duration: 1_200 });
if (!animations.length) return;
animationsRef.current = animations;
content.style.visibility = "hidden";
setStatus("dissolving");
timeoutRef.current = setTimeout(() => {
copies.forEach((copy) => copy.remove());
animationsRef.current = [];
setStatus("gone");
}, 1_200 + 1_100);
};
const gone = status === "gone";
// No box of its own: the text inherits the page's colour, so it works on light and dark pages.
return (
<div style={{ width: "100%", maxWidth: 640, padding: 32, fontFamily: "Arial, sans-serif", color: "inherit" }}>
<div style={{ position: "relative" }}>
<div ref={contentRef}>
<h3 style={{ margin: 0, fontSize: "clamp(2.25rem, 7vw, 4rem)", letterSpacing: "-0.04em", whiteSpace: "nowrap" }}>Thanos Snap</h3>
<p style={{ margin: "20px 0 0", maxWidth: 560, fontSize: 17, lineHeight: 1.7, opacity: 0.7 }}>A single line and paragraph become tiny pieces of dust, then drift away from left to right.</p>
</div>
</div>
<div style={{ display: "flex", alignItems: "center", gap: 14, marginTop: 32 }}>
<button
type="button"
onClick={gone ? reset : snap}
disabled={status === "dissolving"}
style={{ border: "1px solid currentColor", borderRadius: 999, padding: "9px 18px", background: "transparent", color: "inherit", font: "inherit", fontSize: 14, cursor: "pointer", opacity: status === "dissolving" ? 0.4 : 1 }}
>
{gone ? "Bring it back" : "Snap"}
</button>
<span role="status" style={{ fontSize: 12, opacity: 0.55 }}>{gone ? "Gone." : status === "dissolving" ? "Dissolving…" : ""}</span>
</div>
</div>
);
}How it works
Step 1. Start with ordinary HTML
The demo begins as one heading and one paragraph inside a wrapper with position: relative. Nothing about the text is drawn on canvas. It remains normal HTML, so the browser handles fonts, wrapping, and accessibility.
<div style={{ position: "relative" }}>
<div ref={contentRef}>
<h3>Thanos Snap</h3>
<p>A single line and paragraph become tiny pieces of dust.</p>
</div>
</div>What you see: the complete, readable text. The relative wrapper gives later dust copies a fixed place to sit.
Step 2. Learn what the canvas does here
A canvas is a grid of pixels. We use small, invisible canvases as masks, not as a replacement for the HTML. In each mask, a white pixel means “show this part of the HTML copy”; a transparent pixel means “hide it.”
First measure the HTML block. offsetWidth and offsetHeight are its size in CSS pixels. devicePixelRatio tells us how many physical screen pixels fit into one CSS pixel. We cap it at two so the masks stay small enough to create quickly.
const width = Math.ceil(content.offsetWidth)
const height = Math.ceil(content.offsetHeight)
const scale = Math.min(window.devicePixelRatio || 1, 2)
const pixelWidth = Math.ceil(width * scale)
const pixelHeight = Math.ceil(height * scale)What you see: still the original text. We only know the size of the invisible pixel grid now.
Step 3. Make several empty masks
Create 24 canvases, all the same size as that grid. Each one will hold a different portion of the heading and paragraph. getContext("2d") is the browser API that lets us paint pixels into a canvas. White paint becomes the visible part of a mask.
const layers = 24
const masks = Array.from({ length: layers }, () => {
const canvas = document.createElement("canvas")
canvas.width = pixelWidth
canvas.height = pixelHeight
return canvas
})
const contexts = masks.map((mask) => mask.getContext("2d"))
contexts.forEach((context) => { if (context) context.fillStyle = "white" })What you see: no change yet. The canvases are offscreen, and every mask starts transparent.
Step 4. Assign every pixel to one mask
Walk across the grid one pixel at a time. The pixel's horizontal position chooses its mask: pixels on the left usually get a low mask number, and pixels on the right get a high one. Randomness makes the boundary irregular. fillRect(x, y, 1, 1) paints exactly one white pixel in the chosen mask.
for (let y = 0; y < pixelHeight; y++) {
for (let x = 0; x < pixelWidth; x++) {
const layer = Math.max(0, Math.min(layers - 1, Math.floor(
layers * (0.1 + 0.8 * x / pixelWidth) +
(Math.random() - 0.5) * layers / 6
)))
contexts[layer]?.fillRect(x, y, 1, 1)
}
}The 0.1 + 0.8 * x / pixelWidth part moves the typical mask number from about 10% of the stack on the left to 90% on the right. Painting one physical pixel at a time is why the dust looks fine rather than blocky.
What you see: still the original text. The masks now contain all the pieces needed to reconstruct it.
Step 5. Put masked HTML copies over the original
Clone the HTML once for each mask. Convert each mask to a data URL with toDataURL() and give it to the copy's CSS mask-image. Position every copy at the same top-left corner. Once all copies exist, hide the original with visibility: hidden; that keeps its space in the layout.
const copy = content.cloneNode(true) as HTMLElement
const url = `url(${mask.toDataURL()})`
Object.assign(copy.style, {
position: "absolute",
inset: "0",
width: `${width}px`,
height: `${height}px`,
maskImage: url,
maskSize: `${width}px ${height}px`,
pointerEvents: "none",
})
content.parentElement?.appendChild(copy)Mark copies aria-hidden and remove their keyboard focus, because the original is the real content. The complete component also sets the prefixed mask properties for browser compatibility.
What you see: the text still looks whole. Each copy shows only a few pixels, but all copies together cover it.
Step 6. Make the copies drift and fade
The Web Animations API moves one copy from its starting position to a scattered position while fading its opacity from one to zero. delay is based on the mask number, so lower-numbered masks disappear first. Since the masks were assigned from left to right, the dissolve sweeps across the text.
copy.animate([
{ opacity: 1, transform: "translate(0, 0)" },
{ opacity: 0, transform: "translate(70px, -20px) rotate(7deg)" },
], {
duration: 1100,
delay: index / layers * 1200,
easing: "ease-out",
fill: "both",
})The live component gives each copy a different angle and distance so the dust does not travel as a rigid sheet.
What you see: the left side starts breaking apart, then the effect moves right until the text is gone.
Step 7. Finish cleanly and make Reset work
After the last animation, remove the temporary copies. Keep the original hidden so the snapped state remains. Reset cancels any animation still running, removes leftover copies, and makes the original visible again. The same cleanup runs when the component unmounts.
animations.forEach((animation) => animation.cancel())
copies.forEach((copy) => copy.remove())
content.style.visibility = "visible"If someone prefers reduced motion, the component skips the drifting layers and changes visibility immediately.
What you see: Reset restores the exact original HTML without rebuilding its text.
Step 8. Scale it to the full page
The search page selects alternating result blocks and calls the same animateDust function for each one. Its gauntlet sprite has 48 frames, played at 50 milliseconds per frame. The dust starts when the hand animation finishes. A second click calls the same function with restore: true, which reverses each copy's motion. The gauntlet sprites and sounds are served locally in the full page demo.
What you see: half the search results disappear while the others remain in place, then return on the next click.