Skip to main content

Grid Distortion

WebGL-based grid distortion effect that warps images based on mouse interaction. Features Three.js shader materials, configurable grid size, and smooth relaxation effects.

HeroReactThree.jsGLSL
CSSTailwind

Manual

Create a file and paste the following code into it.

src/components/grid-distortion.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
'use client';

import React, { useRef, useEffect } from 'react';
import * as THREE from 'three';

interface GridDistortionProps {
    grid?: number;
    mouse?: number;
    strength?: number;
    relaxation?: number;
    imageSrc: string;
    className?: string;
}

// -----------------------------------------------------------------------------
// SHADERS
// -----------------------------------------------------------------------------

const vertexShader = /* glsl */ `
  uniform float time;
  varying vec2 vUv;
  varying vec3 vPosition;

  void main() {
    vUv = uv;
    vPosition = position;
    gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
  }
`;

const fragmentShader = /* glsl */ `
  uniform sampler2D uDataTexture; // The Physics Texture
  uniform sampler2D uTexture;     // The Image
  uniform vec4 resolution;        // Container Aspect Ratio
  uniform vec2 imageResolution;   // Image Aspect Ratio
  
  varying vec2 vUv;

  void main() {
    // 1. Calculate "Object-Fit: Cover" UVs
    // This ensures the image is never stretched, regardless of container size
    vec2 rs = resolution.xy;
    vec2 is = imageResolution;
    vec2 ratio = vec2(
        min((rs.x / rs.y) / (is.x / is.y), 1.0),
        min((rs.y / rs.x) / (is.y / is.x), 1.0)
    );
    vec2 uv = vec2(
        vUv.x * ratio.x + (1.0 - ratio.x) * 0.5,
        vUv.y * ratio.y + (1.0 - ratio.y) * 0.5
    );

    // 2. Sample the physics texture (The "Liquid" Map)
    vec4 offset = texture2D(uDataTexture, vUv);

    // 3. Apply Displacement with RGB Split (Chromatic Aberration)
    // We offset Red, Green, and Blue channels slightly differently based on velocity
    float r = texture2D(uTexture, uv - 0.02 * offset.rg).r;
    float g = texture2D(uTexture, uv - 0.015 * offset.rg).g; // Less displacement
    float b = texture2D(uTexture, uv - 0.01 * offset.rg).b;  // Even less

    gl_FragColor = vec4(r, g, b, 1.0);
  }
`;

// -----------------------------------------------------------------------------
// COMPONENT
// -----------------------------------------------------------------------------

const GridDistortion: React.FC<GridDistortionProps> = ({
    grid = 15,
    mouse = 0.1,
    strength = 0.15,
    relaxation = 0.9,
    imageSrc,
    className = ''
}) => {
    const containerRef = useRef<HTMLDivElement>(null);

    // Three.js Refs
    const sceneRef = useRef<THREE.Scene | null>(null);
    const rendererRef = useRef<THREE.WebGLRenderer | null>(null);
    const cameraRef = useRef<THREE.OrthographicCamera | null>(null);
    const planeRef = useRef<THREE.Mesh | null>(null);
    const materialRef = useRef<THREE.ShaderMaterial | null>(null);

    // State Refs
    const animationIdRef = useRef<number | null>(null);
    const resizeObserverRef = useRef<ResizeObserver | null>(null);

    useEffect(() => {
        if (!containerRef.current) return;
        const container = containerRef.current;

        // --- SETUP ---
        const scene = new THREE.Scene();
        sceneRef.current = scene;

        const renderer = new THREE.WebGLRenderer({
            antialias: false, // Turn off for performance, usually not needed for this effect
            alpha: true,
            powerPreference: 'high-performance',
            stencil: false,
            depth: false
        });
        renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
        renderer.setClearColor(0x000000, 0);
        container.appendChild(renderer.domElement);
        rendererRef.current = renderer;

        const camera = new THREE.OrthographicCamera(0, 0, 0, 0, -1000, 1000);
        camera.position.z = 2;
        cameraRef.current = camera;

        // --- TEXTURES & DATA ---
        const uniforms = {
            time: { value: 0 },
            resolution: { value: new THREE.Vector4() },
            imageResolution: { value: new THREE.Vector2(1, 1) }, // Default
            uTexture: { value: null as THREE.Texture | null },
            uDataTexture: { value: null as THREE.DataTexture | null }
        };

        // Load Image
        const textureLoader = new THREE.TextureLoader();
        textureLoader.load(imageSrc, (texture) => {
            texture.minFilter = THREE.LinearFilter;
            texture.magFilter = THREE.LinearFilter;
            // Set aspect ratio for the "cover" logic
            uniforms.imageResolution.value.set(texture.image.width, texture.image.height);
            uniforms.uTexture.value = texture;
            handleResize(); // Trigger resize to fit image correctly
        });

        // Initialize Physics Data (The "Grid")
        const size = grid;
        const count = size * size;
        const data = new Float32Array(4 * count);

        // Fill with zeroes (neutral state)
        for (let i = 0; i < count; i++) {
            data[i * 4] = 0;
            data[i * 4 + 1] = 0;
            data[i * 4 + 2] = 0;
            data[i * 4 + 3] = 0;
        }

        const dataTexture = new THREE.DataTexture(
            data,
            size,
            size,
            THREE.RGBAFormat,
            THREE.FloatType
        );
        dataTexture.needsUpdate = true;
        uniforms.uDataTexture.value = dataTexture;

        // --- MESH ---
        const material = new THREE.ShaderMaterial({
            side: THREE.DoubleSide,
            uniforms,
            vertexShader,
            fragmentShader,
            transparent: true
        });
        materialRef.current = material;

        const geometry = new THREE.PlaneGeometry(1, 1, size - 1, size - 1);
        const plane = new THREE.Mesh(geometry, material);
        planeRef.current = plane;
        scene.add(plane);

        // --- EVENTS & LOGIC ---

        const mouseState = { x: 0, y: 0, prevX: 0, prevY: 0, vX: 0, vY: 0 };

        const handleMouseMove = (e: MouseEvent) => {
            const rect = container.getBoundingClientRect();
            // Normalize mouse to 0..1
            const x = (e.clientX - rect.left) / rect.width;
            const y = 1 - (e.clientY - rect.top) / rect.height; // Invert Y for WebGL

            // Calculate Velocity
            mouseState.vX = x - mouseState.prevX;
            mouseState.vY = y - mouseState.prevY;

            mouseState.x = x;
            mouseState.y = y;
            mouseState.prevX = x;
            mouseState.prevY = y;
        };

        const handleMouseLeave = () => {
            // Optional: Reset velocity on leave
            mouseState.vX = 0;
            mouseState.vY = 0;
        };

        container.addEventListener('mousemove', handleMouseMove);
        container.addEventListener('mouseleave', handleMouseLeave);

        const handleResize = () => {
            if (!container || !renderer || !camera || !plane) return;

            const width = container.offsetWidth;
            const height = container.offsetHeight;

            renderer.setSize(width, height);

            // Update Uniforms for shader aspect ratio math
            uniforms.resolution.value.set(width, height, 1, 1);

            // Update Plane Scale to fill container
            const containerAspect = width / height;
            // Since it's orthographic and we want full screen, 
            // we match the frustum to the aspect ratio
            const frustumHeight = 1;
            const frustumWidth = frustumHeight * containerAspect;

            camera.left = -frustumWidth / 2;
            camera.right = frustumWidth / 2;
            camera.top = frustumHeight / 2;
            camera.bottom = -frustumHeight / 2;
            camera.updateProjectionMatrix();

            plane.scale.set(containerAspect, 1, 1);
        };

        if (window.ResizeObserver) {
            const resizeObserver = new ResizeObserver(() => handleResize());
            resizeObserver.observe(container);
            resizeObserverRef.current = resizeObserver;
        } else {
            window.addEventListener('resize', handleResize);
        }

        // Initial resize
        handleResize();

        // --- ANIMATION LOOP ---
        const animate = () => {
            animationIdRef.current = requestAnimationFrame(animate);

            if (!materialRef.current || !dataTexture) return;

            // Update Time
            materialRef.current.uniforms.time.value += 0.05;

            // 1. RELAXATION (Dampen the forces)
            // We read the array directly for performance
            const data = dataTexture.image.data as Float32Array;

            for (let i = 0; i < count; i++) {
                // Multiply by relaxation factor (e.g., 0.9) to make ripples fade
                data[i * 4] *= relaxation;
                data[i * 4 + 1] *= relaxation;
            }

            // 2. ADD MOUSE FORCE
            // Map mouse position to grid coordinates
            const gridMouseX = size * mouseState.x;
            const gridMouseY = size * mouseState.y;
            const maxDist = size * mouse;
            const distSqThreshold = maxDist * maxDist;

            // Only loop if there is significant velocity
            if (Math.abs(mouseState.vX) > 0.001 || Math.abs(mouseState.vY) > 0.001) {
                for (let i = 0; i < size; i++) {
                    for (let j = 0; j < size; j++) {
                        const distSq = (gridMouseX - i) ** 2 + (gridMouseY - j) ** 2;

                        if (distSq < distSqThreshold) {
                            const index = 4 * (i + size * j);
                            // Force falls off with distance
                            const power = maxDist / Math.sqrt(distSq);

                            // Add velocity to the red/green channels of the data texture
                            // 100 is an arbitrary multiplier to make the effect visible
                            data[index] += strength * 100 * mouseState.vX * power;
                            data[index + 1] += strength * 100 * mouseState.vY * power;
                        }
                    }
                }
            }

            // 3. UPDATE TEXTURE
            dataTexture.needsUpdate = true;
            renderer.render(scene, camera);
        };

        animate();

        // --- CLEANUP ---
        return () => {
            if (animationIdRef.current) cancelAnimationFrame(animationIdRef.current);
            if (resizeObserverRef.current) resizeObserverRef.current.disconnect();
            window.removeEventListener('resize', handleResize);
            container.removeEventListener('mousemove', handleMouseMove);
            container.removeEventListener('mouseleave', handleMouseLeave);

            if (renderer) {
                renderer.dispose();
                if (container.contains(renderer.domElement)) {
                    container.removeChild(renderer.domElement);
                }
            }

            // Dispose Three.js resources
            if (geometry) geometry.dispose();
            if (material) material.dispose();
            if (dataTexture) dataTexture.dispose();
            if (uniforms.uTexture.value) uniforms.uTexture.value.dispose();
        };
    }, [grid, mouse, strength, relaxation, imageSrc]);

    return (
        <div
            ref={containerRef}
            className={`relative w-full h-full overflow-hidden ${className}`}
        />
    );
};

export default GridDistortion;

Update the import paths to match your project setup.

Similar components

3D Showcase Hero

Liquid Reveal

Pulse Stripes Layout

Shaders Hero Section

Resource details

PublishedApril 24, 2026
CategoryHero
ReactThree.jsGLSL