
instantshader is a vanilla JavaScript library for animated WebGL gradient backgrounds.
It has 10+ shaders for fluid, glowing, fabric, and geometric patterns, plus 5 stackable effects for pixelation, dithering, halftone, ASCII, and tint on gradients or images.
The library accepts 2 to 8 hex colors, supports repeatable animation loops and exact-size frame export, and has a separate React component package.
Features
- OKLCh interpolation for multicolor gradient palettes.
- Bayer and blue-noise dithering patterns.
- Media sources including images, canvases, video frames, and
ImageBitmap objects. - Ordered effect layers with blending and opacity controls.
- Live palette, shader parameter, and playback controls.
- Responsive canvas sizing with device-pixel-ratio rendering capped at 2x.
- Seekable frame rendering for thumbnails and video encoders.
How To Use It
Installation
Install the core ESM package in a Vanilla JavaScript or TypeScript project:
npm install instantshader
For React apps, install the component package instead:
npm install @instantshader/react
Basic Usage
Give the container a width and height before mounting the shader.
<div id="gradient-hero" style="width: 100%; height: 360px;"></div>
import { mountGradient, halo } from "instantshader";
const hero = document.querySelector("#gradient-hero");
const gradient = mountGradient(hero, {
shader: halo,
colors: ["#170b39", "#7948d7", "#f476a4", "#ffd995"],
params: { radius: 1.2, y: -0.7, glow: 0.7 },
});
// Keep gradient to update, pause, or dispose of the canvas later.
For a static HTML page, place the container shown above before this module script. Use this CDN example as an alternative to the npm import.
<script type="module">
import { mountGradient, halo } from "https://cdn.jsdelivr.net/npm/instantshader/dist/index.js";
mountGradient(document.querySelector("#gradient-hero"), {
shader: halo,
colors: ["#170b39", "#7948d7", "#f476a4", "#ffd995"],
});
</script>
Choose a Shader
| Shader | Appearance |
|---|
flow | Swirling fluid gradients and moving color currents. |
beam | A luminous beam stretching across a dark background. |
bloom | Large overlapping petal shapes with animated color flow. |
halo | A glowing eclipse or horizon with corona effects. |
strata | Layered cut-paper forms and soft shadows. |
dune | Overlapping wave crests with soft fades. |
whorl | Curved blades forming an adjustable spiral. |
silk | Shaded satin folds with directional highlights. |
nacre | Iridescent liquid folds. |
burst | Radiating light streaks with optional twisting. |
glint | Small rotating shards moving along a current. |
Change Colors and Animation Settings
Keep the returned handle to update a mounted gradient. setParams() merges new values into the current shader settings.
gradient.setColors(["#081d3d", "#178caa", "#74e6d0"]);
gradient.setParams({ radius: 0.45, y: 0, flares: 0.3 });
gradient.setSpeed(0.6);
gradient.pause();
gradient.resume();
Use seed to reproduce a composition and loopSeconds for an exactly repeating animation.
Loop duration is measured in animation seconds: a 30-second loop at speed: 2 takes 15 real seconds. Very short loops can alter the motion of individual shaders.
<div id="looping-gradient" style="width: 100%; height: 320px;"></div>
import { mountGradient, flow } from "instantshader";
const loopingGradient = mountGradient(document.querySelector("#looping-gradient"), {
shader: flow,
colors: ["#0d1439", "#7363ec", "#ed75c1"],
seed: 7,
loopSeconds: 30,
speed: 1,
});
Apply Effects to a Gradient
mountStack() accepts a shader or media source followed by an ordered array of effects. The first effect is closest to the original image.
<div id="effect-gradient" style="width: 100%; height: 360px;"></div>
import { mountStack, bloom, dither, tint } from "instantshader";
const stack = mountStack(document.querySelector("#effect-gradient"), {
source: { kind: "generator", shader: bloom, params: { petals: 10 } },
colors: ["#171335", "#9e3884", "#f49268", "#f9e3a1"],
effects: [
{
effect: dither,
params: {
pattern: "blueNoise",
size: 4,
colorMode: "palette",
levels: 4,
blend: "normal",
opacity: 1,
},
},
{ effect: tint, params: { mode: "palette", amount: 0.35 } },
],
loopSeconds: 30,
});
Apply Halftone or ASCII to an Image
Provide a local image at /images/sample-photo.jpg, or change the URL to an image on your site.
Media sources also accept HTMLCanvasElement, HTMLVideoElement, and ImageBitmap. Use fit: "contain" to display the entire image and background for any surrounding area.
<div id="image-effect" style="width: 100%; height: 420px;"></div>
import { mountStack, halftone } from "instantshader";
const image = new Image();
image.src = "/images/sample-photo.jpg";
await image.decode();
const imageEffect = mountStack(document.querySelector("#image-effect"), {
source: { kind: "media", media: image, fit: "contain" },
colors: ["#111827", "#faf4e7"],
background: "#faf4e7",
effects: [
{
effect: halftone,
params: {
ground: "paper",
blend: "normal",
shape: "dot",
size: 18,
colorMode: "duotone",
ink: "#111827",
paper: "#faf4e7",
},
},
],
});
For video, create a stack with the video element as media and call refreshMedia() when the frame advances.
Render a PNG Frame
renderGradientFrame() creates a detached canvas at an exact pixel size.
import { renderGradientFrame, strata } from "instantshader";
const { canvas, dispose } = renderGradientFrame({
shader: strata,
colors: ["#171335", "#a33a83", "#f2ad63", "#f9e6a9"],
width: 1920,
height: 1080,
seed: 4,
timeMs: 1500,
});
const pngDataUrl = canvas.toDataURL("image/png");
dispose();
For effect layers, renderStackFrame() also accepts source and effects. For video output, reuse a canvas with createRenderer() or createStackRenderer() and render every frame with renderAt(timeMs). An external video encoder is required to produce an MP4 file.
Use It in React & Next.js
import { Halo, dither } from "@instantshader/react";
export default function GradientHero() {
return (
<div style={{ height: 360, position: "relative" }}>
<Halo
colors={["#170b39", "#7948d7", "#f476a4", "#ffd995"]}
params={{ radius: 1, y: -0.65 }}
effects={[{ effect: dither, params: { size: 3, opacity: 0.5 } }]}
style={{ width: "100%", height: "100%" }}
/>
</div>
);
}
Configuration and API Reference
`mountGradient(container, options)`
| Option | Description |
|---|
shader | Required ShaderDef, such as flow, halo, or silk. |
colors | Required array of two to eight hex colors in gradient order. |
params | Shader-specific numeric values. Unset keys use the shader defaults. |
speed | Animation speed multiplier; default 1. Set 0 to freeze movement. |
seed | Composition seed; default 0. |
loopSeconds | Exact animation loop duration in seconds; disabled by default. |
`mountStack(container, options)`
container is a real DOM element. options supplies a source and optional layers. A stack has the common animation options colors, seed, speed, and loopSeconds. Media sources accept HTML images, canvases, video elements, or ImageBitmap. The fit field is "cover" (default) or "contain". Generator parameters are numeric; effect parameters can be numbers, strings, or booleans. Each effect layer is enabled by default.
| Option | Description |
|---|
source | Required source object. Choose { kind: "generator", shader, params? } or { kind: "media", media, fit? }. |
colors | Required palette of hex colors; also used by palette-colored effects on media. |
effects | Array of { effect, params?, enabled? } layers in bottom-to-top order; default []. |
speed | Playback multiplier; default 1 for mounted stacks. |
seed | Randomized composition seed; default 0. |
loopSeconds | Optional repeating animation period; disabled by default. |
background | Background behind transparent or contain-fitted media; default black. |
fontFamily | CSS font-family used by text effects; default system monospace. |
Mount Handle Methods
// Shared by MountHandle and StackHandle:
handle.setColors(colors); // Replace the palette.
handle.setSpeed(1.5); // Change playback speed.
handle.setLoopSeconds(20); // Set the exact loop period.
handle.setLoopSeconds(undefined); // Disable looping (0 also disables it).
handle.pause(); // Stop the animation frame loop.
handle.resume(); // Resume playback.
handle.seek(2500); // Jump to 2.5 seconds.
handle.getTimeMs(); // Read the playback position.
handle.canvas; // Read the HTML canvas element.
handle.dispose(); // Stop rendering and release WebGL resources.
// Only on the MountHandle returned by mountGradient():
handle.setParams({ scale: 1.4 }); // Merge shader parameters.
// Only on the StackHandle returned by mountStack():
stack.setSource(source); // Replace the generator or media source.
stack.setSourceParams({ petals: 8 }); // Merge generator parameters; no-op for media.
stack.setEffects(layers); // Replace the ordered effect layers.
stack.setEffectParams(0, { size: 6 }); // Merge parameters into layer 0.
stack.refreshMedia(); // Upload the current media frame.
stack.getGridInfo(); // Read the grid data for enabled grid effects.
One-Shot and Seekable Rendering
| API | Parameters and result |
|---|
renderGradientFrame(options) | Requires shader, colors, width, and height; accepts params, seed, timeMs, and loopSeconds. Returns { canvas, dispose }. |
renderStackFrame(options) | Requires source, colors, width, and height; accepts effects, seed, timeMs, loopSeconds, background, and fontFamily. Returns { canvas, dispose }. |
createRenderer(options) | Requires canvas, shader, colors, params, and seed; accepts loopSeconds. Returns a seekable gradient renderer. |
createStackRenderer(options) | Requires canvas, source, and colors; accepts effects, seed, loopSeconds, background, and fontFamily. Returns a seekable stack renderer. |
Shader and Effect Discovery
| API | Description |
|---|
shaders | Array containing all 11 shader definitions. |
getShader(id) | Find a shader by its id; returns undefined for an unknown ID. |
effects | Array containing the five effect definitions. |
getEffect(id) | Find an effect by its id; returns undefined for an unknown ID. |
shader.params | Parameter metadata: key, label, min, max, step, and default. |
shader.randomParams(rand) | Create parameter values using a supplied random-number generator. |
effect.params | Effect parameter metadata: key, label, default, numeric min/max/step where applicable, type (float, enum, bool, or color), enum options, and optional conditional when. |
effect.randomParams(rand) | Create a randomized set of effect parameters. |
Low-Level Utilities
| Export | Purpose |
|---|
gridFor(width, height, cell, lattice?) | Returns grid dimensions and scaling for a frame. cell is a two-number tuple; optional lattice accepts { angle } in degrees. The returned Grid contains cols, rows, cell, ref, pxPerCell, angle, and extent. |
buildPaletteRamp(colors) | Converts hex colors into a 1024-texel OKLCh-interpolated RGBA lookup table (Uint8Array). The utility accepts one or more stops. |
React Component Props
| Prop | Description |
|---|
colors | Required array of gradient palette colors. |
params | Shader-specific parameter overrides on shader components and ShaderCanvas. |
effects | Ordered effect layers. |
speed | Playback multiplier; default 1. |
seed | Composition seed; default 0. |
loopSeconds | Seamless loop period in animation seconds. |
paused | Pause or resume playback; default false. |
className | Class applied to the canvas container <div>. |
style | React styles applied to the canvas container <div>. |
shader | Required ShaderDef for ShaderCanvas. |
source | Required generator or media source for ShaderStack. |
background | Background color for ShaderStack, used with media. |
fontFamily | Font for ASCII effects in ShaderStack and its shader wrappers. |
Shader Parameters
flow
| Parameter | Range, default, and behavior |
|---|
scale | 0.6 to 2.6; default 1.7. Size of the color masses. |
curl | 0.3 to 1.6; default 1.05. Swirl tightness. |
drift | 0 to 1; default 0.5. Strength of the swirling currents. |
openness | 0 to 1; default 0.28. Openness around the first palette color. |
grain | 0 to 0.3; default 0.08. Film grain strength. |
beam
| Parameter | Range, default, and behavior |
|---|
scale | 0.5 to 2; default 0.75. Beam curvature. |
width | 0.04 to 0.6; default 0.4. Beam thickness. |
glow | 0 to 1; default 0.5. Spread of light outside the beam. |
angle | 0 to 360; default 28. Beam direction, in degrees. |
grain | 0 to 0.3; default 0.08. Film grain strength. |
bloom
| Parameter | Range, default, and behavior |
|---|
scale | 0.5 to 2; default 0.9. Petal length. |
petals | 6 to 16; default 11. Petals around the full circle (about half are in frame). |
pinch | 0.35 to 2.5; default 0.6. Controls petal width and taper. |
bend | -0.9 to 0.9; default 0.25. Curves the petals one way or the other. |
sway | 0 to 1; default 0.5. Petal movement. |
colorflow | 0 to 1; default 0. Outward motion of colors through the petals. |
grain | 0 to 0.3; default 0.08. Film grain strength. |
halo
| Parameter | Range, default, and behavior |
|---|
radius | 0.12 to 1.6; default 1. Disc radius, in frame heights. |
x | -1 to 1; default 0. Disc position. 0 is centered; ±1 puts the disc just outside that edge, whatever the radius. |
y | -1 to 1; default -0.78. Disc position. 0 is centered; ±1 puts the disc just outside that edge, whatever the radius. |
glow | 0 to 1; default 0.5. Reach of the corona. |
crescent | 0 to 1; default 0.35. 0 is a full ring, 1 a single lit arc. |
flares | 0 to 1; default 0.5. Streamer strength, from smooth glow to spiky corona. |
grain | 0 to 0.3; default 0.08. Film grain strength. |
strata
| Parameter | Range, default, and behavior |
|---|
scale | 0.4 to 2.5; default 1. Size of the landscape. |
layers | 3 to 16; default 7. Number of paper sheets. |
warp | 0 to 1; default 0.5. Round islands at 0, liquid marbled shorelines at 1. |
ridges | 0 to 1; default 0.25. Amount of branching ridge detail. |
stretch | 0 to 1; default 0.2. Length of stretched bands. |
depth | 0 to 1; default 0.6. Shadow length and strength; 0 is flat. |
blend | 0 to 1; default 0.15. 0 is one flat color per sheet, 1 a continuous gradient. |
angle | 0 to 360; default 125. Where the light comes from, in degrees. |
grain | 0 to 0.3; default 0.06. Film grain strength. |
dune
| Parameter | Range, default, and behavior |
|---|
layers | 2 to 12; default 6. Number of crests. |
swell | 0 to 1.6; default 0.7. Crest height; high values make crests cross each other. |
waves | 0.3 to 5; default 1.4. Undulations across the frame. |
fade | 0 to 1.5; default 0.9. How far each layer fades below its crest. |
soft | 0 to 1; default 0.02. Softness of crest edges. |
angle | 0 to 360; default 352. Rotation of the whole stack, in degrees. |
grain | 0 to 0.3; default 0.05. Film grain strength. |
whorl
| Parameter | Range, default, and behavior |
|---|
blades | 2 to 24; default 9. Number of blades. |
twist | -3 to 3; default 1.1. Spiral tightness; the sign picks the winding direction, 0 is a straight fan. |
depth | 0 to 1.5; default 0.8. Strength of the crease at each blade edge. |
scale | 0.3 to 3; default 1.2. Distance over which the palette runs, center to rim. |
wobble | 0 to 1; default 0. Blade irregularity; 0 is symmetrical. |
x | -1.5 to 1.5; default -0.55. Center position. 0 is the middle, ±1 the frame edge, beyond is off-frame. |
y | -1.5 to 1.5; default -0.7. Center position. 0 is the middle, ±1 the frame edge, beyond is off-frame. |
grain | 0 to 0.3; default 0.06. Film grain strength. |
silk
| Parameter | Range, default, and behavior |
|---|
scale | 0.3 to 2.5; default 1. Fold size. |
folds | 0 to 1; default 0.6. 0 is rumpled cloth, 1 long parallel drapery. |
depth | 0.2 to 2; default 1. Relief height; how steeply the folds shade. |
warp | 0 to 1; default 0.5. Bends the folds so they gather and fork. |
sheen | 0 to 1; default 0.6. Satin highlight strength. |
light | 0 to 360; default 20. Light direction relative to the folds. 0 and 180 rake across them, 90 and 270 flatten the relief. |
grain | 0 to 0.5; default 0.06. Film grain strength. |
nacre
| Parameter | Range, default, and behavior |
|---|
scale | 0.4 to 2; default 0.9. Lobe size. |
flow | 0 to 1; default 0.5. Domain warp: 0 round pools, 1 pulled liquid. |
crease | 0 to 1; default 0.6. Thin fold lines hugging the lobes’ edges. |
depth | 0.2 to 2; default 1. Relief height and slope color shifts. |
iridescence | 0 to 1; default 0.6. Amount of color change across the slopes; 0 keeps a lit gradient. |
light | 0 to 360; default 40. Light direction, in degrees. |
grain | 0 to 0.3; default 0.04. Film grain strength. |
burst
| Parameter | Range, default, and behavior |
|---|
rays | 0 to 1; default 0.45. Ray count: 8 broad rays at 0, 80 needles at 1. |
sharp | 0 to 1; default 0.6. Ray contrast: 0 soft sectors, 1 hard-edged rays. |
glow | 0 to 1; default 0.7. Center brightness, from dark to bright. |
twist | 0 to 1; default 0.2. Rays curve into a pinwheel. |
x | -1 to 1; default 0.1. Center position; 0 is the middle, ±1 the frame edge. |
y | -1 to 1; default 0.05. Center position; 0 is the middle, ±1 the frame edge. |
grain | 0 to 0.3; default 0.14. Film grain strength. |
glint
| Parameter | Range, default, and behavior |
|---|
size | 0.01 to 0.06; default 0.03. Shard length, in frame heights. |
density | 0.2 to 1; default 0.6. How many cells hold a shard. |
bend | 0 to 1; default 0.5. How far the current arcs across the frame. |
angle | 0 to 360; default 10. Direction of the current. |
speed | 0.3 to 2; default 1. Streaming speed when not looping; a loop always travels one pattern period. |
grain | 0 to 0.3; default 0.06. Film grain strength. |
Effect Parameters
Effect layers accept parameter overrides through params; unspecified fields use their defaults. For pixelate, dither, halftone, and ascii, sizes are measured in reference pixels at 1920 x 1080 and scale with output resolution.
The blend values are normal, multiply, screen, overlay, softLight, and colorDodge. blend and opacity are available for pixelate, dither, halftone, and ascii. tint uses its own amount setting.
Pixelate
| Parameter | Range, default, and behavior |
|---|
size | 2 to 160; default 13. Pixel cell size. |
levels | 0 to 16; default 0. Color levels per channel; 0 preserves full color. |
gap | 0 to 0.4; default 0.08. Grid-line width relative to cell size. |
gapColor | Hex color; default #000000. Grid-line color. |
blend | Blend mode; default normal. |
opacity | 0 to 1; default 1. Effect opacity. |
Dither
Floyd-Steinberg and other error-diffusion algorithms are not included. For a full-frame dither, set blend: "normal" and opacity: 1.
| Parameter | Range, default, and behavior |
|---|
pattern | bayer2, bayer4, bayer8, blueNoise; default bayer8. |
size | 1 to 16; default 3. Dithering cell size. |
levels | 2 to 8; default 4. Tone or palette levels. |
bias | -0.5 to 0.5; default 0. Tone offset before quantization. |
linear | Boolean; default true. Threshold in linear light. |
shimmer | 0 to 12; default 0. Pattern changes per second. |
colorMode | source, duotone, palette; default source. |
ink | Hex color; default #000000. Duotone ink color. |
paper | Hex color; default #ffffff. Duotone paper color. |
invert | Boolean; default false. Reverse the tone scale. |
blend | Blend mode; default softLight. |
opacity | 0 to 1; default 0.6. Effect opacity. |
Halftone
| Parameter | Range, default, and behavior |
|---|
ground | image, paper; default image. Render marks over the image or on a flat background. |
blend | Blend mode; default screen. |
opacity | 0 to 1; default 1. Mark opacity. |
blur | 0 to 40; default 0. Backdrop blur with image ground. |
grid | square, hex; default square. Dot arrangement. |
shape | dot, line, square; default square. square at 45 degrees creates diamonds. |
size | 6 to 160; default 20. Screen pitch. |
angle | 0 to 180; default 45. Screen rotation in degrees. |
radius | 0.2 to 1.5; default 0.75. Relative mark size. |
softness | 0 to 1; default 0.1. Edge softness. |
style | filled, uniform; default filled. Tone-sized or fixed-size marks. |
exposure | -1 to 1; default 0. Tone adjustment for mark sizing. |
contrast | 0 to 2; default 1.15. Tone contrast for mark sizing. |
density | 0 to 1; default 1. Fraction of cells containing marks. |
colorMode | source, duotone, palette; default source. |
ink | Hex color; default #111111. Single ink color in duotone mode. |
paper | Hex color; default #f4f1ea. Background color when ground is paper. |
invert | Boolean; default false. Reverse tone response. |
ASCII
| Parameter | Range, default, and behavior |
|---|
ground | image, paper; default image. Characters over image or paper. |
blend | Blend mode; default colorDodge. |
opacity | 0 to 1; default 1. Character opacity. |
blur | 0 to 40; default 0. Backdrop blur with image ground. |
charset | standard, dense, blocks, minimal, binary, katakana; default standard. |
size | 8 to 96; default 10. Character height. |
smooth | Boolean; default true. Dither between adjacent characters. |
cycle | 0 to 12; default 2. Character rerolls per second. |
cycleAmount | 0 to 1; default 0.2. Fraction of characters that reroll. |
style | filled, uniform; default filled. Tone-sized or fixed-size characters. |
exposure | -1 to 1; default 0. Tone adjustment for character selection. |
contrast | 0 to 2; default 1.2. Tone contrast. |
density | 0 to 1; default 1. Fraction of cells with characters. |
colorMode | source, duotone, palette; default source. |
ink | Hex color; default #e8ffe8. Text color in duotone mode. |
paper | Hex color; default #000000. Background when ground is paper. |
invert | Boolean; default false. Reverse tone response. |
Tint
| Parameter | Range, default, and behavior |
|---|
mode | duotone, palette; default duotone. Map brightness through two colors or the full palette. |
dark | Hex color; default #1b1a4a. Shadow color in duotone mode. |
light | Hex color; default #f2c6a0. Highlight color in duotone mode. |
amount | 0 to 1; default 1. Recolor strength. |
Alternatives and Related Resources