How to Build Scroll-Driven WebGL Particle Effects with Performance Optimization

    \$$This article explains how to implement scroll-driven particle convergence and dispersion effects on the web, covering image sampling for target coordinates, scattered position generation, GLSL shader animation, scroll progress mapping, mouse interaction, and performance optimization. You will learn the rendering pipeline, memory and rendering optimization strategies, graceful degradation for unsupported environments, and common troubleshooting solutions for flicker, scroll sync, and mobile performance.

    1. Introduction: The Technical Value of Interactive Visual Effects

    In modern web applications, scroll-driven dynamic visual effects have become an important means of improving user experience. A typical example is a particle system that goes through a “scatter -> converge -> scatter again” transformation as the user scrolls the page. When converging, the particles form a specific shape (such as numbers or a logo); when scattering, they become starfield-like points. In addition, mouse movement can produce local attraction or repulsion effects to further enhance interactivity.

    Such effects may look impressive, but their technical essence is not mysterious. This article systematically explains how to implement a complete and reproducible particle convergence and dispersion effect from four dimensions: data preparation, rendering pipeline, interactive animation mapping, and performance optimization.


    2. Overall Architecture Design

    2.1 Technology Selection

    Layer Recommended Solution Description
    Rendering engine WebGL / Three.js GPU acceleration, supports real-time rendering of tens of thousands of particles
    Shader language GLSL ES Custom vertex/fragment shaders control particle behavior
    Coordinate system Normalized Device Coordinates (NDC) Unified coordinate system simplifies shape switching
    Interaction detection Mouse events + ray projection Maps 2D mouse coordinates to 3D particle space

    2.2 Data Flow

    1. Static image / Logo
    2. ↓ Pre-sampling
    3. Target coordinate set (Target Positions)
    4. ↓ Random initialization
    5. Particle starting coordinates (Source Positions)
    6. ↓ Scroll progress driven
    7. Current position = mix(start position, target position, progress)
    8. ↓ Shader processing
    9. GPU rendering output

    3. Core Implementation Steps

    3.1 Step 1: Extracting Target Coordinates from an Image

    The target shape (such as the number “6” or a logo outline) needs to be converted to particle target positions through image sampling:

    1. // Pseudocode: sample image into particle coordinates
    2. function sampleImageToPoints(imagePath, sampleCount) {
    3. const canvas = document.createElement('canvas');
    4. const ctx = canvas.getContext('2d');
    5. // Load the image and draw it onto the canvas
    6. // Scan pixel by pixel, take a valid point every N pixels
    7. // Filter out transparent and white background pixels
    8. const points = [];
    9. for (let y = 0; y < canvas.height; y += stepY) {
    10. for (let x = 0; x < canvas.width; x += stepX) {
    11. const pixel = ctx.getImageData(x, y, 1, 1).data;
    12. if (pixel[3] > 128) { // alpha > 0.5
    13. points.push({
    14. x: (x / canvas.width) * 2 - 1, // Map to [-1, 1]
    15. y: -((y / canvas.height) * 2 - 1) // Y-axis flip
    16. });
    17. }
    18. }
    19. }
    20. return points;
    21. }

    Key points:

    • The number of sample points determines the total number of particles, generally between 2,000 and 50,000
    • Coordinates need to be mapped to the normalized range [-1, 1] for subsequent blending operations
    • Background color must be filtered out, retaining only pixels of the target shape

    3.2 Step 2: Initializing Particle Starting Positions

    Particles in the scattered state need random distribution, but the distribution must be uniform and aesthetically pleasing:

    1. // Pseudocode: generate random positions for the scattered state
    2. function generateScatteredPositions(count) {
    3. const positions = [];
    4. for (let i = 0; i < count; i++) {
    5. // Method 1: uniform spherical distribution
    6. const theta = Math.random() * Math.PI * 2;
    7. const phi = Math.acos(2 * Math.random() - 1);
    8. const radius = 1 + Math.random() * 2; // radius range [1, 3]
    9. positions.push({
    10. x: radius * Math.sin(phi) * Math.cos(theta),
    11. y: radius * Math.sin(phi) * Math.sin(theta),
    12. z: radius * Math.cos(phi)
    13. });
    14. }
    15. return positions;
    16. }

    Distribution strategy selection:

    • Uniform spherical distribution: creates a “nebula” visual feel, suitable for starfield themes
    • Disk distribution: more like a top-down view of a star cluster, suitable for flat scenarios
    • Spiral distribution: has rotational dynamics, suitable for tech-style pages

    3.3 Step 3: Implementing Convergence and Dispersion Animation in Shaders

    The core principle is to use the scroll progress (progress) in the vertex shader to control the interpolation of particles from the scattered position to the target position:

    1. // Vertex shader core logic
    2. attribute vec3 a_scatteredPos; // scattered position
    3. attribute vec3 a_targetPos; // target position (image-sampled coordinates)
    4. uniform float u_progress; // scroll progress [0.0, 1.0]
    5. void main() {
    6. // Smooth interpolation: use smoothstep for a more natural transition
    7. float eased = smoothstep(0.0, 1.0, u_progress);
    8. // Position blending
    9. vec3 pos = mix(a_scatteredPos, a_targetPos, eased);
    10. // Add a subtle rotation effect to avoid being too mechanical
    11. float angle = eased * 3.14159 * 0.5;
    12. mat2 rotation = mat2(
    13. cos(angle), -sin(angle),
    14. sin(angle), cos(angle)
    15. );
    16. pos.xy = rotation * pos.xy;
    17. gl_Position = projectionMatrix * modelViewMatrix * vec4(pos, 1.0);
    18. gl_PointSize = mix(8.0, 3.0, eased); // particles shrink when converging
    19. }

    Key shader techniques:

    1. Replace linear interpolation with smoothstep to make the transition more natural
    2. Appropriately reduce particle size when converging to avoid the target shape being too heavy
    3. Add a rotation matrix to increase dynamism

    3.4 Step 4: Scroll Progress Mapping

    Map the page scroll position to the animation progress:

    1. // Scroll progress calculation
    2. function calculateScrollProgress() {
    3. const scrollTop = window.scrollY;
    4. const sectionHeight = effectSection.offsetHeight;
    5. const windowHeight = window.innerHeight;
    6. // Total scroll distance from when the element enters the viewport to when it fully leaves
    7. const totalScroll = sectionHeight + windowHeight;
    8. // Proportion already scrolled
    9. const progress = scrollTop / totalScroll;
    10. return Math.min(Math.max(progress, 0), 1);
    11. }
    12. // Update per frame
    13. function animate() {
    14. const progress = calculateScrollProgress();
    15. material.uniforms.u_progress.value = progress;
    16. renderer.render(scene, camera);
    17. requestAnimationFrame(animate);
    18. }

    Advanced handling:

    • Add a “damping” effect so the animation follows scrolling but is not fully synchronized: currentProgress += (targetProgress - currentProgress) * 0.08
    • Set a “trigger interval” so the effect is only active within a specific scroll range

    3.5 Step 5: Mouse Interaction Effects

    Mouse interaction is typically implemented in the following ways:

    Method 1: Local attraction/repulsion (Shader layer)

    1. uniform vec3 u_mousePos; // mouse position in 3D space
    2. uniform float u_mouseRadius; // influence radius
    3. void main() {
    4. vec3 pos = mix(a_scatteredPos, a_targetPos, u_progress);
    5. // Calculate the distance from the mouse to the particle
    6. float dist = distance(pos.xy, u_mousePos.xy);
    7. // Apply repulsion within the influence radius
    8. if (dist < u_mouseRadius) {
    9. float force = (1.0 - dist / u_mouseRadius) * 0.5;
    10. vec2 direction = normalize(pos.xy - u_mousePos.xy);
    11. pos.xy += direction * force;
    12. }
    13. gl_Position = projectionMatrix * modelViewMatrix * vec4(pos, 1.0);
    14. }

    Method 2: CPU-level particle physics simulation (CPU layer)

    1. // Pseudocode: calculate repulsion on the CPU
    2. function applyMouseForce(particle, mouseX, mouseY) {
    3. const dx = particle.x - mouseX;
    4. const dy = particle.y - mouseY;
    5. const dist = Math.sqrt(dx * dx + dy * dy);
    6. if (dist < mouseRadius) {
    7. const force = (mouseRadius - dist) / mouseRadius * forceStrength;
    8. particle.x += (dx / dist) * force;
    9. particle.y += (dy / dist) * force;
    10. }
    11. }

    Selection recommendations:

    • Particles < 5,000: both approaches are viable
    • Particles > 10,000: the shader approach is recommended to avoid the CPU becoming a bottleneck

    4. Performance Optimization Strategies

    4.1 Rendering Performance

    Optimization Solution Effect
    Batch drawing Use gl.POINTS to draw all particles at once Reduces draw calls
    Pixel ratio control Math.min(window.devicePixelRatio, 2) Avoids excessive rendering on high-DPI screens
    Viewport culling Pause rendering when the element is out of the viewport Saves GPU resources
    Texture atlas Merge particle textures into a single atlas Reduces texture switches

    4.2 Memory Optimization

    1. // Use Float32Array instead of regular arrays
    2. const positions = new Float32Array(count * 3);
    3. const colors = new Float32Array(count * 3);
    4. const sizes = new Float32Array(count);
    5. // Use BufferGeometry + BufferAttribute
    6. const geometry = new THREE.BufferGeometry();
    7. geometry.setAttribute('position', new THREE.BufferAttribute(positions, 3));
    8. geometry.setAttribute('color', new THREE.BufferAttribute(colors, 3));
    9. geometry.setAttribute('size', new THREE.BufferAttribute(sizes, 1));

    4.3 Degradation Strategy

    1. // Check WebGL support
    2. function checkWebGLSupport() {
    3. const canvas = document.createElement('canvas');
    4. const gl = canvas.getContext('webgl') || canvas.getContext('experimental-webgl');
    5. return !!gl;
    6. }
    7. // Fallback solution when WebGL is not supported
    8. if (!checkWebGLSupport()) {
    9. // Use CSS animation or a static image instead
    10. fallbackElement.style.display = 'block';
    11. effectElement.style.display = 'none';
    12. }

    5. Complete Implementation Example

    The following is the core structure of a minimal runnable example:

    1. <!DOCTYPE html>
    2. <html>
    3. <head>
    4. <style>
    5. .particle-container {
    6. position: fixed;
    7. top: 0;
    8. left: 0;
    9. width: 100%;
    10. height: 100%;
    11. pointer-events: none;
    12. }
    13. .scroll-section {
    14. height: 300vh; /* provide enough scroll space */
    15. }
    16. </style>
    17. </head>
    18. <body>
    19. <canvas class="particle-container" id="canvas"></canvas>
    20. <div class="scroll-section"></div>
    21. <script>
    22. // Initialize scene
    23. const scene = new THREE.Scene();
    24. const camera = new THREE.PerspectiveCamera(
    25. 75, window.innerWidth / window.innerHeight, 0.1, 1000
    26. );
    27. camera.position.z = 5;
    28. const renderer = new THREE.WebGLRenderer({ canvas: document.getElementById('canvas') });
    29. renderer.setSize(window.innerWidth, window.innerHeight);
    30. renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
    31. // Particle system initialization, shader compilation, event binding...
    32. // (see the sections above for detailed code)
    33. // Animation loop
    34. function animate() {
    35. requestAnimationFrame(animate);
    36. // Update scroll progress
    37. // Update mouse position
    38. // Render
    39. renderer.render(scene, camera);
    40. }
    41. animate();
    42. </script>
    43. </body>
    44. </html>

    6. Common Issues and Solutions

    6.1 Particle Flickering

    Cause: Z-axis depth conflicts
    Solution: Add a tiny Z-axis offset in the shader: pos.z += 0.001 * float(gl_VertexID % 100);

    6.2 Scroll Out of Sync

    Cause: Scroll event frequency does not match the rendering frame rate
    Solution: Use requestAnimationFrame for synchronized updates; avoid direct rendering operations inside the scroll event

    6.3 Performance Drop on Mobile

    Solution:

    • Reduce the particle count (recommended <= 5,000 on mobile)
    • Simplify shader logic
    • Disable mouse interaction (mobile devices have no mouse)
    • Use will-change: transform to optimize CSS layer composition

    6.4 Incomplete Image Sampling

    Cause: The sampling step is too large or the threshold is set improperly
    Solution: Dynamically adjust the sampling step to ensure the final point count is close to the target value:

    1. let step = 5;
    2. let points = [];
    3. while (points.length < targetCount && step > 1) {
    4. points = sampleImage(imageData, step);
    5. if (points.length > targetCount * 1.5) step++;
    6. if (points.length < targetCount * 0.5) step--;
    7. }

    7. Summary and Outlook

    The core of a scroll-driven particle convergence and dispersion effect is the combination of “target coordinates + random coordinates + interpolation animation”. Through reasonable data preparation, shader programming, and performance optimization, it is possible to achieve smooth, interactive visual effects in modern browsers.

    Technical key points review:

    1. Data layer: obtain target coordinates via image sampling, obtain scattered coordinates via random distribution
    2. Animation layer: interpolation blending based on scroll progress, combined with easing functions
    3. Interaction layer: map mouse coordinates to 3D space, apply force field effects in the shader
    4. Performance layer: GPU batch rendering, viewport culling, mobile adaptation

    In the future, with the adoption of WebGPU and improved browser performance, such effects will support larger-scale particle systems (over 100,000) and more complex interaction logic. Mastering the fundamental methodology described in this article allows you to flexibly apply it to various interactive visual scenarios.