Scroll-Linked Particle Morph Animation: Design and Implementation Considerations
This article breaks down a scroll-driven particle morph effect into shape sampling, scroll-state mapping, per-particle motion, rendering performance, and accessibility fallbacks. It explains how to convert arbitrary shapes into point sets, map scroll progress to stage and local progress, combine swirl, interpolation, and mid-stage dispersion in a single particle model, and keep Canvas 2D rendering smooth with requestAnimationFrame, visibility checks, DPR limits, and reduced particle counts. Readers get a layered implementation approach and practical constraints for building similar effects.
1. Breaking Down the Effect: Translating Visual Language into Technical Requirements
This type of animation usually combines three layers of meaning. The first is a shape sequence: the hero section presents several graphics in turn, such as a numeric form, a cursor form, and a logo form, with smooth transitions between them. The second is motion semantics: the particles disperse midway through the transition and regroup when they reach the target. Dispersion represents exploration and divergence; regrouping represents convergence and certainty. The third is spatial perception: particles form a vortex-like orbit near the center, giving the image a sense of flow rather than simple position interpolation.
After translating the visual language into technical requirements, four clear questions emerge:
- How can an arbitrary shape be converted into a set of driveable coordinate points?
- How can page scroll position be mapped to animation stages and progress?
- How can a single particle’s motion function satisfy rotation, dispersion, and convergence at the same time?
- How can the effect stay smooth across devices and provide an alternative for users who prefer reduced motion?
The following sections address these four questions one by one.
2. Overall Architecture
A recommended approach is to split the system into three layers, each responsible for one concern.
- Data layer: Converts each shape into a target point set. This happens during initialization and is not recalculated afterward.
- State layer: Reads scroll position, determines the current shape stage, and calculates local progress within that stage. This layer does not touch drawing logic.
- Render layer: Updates particle coordinates and draws to the canvas each frame based on the progress provided by the state layer.
The benefit of this separation is that adding or modifying shapes only requires changes to the data layer input; adjusting scroll pacing only requires changes to the state-layer mapping; replacing the drawing method only requires swapping the render layer. The three layers communicate through plain data, which makes them easier to test independently.
For drawing technology, Canvas 2D is usually sufficient for 2D scenarios. With a few thousand particles, updating coordinates per frame and drawing in batches generally performs reliably. If particle counts reach tens of thousands, or if complex lighting and blending effects are required, WebGL can be considered. The examples in this article use Canvas 2D, and the principles can be transferred directly to WebGL.
3. Shape Sampling: Converting Shapes into Point Sets
Each shape needs a set of target coordinates. The most direct approach is to draw the shape on an offscreen canvas, read the pixel alpha values, and record grid points in opaque areas as target points.
function sampleShape(drawFn, width, height, gap = 4) {const off = document.createElement('canvas');off.width = width;off.height = height;const ctx = off.getContext('2d');drawFn(ctx, width, height); // The caller draws text, paths, or shapesconst { data } = ctx.getImageData(0, 0, width, height);const points = [];for (let y = 0; y < height; y += gap) {for (let x = 0; x < width; x += gap) {const alpha = data[(y * width + x) * 4 + 3];if (alpha > 128) {points.push({ x, y });}}}return points;}
There are several points to note in this code.
First, the sampling interval gap determines point density. A smaller interval produces a clearer shape, but particle count and computational cost increase accordingly. In practice, you can first use a larger interval to establish the shape outline, then decide the final density based on device performance.
Second, different shapes often have different point counts. The particle count is determined by the shape with the most points. Shapes with fewer points need padding, or extra particles can be randomly distributed at the canvas edges and kept transparent. When padding points, prefer positions close to existing points to avoid abrupt jumps.
Third, if shapes come from images, cross-origin restrictions matter. Browsers reject canvas pixel reads for cross-origin images, so images should come from the same origin or be hosted by the project itself.
Fourth, coordinates need to be normalized to the current viewport. Sampling results can be stored as ratios relative to canvas width and height, then multiplied by the new dimensions when the window size changes, avoiding resampling.
4. Scroll-Driven State Mapping
The core of a scroll animation is converting page scroll position into animation progress. There are two key concepts here: global progress and stage-local progress.
Global progress describes how far the user has scrolled through the entire container, ranging from 0 to 1. Stage-local progress describes which shape stage is current and how much of that stage has completed.
function getScrollProgress(container) {const total = container.offsetHeight - window.innerHeight;if (total <= 0) return 0;const scrolled = window.scrollY - container.offsetTop;return Math.min(Math.max(scrolled / total, 0), 1);}function resolveStage(progress, stageCount) {const scaled = progress * stageCount;const index = Math.min(Math.floor(scaled), stageCount - 1);const local = scaled - index;return { index, local };}
With three shapes as an example, stageCount is 2 because there are two transitions between the three shapes. When index is 0, the animation transitions from the first shape to the second; when index is 1, it transitions from the second shape to the third. local is the stage-local progress and determines where particles are between the two shapes.
One easily overlooked issue with this mapping is that scroll position is discrete, and touch devices may produce inertial scrolling. Mapping scroll position directly to the visual can make the visual jitter with scrolling. A common solution is to apply damping to the progress, moving the displayed progress toward the target progress by a certain ratio each frame:
let displayProgress = 0;function smoothProgress(target, factor = 0.1) {displayProgress += (target - displayProgress) * factor;return displayProgress;}
The smaller factor is, the smoother the visual becomes, but the more noticeable the delay. A typical range is 0.05 to 0.15, and the exact value should be tuned against the actual scrolling feel.
5. Per-Particle Motion Model
Particle motion is the most recognizable part of this type of effect. It needs to satisfy three requirements at the same time: move smoothly from the start point to the end point, form a vortex midway, and create a sense of dispersion in the middle section.
Below is a usable motion function example:
function easeInOutCubic(t) {return t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2;}function updateParticle(p, center, local) {const k = easeInOutCubic(local); // Easing factor for overall displacementconst spread = Math.sin(Math.PI * local); // Maximum at the middle of the stage, zero at both ends// 1. Rotate around the center; rotation decays with progress to form a swirlconst angle = p.swirl * (1 - k);const dx = p.fromX - center.x;const dy = p.fromY - center.y;const rx = dx * Math.cos(angle) - dy * Math.sin(angle) + center.x;const ry = dx * Math.sin(angle) + dy * Math.cos(angle) + center.y;// 2. Interpolate toward the target pointconst baseX = rx + (p.toX - rx) * k;const baseY = ry + (p.toY - ry) * k;// 3. Add random offset in the middle section to express dispersionp.x = baseX + p.jitterX * spread;p.y = baseY + p.jitterY * spread;}
This model divides motion into three independent terms, each with a clear meaning.
The rotation term uses (1 - k) as a decay coefficient. At the beginning of the stage, particles rotate around the center with the largest amplitude, and as progress advances they gradually return to a straight path. The rotation angle p.swirl is randomly assigned to each particle during initialization; a recommended range is from a fraction of a radian to half a radian. Too large a value makes particle trajectories look chaotic.
The interpolation term sends particles to the target position. Using an easing function rather than linear interpolation makes motion gentle at the start and end, avoiding a mechanical feel.
The dispersion term uses sin(π·local). At the start and end of the stage, this value is 0, and particle positions are entirely determined by the first two terms. At the midpoint of the stage, this value reaches its maximum, pushing particles apart with random offsets. jitterX and jitterY are generated randomly during initialization. Their amplitude is recommended to be proportional to viewport size, such as a percentage of the viewport’s shorter side, to avoid large differences across screens.
It is important to note that the parameters above are example values and have no corresponding performance or effect benchmark. In a real project, they should be tuned repeatedly on target devices to observe whether the swirl is too scattered, whether dispersion is too intense, and whether convergence is clean enough.
6. Render Loop and Performance Control
The render loop should follow several basic principles.
Use requestAnimationFrame to drive drawing. Do not draw directly inside scroll event callbacks, because scroll event frequency does not match screen refresh rate and can cause duplicate drawing or dropped frames. The correct approach is to record target progress only in the scroll event and perform calculation and drawing in the next frame.
Redraw only when necessary. If progress has not changed and particle positions have stabilized, the current frame can be skipped. The threshold can be a very small value; for example, a progress difference between frames below a tiny value can be treated as static.
Control offscreen computation. When the animation container scrolls out of the viewport, rendering should pause. IntersectionObserver can be used to monitor container visibility, stop the loop when it is not visible, and resume when it re-enters the viewport.
Adapt to device pixel ratio. On high-resolution screens, the canvas needs to be scaled by device pixel ratio; otherwise edges appear blurry. However, scaling multiplies pixel count, so the maximum pixel ratio should also be limited, for example to 2, to balance clarity and performance.
Reduce per-frame memory allocation. Frequently creating objects in the loop increases garbage collection pressure. Particle data can be stored in typed arrays in advance, and array elements can be modified directly each frame instead of creating new objects.
Adjust particle count by device capability. Mobile devices usually have weaker computation and drawing capability than desktop devices. Window width or device information can be used for a rough estimate, and sampling interval can be reduced accordingly to lower the total particle count.
Below is a skeleton example of the render loop:
let rafId = null;let visible = true;function render(time) {if (!visible) {rafId = null;return;}const progress = smoothProgress(getScrollProgress(container));const { index, local } = resolveStage(progress, 2);// Update particles based on index and local, then drawdrawParticles(index, local);rafId = requestAnimationFrame(render);}const observer = new IntersectionObserver(([entry]) => {visible = entry.isIntersecting;if (visible && rafId === null) {rafId = requestAnimationFrame(render);}});observer.observe(container);
Scroll listening should use passive mode to tell the browser that the callback will not prevent default scrolling behavior, reducing scroll jank:
window.addEventListener('scroll', () => {}, { passive: true });
When the component unmounts, remove the scroll listener, disconnect the IntersectionObserver, and cancel pending animation frame requests; otherwise memory leaks and unnecessary computation can occur.
7. Accessibility and Fallbacks
Animation should not come at the cost of usability. Pages like this should follow the principles below.
Respect the system setting for reduced motion. Use the prefers-reduced-motion media query to detect user preference. When this option is enabled, render the final shape directly without playing transition animations, or keep only a very subtle fade-in effect.
@media (prefers-reduced-motion: reduce) {.hero-canvas {transition: none;}}
Ensure text content can be read. Text drawn in the canvas is not visible to screen readers. Core page information should also exist as regular text in the DOM.
