Shader Text Reveal
Reveal words through the original OpenShaders hero shader, then settle into white type.
Source
components/kuchi/shader-text-reveal.tsx
1"use client";23import { useLayoutEffect, useRef } from "react";4import { useCurrentFrame, useDelayRender, useVideoConfig } from "remotion";56export type ShaderTextRevealProps = {7 /** Words appear one at a time. Separate phrases with newlines to keep them together. */8 text?: string;9 fontSize?: number;10 fontFamily?: string;11 fontWeight?: number;12 /** Frames per word, including its entrance and exit. The final word stays visible. */13 wordDuration?: number;14 /** Strength of the original hero shader inside the letters, from 0 to 1. */15 intensity?: number;16};1718const clamp = (n: number, min = 0, max = 1) => Math.min(max, Math.max(min, n));1920export function getShaderTextState(21 frame: number,22 wordCount: number,23 wordDuration: number,24) {25 const duration = Math.max(12, Math.round(wordDuration));26 const count = Math.max(1, wordCount);27 const f = Math.max(0, frame);28 const index = Math.min(count - 1, Math.floor(f / duration));29 const local = f - index * duration;30 const enter = clamp((local / duration + 0.16) / 0.76);31 const exit =32 index === count - 1 ? 0 : clamp((local / duration - 0.65) / 0.35);33 return {34 index,35 enter,36 exit: exit * exit * (3 - 2 * exit),37 scale: 1 + 0.12 * (1 - enter) ** 3,38 };39}4041const VERTEX = `#version 300 es42void main() {43 vec2 p = vec2(float((gl_VertexID << 1) & 2), float(gl_VertexID & 2));44 gl_Position = vec4(p * 2.0 - 1.0, 0.0, 1.0);45}`;4647/* @kuchi · OpenShaders — https://openshaders.com/@kuchi48 * Original hero field and halftone GLSL. Only its clock is driven by Remotion.49 */50const HERO_FIELD = `#version 300 es51precision highp float;5253uniform vec2 iResolution;54uniform float iTime;55uniform float uLightMode;56uniform vec3 uDarkBackground;57uniform vec3 uLightBackground;58out vec4 fragColor;5960const float HUE = 0.663466752;61const float HUE_SPREAD = 0.314346701;62const float HUE_TRAVEL = 1.65112376;63const float CHROMA = 0.160295546;64const float LIGHTNESS = 0.537409723;65const float COLOUR_CYCLE = 0.124862425;66const float THETA = 2.12986207;67const float SHEAR = 0.968176901;68const float SHRINK = 0.955401778;69const float LAYERS = 72.0;70const float WARP_FREQ_X = 0.439311415;71const float WARP_FREQ_Y = 2.87923527;72const float WARP_AMP_X = 0.156202048;73const float WARP_AMP_Y = 0.0256033838;74const float ASPECT_X = 2.23183894;75const float ASPECT_Y = 0.15731883;76const float OFFSET_X = 0.375628948;77const float OFFSET_Y = -0.017801486;78const float TILT = 1.63293767;79const float ZOOM = 0.93135649;80const float CENTRE_X = -0.0956316143;81const float CENTRE_Y = -0.520057321;82const float GLOW_SIZE = 0.00201825937;83const float FALLOFF = 0.352821857;84const float VIGNETTE = 0.136085436;85const float FLOW_SPEED = 0.391012281;86const float FLOW_DIRECTION = 1.0;87const float BREATH_RATE = 0.382053256;88const float BREATH_AMOUNT = 0.0873704553;89const float PHASE = 56.3862724;90const float ECHO = 0.0;91const float ECHO_SHIFT = 0.178754866;92const float SOFTNESS = 0.00164903817;93const float LIGHT_SWING = 0.149726808;9495const float TAU = 6.28318530718;9697vec3 oklchToLinear(float L, float C, float h) {98 float a = C * cos(h), b = C * sin(h);99 float l_ = L + 0.3963377774 * a + 0.2158037573 * b;100 float m_ = L - 0.1055613458 * a - 0.0638541728 * b;101 float s_ = L - 0.0894841775 * a - 1.2914855480 * b;102 vec3 lms = vec3(l_, m_, s_);103 lms = lms * lms * lms;104 return mat3(4.0767416621, -1.2684380046, -0.0041960863,105 -3.3077115913, 2.6097574011, -0.7034186147,106 0.2309699292, -0.3413193965, 1.7076147010) * lms;107}108109float blueNoise(vec2 p, float frame) {110 p += 5.588238 * mod(frame, 64.0);111 return fract(52.9829189 * fract(0.06711056 * p.x + 0.00583715 * p.y));112}113114void main() {115 vec2 R = iResolution.xy;116 vec2 pos = (gl_FragCoord.xy - 0.5 * R) / R.y;117 float t = iTime * FLOW_SPEED * FLOW_DIRECTION + PHASE;118 float breath = (-sin(iTime * BREATH_RATE * 1.5) + sin(iTime * BREATH_RATE + 1.0)) * 0.25 + 0.5;119120 vec2 u = (pos - vec2(CENTRE_X, CENTRE_Y)) * (ZOOM - breath * BREATH_AMOUNT);121 float ct = cos(TILT), st = sin(TILT);122 u = mat2(ct, st, -st, ct) * u;123124 mat2 fold = mat2(cos(THETA), sin(THETA), -SHEAR, cos(THETA));125126 float hue0 = HUE * TAU;127 float hue1 = hue0 + HUE_SPREAD * TAU;128 vec3 color = vec3(0.0);129130 for (float i = 1.0; i <= 96.0; i += 1.0) {131 if (i > LAYERS) break;132 u.x += -sin(u.y * WARP_FREQ_X + t + i * 0.007) * WARP_AMP_X;133 u.y += -sin(u.x * WARP_FREQ_Y - t + i * 0.02) * WARP_AMP_Y;134 u = fold * u * SHRINK;135136 vec2 q = u - vec2(OFFSET_X + breath * 0.1, OFFSET_Y);137 vec2 s = vec2(q.x * ASPECT_X, q.y * ASPECT_Y);138 float glow = GLOW_SIZE / (dot(s, s) + SOFTNESS);139#ifndef SKIP_ECHO140 vec2 e = vec2((q.x - ECHO_SHIFT) * ASPECT_X, s.y);141 glow += ECHO * GLOW_SIZE / (dot(e, e) + SOFTNESS);142#endif143 glow *= 0.25 + breath * 0.4;144145 float r = length(u);146 float k = sin(i * COLOUR_CYCLE + t * 1.2 + r * HUE_TRAVEL) * 0.5 + 0.5;147 vec3 tint = clamp(oklchToLinear(LIGHTNESS + LIGHT_SWING * k, CHROMA * (0.75 + 0.35 * k), mix(hue0, hue1, k)), 0.0, 1.0);148 color += glow * tint * exp2(-r * FALLOFF);149 }150151 vec3 x = max(color, 0.0);152 color = (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14);153 color = pow(clamp(color, 0.0, 1.0), vec3(0.85, 0.92, 0.98));154155 float edge = smoothstep(0.5, 1.6, length(pos));156 color *= 1.0 - edge * VIGNETTE;157158 vec3 dark = uDarkBackground + color * (1.0 - uDarkBackground);159 float strength = max(color.r, max(color.g, color.b));160 vec3 light = uLightBackground * (1.0 - strength) + color * 0.96;161 color = mix(dark, light, uLightMode);162163 color += (blueNoise(gl_FragCoord.xy, floor(iTime * 24.0)) - 0.5) / 255.0;164 fragColor = vec4(clamp(color, 0.0, 1.0), 1.0);165}166`;167168const HERO_HALFTONE = `#version 300 es169precision highp float;170171uniform sampler2D tScene;172uniform vec2 iResolution;173uniform float iTime;174uniform float uLightMode;175uniform vec3 uDarkBackground;176uniform vec3 uLightBackground;177uniform float uPixelRatio;178out vec4 fragColor;179180const float uStrength = 0.797335207;181const float uScale = 0.985214949;182const float uSeed = 0.435611069;183184const float TAU = 6.28318530718;185const vec3 LUMA = vec3(0.2126, 0.7152, 0.0722);186187vec3 toInk(vec3 c) { return mix(c - uDarkBackground, uLightBackground - c, uLightMode); }188vec3 fromInk(vec3 ink) { return mix(uDarkBackground + ink, uLightBackground - ink, uLightMode); }189vec3 sceneInk(vec2 uv) { return toInk(texture(tScene, clamp(uv, 0.0, 1.0)).rgb); }190191float blueNoise(vec2 p, float frame) {192 p += 5.588238 * mod(frame, 64.0);193 return fract(52.9829189 * fract(0.06711056 * p.x + 0.00583715 * p.y));194}195196vec3 halftone(vec2 frag) {197 float cell = max(3.0, uScale * 3.6 * uPixelRatio);198 float angle = 0.26 + uSeed * 0.3;199 mat2 turn = mat2(cos(angle), -sin(angle), sin(angle), cos(angle));200 vec2 rotated = turn * frag;201 vec2 grid = floor(rotated / cell);202 vec2 centre = (grid + 0.5) * cell;203 vec2 source = transpose(turn) * centre;204 vec3 soft = sceneInk(frag / iResolution);205 vec3 ink = sceneInk(source / iResolution);206 float level = clamp(dot(ink, LUMA), 0.0, 1.0);207 float radius = cell * sqrt(pow(level, 0.9) / 3.14159265);208 float dist = length(rotated - centre);209 float aa = 0.7 * uPixelRatio;210 float dot_ = 1.0 - smoothstep(radius - aa, radius + aa, dist);211 vec3 dots = ink * min(0.8 / max(level, 1e-3), 2.2) * dot_;212 float presence = smoothstep(0.03, 0.16, level) * (0.3 + 0.14 * uStrength);213 return mix(soft, dots, presence);214}215216void main() {217 vec2 frag = gl_FragCoord.xy;218 vec3 ink = halftone(frag);219 vec3 color = fromInk(clamp(ink, 0.0, 1.0));220 color += (blueNoise(frag, floor(iTime * 24.0)) - 0.5) / 255.0;221 fragColor = vec4(clamp(color, 0.0, 1.0), 1.0);222}223`;224225const FRAGMENT = `#version 300 es226precision highp float;227uniform sampler2D uText;228uniform sampler2D uHero;229uniform vec2 uResolution;230uniform vec4 uBounds;231uniform float uEnter;232uniform float uExit;233uniform float uScale;234uniform float uTime;235uniform float uIntensity;236out vec4 fragColor;237238void main() {239 vec2 uv = (gl_FragCoord.xy / uResolution - 0.5) / uScale + 0.5;240 vec2 q = (uv - uBounds.xy) / uBounds.zw;241 float flow = sin(q.x * 7.0 + q.y * 5.0 - uTime * 3.2) * 0.065242 + sin(q.x * 13.0 - q.y * 8.0 + uTime * 2.1) * 0.025;243 float rank = q.x * 0.64 + (1.0 - q.y) * 0.36 + flow;244 float d = rank - mix(-0.15, 1.65, uEnter);245 float edge = exp(-pow((d + 0.1) * 6.0, 2.0));246 // Refraction affects the glyph itself, concentrated inside the wet leading edge.247 vec3 field = texture(uHero, uv).rgb;248 vec2 warp = vec2(field.r - field.b, field.g - field.r);249 vec2 sampleUV = uv + warp * edge * uIntensity * 2.5 / uResolution;250 float glyph = texture(uText, sampleUV).a;251 float appear = 1.0 - smoothstep(-0.025, 0.09, d);252 float exitRank = q.x * 0.65 + (1.0 - q.y) * 0.5 + flow;253 float leave = smoothstep(-0.12, 0.06, exitRank - mix(-0.25, 1.45, uExit));254255 vec3 liquid = texture(uHero, sampleUV).rgb;256 vec3 silver = vec3(0.96, 0.925, 1.0);257 float settled = 1.0 - smoothstep(-0.58, -0.16, d);258 vec3 color = mix(liquid, silver, settled);259 color = mix(silver, color, uIntensity);260 float alpha = glyph * appear * leave;261 fragColor = vec4(color * alpha, alpha);262}`;263264function createRenderer(canvas: HTMLCanvasElement) {265 const gl = canvas.getContext("webgl2", {266 alpha: true,267 premultipliedAlpha: true,268 antialias: false,269 depth: false,270 });271 if (!gl) throw new Error("Shader Text Reveal requires WebGL2.");272 const shaders: WebGLShader[] = [];273 const programs: WebGLProgram[] = [];274 const textures: WebGLTexture[] = [];275 const buffers: WebGLFramebuffer[] = [];276 const dispose = () => {277 for (const shader of shaders) gl.deleteShader(shader);278 for (const program of programs) gl.deleteProgram(program);279 for (const texture of textures) gl.deleteTexture(texture);280 for (const buffer of buffers) gl.deleteFramebuffer(buffer);281 };282 const compile = (fragment: string) => {283 const program = gl.createProgram();284 if (!program) throw new Error("Shader Text Reveal: GPU allocation failed.");285 programs.push(program);286 for (const [type, source] of [287 [gl.VERTEX_SHADER, VERTEX],288 [gl.FRAGMENT_SHADER, fragment],289 ] as const) {290 const shader = gl.createShader(type);291 if (!shader)292 throw new Error("Shader Text Reveal: shader allocation failed.");293 shaders.push(shader);294 gl.shaderSource(shader, source);295 gl.compileShader(shader);296 if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS))297 throw new Error(298 gl.getShaderInfoLog(shader) ?? "Shader compilation failed.",299 );300 gl.attachShader(program, shader);301 }302 gl.linkProgram(program);303 if (!gl.getProgramParameter(program, gl.LINK_STATUS))304 throw new Error(gl.getProgramInfoLog(program) ?? "Shader link failed.");305 const locations = new Map<string, WebGLUniformLocation | null>();306 const uniform = (name: string) => {307 if (!locations.has(name))308 locations.set(name, gl.getUniformLocation(program, name));309 return locations.get(name) ?? null;310 };311 return {312 uniform,313 begin: (time: number) => {314 gl.useProgram(program);315 gl.viewport(0, 0, canvas.width, canvas.height);316 gl.uniform2f(uniform("iResolution"), canvas.width, canvas.height);317 gl.uniform1f(uniform("iTime"), time);318 gl.uniform1f(uniform("uLightMode"), 0);319 gl.uniform3f(uniform("uDarkBackground"), 9 / 255, 9 / 255, 9 / 255);320 gl.uniform3f(uniform("uLightBackground"), 1, 1, 1);321 gl.uniform1f(uniform("uPixelRatio"), 1);322 },323 };324 };325 const texture = () => {326 const value = gl.createTexture();327 if (!value)328 throw new Error("Shader Text Reveal: texture allocation failed.");329 textures.push(value);330 gl.activeTexture(gl.TEXTURE0);331 gl.bindTexture(gl.TEXTURE_2D, value);332 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);333 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);334 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);335 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);336 return value;337 };338 const target = () => {339 const value = texture();340 const buffer = gl.createFramebuffer();341 if (!buffer)342 throw new Error("Shader Text Reveal: framebuffer allocation failed.");343 buffers.push(buffer);344 gl.bindFramebuffer(gl.FRAMEBUFFER, buffer);345 gl.texImage2D(346 gl.TEXTURE_2D,347 0,348 gl.RGBA,349 canvas.width,350 canvas.height,351 0,352 gl.RGBA,353 gl.UNSIGNED_BYTE,354 null,355 );356 gl.framebufferTexture2D(357 gl.FRAMEBUFFER,358 gl.COLOR_ATTACHMENT0,359 gl.TEXTURE_2D,360 value,361 0,362 );363 if (gl.checkFramebufferStatus(gl.FRAMEBUFFER) !== gl.FRAMEBUFFER_COMPLETE)364 throw new Error("Shader Text Reveal: incomplete framebuffer.");365 return { value, buffer };366 };367 const bind = (value: WebGLTexture, unit: number) => {368 gl.activeTexture(gl.TEXTURE0 + unit);369 gl.bindTexture(gl.TEXTURE_2D, value);370 };371 try {372 const field = compile(HERO_FIELD);373 const halftone = compile(HERO_HALFTONE);374 const composite = compile(FRAGMENT);375 const text = texture();376 const raw = target();377 const hero = target();378 gl.bindFramebuffer(gl.FRAMEBUFFER, null);379 gl.clearColor(0, 0, 0, 0);380 gl.clear(gl.COLOR_BUFFER_BIT);381 let previous: HTMLCanvasElement | null = null;382 return {383 dispose,384 draw: (385 word: TextTexture,386 state: ReturnType<typeof getShaderTextState>,387 time: number,388 intensity: number,389 ) => {390 if (gl.isContextLost())391 throw new Error("Shader Text Reveal: WebGL context lost.");392 // Render the hero's original field, then its original halftone pass.393 gl.bindFramebuffer(gl.FRAMEBUFFER, raw.buffer);394 field.begin(time);395 gl.drawArrays(gl.TRIANGLES, 0, 3);396 gl.bindFramebuffer(gl.FRAMEBUFFER, hero.buffer);397 halftone.begin(time);398 bind(raw.value, 0);399 gl.uniform1i(halftone.uniform("tScene"), 0);400 gl.drawArrays(gl.TRIANGLES, 0, 3);401402 gl.bindFramebuffer(gl.FRAMEBUFFER, null);403 composite.begin(time);404 bind(text, 0);405 if (previous !== word.canvas) {406 gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);407 gl.texImage2D(408 gl.TEXTURE_2D,409 0,410 gl.RGBA,411 gl.RGBA,412 gl.UNSIGNED_BYTE,413 word.canvas,414 );415 gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);416 previous = word.canvas;417 }418 bind(hero.value, 1);419 gl.uniform1i(composite.uniform("uText"), 0);420 gl.uniform1i(composite.uniform("uHero"), 1);421 gl.uniform2f(422 composite.uniform("uResolution"),423 canvas.width,424 canvas.height,425 );426 gl.uniform4f(composite.uniform("uBounds"), ...word.bounds);427 gl.uniform1f(composite.uniform("uEnter"), state.enter);428 gl.uniform1f(composite.uniform("uExit"), state.exit);429 gl.uniform1f(composite.uniform("uScale"), state.scale);430 gl.uniform1f(composite.uniform("uTime"), time);431 gl.uniform1f(composite.uniform("uIntensity"), clamp(intensity));432 gl.drawArrays(gl.TRIANGLES, 0, 3);433 },434 };435 } catch (error) {436 dispose();437 throw error;438 }439}440441type TextTexture = {442 canvas: HTMLCanvasElement;443 bounds: [number, number, number, number];444};445446function textTexture(447 text: string,448 width: number,449 height: number,450 fontSize: number,451 fontWeight: number,452 fontFamily: string,453): TextTexture {454 const canvas = document.createElement("canvas");455 canvas.width = width;456 canvas.height = height;457 const ctx = canvas.getContext("2d");458 if (!ctx) throw new Error("Shader Text Reveal: cannot rasterize text.");459 let size = Math.min(Math.max(1, fontSize), height * 0.58);460 ctx.font = `${fontWeight} ${size}px ${fontFamily}`;461 size *= Math.min(462 1,463 (width * 0.72) / Math.max(1, ctx.measureText(text).width),464 );465 ctx.font = `${fontWeight} ${size}px ${fontFamily}`;466 const metrics = ctx.measureText(text);467 const left = (width - metrics.width) / 2;468 const ascent = metrics.actualBoundingBoxAscent;469 const descent = metrics.actualBoundingBoxDescent;470 const baseline = (height + ascent - descent) / 2;471 ctx.fillStyle = "white";472 ctx.fillText(text, left, baseline);473 return {474 canvas,475 bounds: [476 left / width,477 (height - baseline - descent) / height,478 Math.max(1, metrics.width) / width,479 Math.max(1, ascent + descent) / height,480 ],481 };482}483484export function ShaderTextReveal({485 text = "Your product",486 fontSize = 400,487 fontFamily = "Arial, sans-serif",488 fontWeight = 500,489 wordDuration = 30,490 intensity = 1,491}: ShaderTextRevealProps) {492 const frame = useCurrentFrame();493 const { width, height, fps } = useVideoConfig();494 const { delayRender, continueRender, cancelRender } = useDelayRender();495 const canvas = useRef<HTMLCanvasElement>(null);496 const resources = useRef<{497 renderer: ReturnType<typeof createRenderer>;498 words: TextTexture[];499 } | null>(null);500 const current = useRef({ frame, fps, wordDuration, intensity });501 current.current = { frame, fps, wordDuration, intensity };502503 useLayoutEffect(() => {504 const element = canvas.current;505 if (!element) return;506 let cancelled = false;507 const handle = delayRender("Load Shader Text Reveal font");508 const phrases = text.includes("\n") ? text.split("\n") : text.split(/\s+/);509 const words = phrases.map((word) => word.trim()).filter(Boolean);510 const draw = () => {511 const resource = resources.current;512 if (!resource || resource.words.length === 0) return;513 const clock = current.current;514 const state = getShaderTextState(515 clock.frame,516 resource.words.length,517 clock.wordDuration,518 );519 resource.renderer.draw(520 resource.words[state.index],521 state,522 clock.frame / clock.fps,523 clock.intensity,524 );525 };526 void document.fonts527 .load(`${fontWeight} ${fontSize}px ${fontFamily}`, text || " ")528 .then(() => {529 if (cancelled) return;530 const textures = words.map((word) =>531 textTexture(word, width, height, fontSize, fontWeight, fontFamily),532 );533 const renderer = createRenderer(element);534 resources.current = { renderer, words: textures };535 draw();536 continueRender(handle);537 })538 .catch((error: unknown) => {539 if (!cancelled)540 cancelRender(541 error instanceof Error ? error : new Error(String(error)),542 );543 });544 return () => {545 cancelled = true;546 continueRender(handle);547 resources.current?.renderer.dispose();548 resources.current = null;549 };550 }, [551 text,552 width,553 height,554 fontSize,555 fontWeight,556 fontFamily,557 delayRender,558 continueRender,559 cancelRender,560 ]);561562 useLayoutEffect(() => {563 const resource = resources.current;564 if (!resource || resource.words.length === 0) return;565 try {566 const state = getShaderTextState(567 frame,568 resource.words.length,569 wordDuration,570 );571 resource.renderer.draw(572 resource.words[state.index],573 state,574 frame / fps,575 intensity,576 );577 } catch (error) {578 cancelRender(error instanceof Error ? error : new Error(String(error)));579 }580 }, [frame, fps, wordDuration, intensity, cancelRender]);581582 return (583 <canvas584 ref={canvas}585 width={width}586 height={height}587 role="img"588 aria-label={text}589 style={{590 position: "absolute",591 inset: 0,592 width: "100%",593 height: "100%",594 pointerEvents: "none",595 }}596 />597 );598}









