Animated WebGL Gradients & Effects – instantshader

Category: Animation , Javascript | October 28, 2026
Authorugolbck
Last UpdateOctober 28, 2026
LicenseMIT
Views0 views
Animated WebGL Gradients & Effects – instantshader

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

ShaderAppearance
flowSwirling fluid gradients and moving color currents.
beamA luminous beam stretching across a dark background.
bloomLarge overlapping petal shapes with animated color flow.
haloA glowing eclipse or horizon with corona effects.
strataLayered cut-paper forms and soft shadows.
duneOverlapping wave crests with soft fades.
whorlCurved blades forming an adjustable spiral.
silkShaded satin folds with directional highlights.
nacreIridescent liquid folds.
burstRadiating light streaks with optional twisting.
glintSmall 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)`

OptionDescription
shaderRequired ShaderDef, such as flow, halo, or silk.
colorsRequired array of two to eight hex colors in gradient order.
paramsShader-specific numeric values. Unset keys use the shader defaults.
speedAnimation speed multiplier; default 1. Set 0 to freeze movement.
seedComposition seed; default 0.
loopSecondsExact 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.

OptionDescription
sourceRequired source object. Choose { kind: "generator", shader, params? } or { kind: "media", media, fit? }.
colorsRequired palette of hex colors; also used by palette-colored effects on media.
effectsArray of { effect, params?, enabled? } layers in bottom-to-top order; default [].
speedPlayback multiplier; default 1 for mounted stacks.
seedRandomized composition seed; default 0.
loopSecondsOptional repeating animation period; disabled by default.
backgroundBackground behind transparent or contain-fitted media; default black.
fontFamilyCSS 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

APIParameters 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

APIDescription
shadersArray containing all 11 shader definitions.
getShader(id)Find a shader by its id; returns undefined for an unknown ID.
effectsArray containing the five effect definitions.
getEffect(id)Find an effect by its id; returns undefined for an unknown ID.
shader.paramsParameter metadata: key, label, min, max, step, and default.
shader.randomParams(rand)Create parameter values using a supplied random-number generator.
effect.paramsEffect 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

ExportPurpose
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

PropDescription
colorsRequired array of gradient palette colors.
paramsShader-specific parameter overrides on shader components and ShaderCanvas.
effectsOrdered effect layers.
speedPlayback multiplier; default 1.
seedComposition seed; default 0.
loopSecondsSeamless loop period in animation seconds.
pausedPause or resume playback; default false.
classNameClass applied to the canvas container <div>.
styleReact styles applied to the canvas container <div>.
shaderRequired ShaderDef for ShaderCanvas.
sourceRequired generator or media source for ShaderStack.
backgroundBackground color for ShaderStack, used with media.
fontFamilyFont for ASCII effects in ShaderStack and its shader wrappers.

Shader Parameters

flow

ParameterRange, default, and behavior
scale0.6 to 2.6; default 1.7. Size of the color masses.
curl0.3 to 1.6; default 1.05. Swirl tightness.
drift0 to 1; default 0.5. Strength of the swirling currents.
openness0 to 1; default 0.28. Openness around the first palette color.
grain0 to 0.3; default 0.08. Film grain strength.

beam

ParameterRange, default, and behavior
scale0.5 to 2; default 0.75. Beam curvature.
width0.04 to 0.6; default 0.4. Beam thickness.
glow0 to 1; default 0.5. Spread of light outside the beam.
angle0 to 360; default 28. Beam direction, in degrees.
grain0 to 0.3; default 0.08. Film grain strength.

bloom

ParameterRange, default, and behavior
scale0.5 to 2; default 0.9. Petal length.
petals6 to 16; default 11. Petals around the full circle (about half are in frame).
pinch0.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.
sway0 to 1; default 0.5. Petal movement.
colorflow0 to 1; default 0. Outward motion of colors through the petals.
grain0 to 0.3; default 0.08. Film grain strength.

halo

ParameterRange, default, and behavior
radius0.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.
glow0 to 1; default 0.5. Reach of the corona.
crescent0 to 1; default 0.35. 0 is a full ring, 1 a single lit arc.
flares0 to 1; default 0.5. Streamer strength, from smooth glow to spiky corona.
grain0 to 0.3; default 0.08. Film grain strength.

strata

ParameterRange, default, and behavior
scale0.4 to 2.5; default 1. Size of the landscape.
layers3 to 16; default 7. Number of paper sheets.
warp0 to 1; default 0.5. Round islands at 0, liquid marbled shorelines at 1.
ridges0 to 1; default 0.25. Amount of branching ridge detail.
stretch0 to 1; default 0.2. Length of stretched bands.
depth0 to 1; default 0.6. Shadow length and strength; 0 is flat.
blend0 to 1; default 0.15. 0 is one flat color per sheet, 1 a continuous gradient.
angle0 to 360; default 125. Where the light comes from, in degrees.
grain0 to 0.3; default 0.06. Film grain strength.

dune

ParameterRange, default, and behavior
layers2 to 12; default 6. Number of crests.
swell0 to 1.6; default 0.7. Crest height; high values make crests cross each other.
waves0.3 to 5; default 1.4. Undulations across the frame.
fade0 to 1.5; default 0.9. How far each layer fades below its crest.
soft0 to 1; default 0.02. Softness of crest edges.
angle0 to 360; default 352. Rotation of the whole stack, in degrees.
grain0 to 0.3; default 0.05. Film grain strength.

whorl

ParameterRange, default, and behavior
blades2 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.
depth0 to 1.5; default 0.8. Strength of the crease at each blade edge.
scale0.3 to 3; default 1.2. Distance over which the palette runs, center to rim.
wobble0 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.
grain0 to 0.3; default 0.06. Film grain strength.

silk

ParameterRange, default, and behavior
scale0.3 to 2.5; default 1. Fold size.
folds0 to 1; default 0.6. 0 is rumpled cloth, 1 long parallel drapery.
depth0.2 to 2; default 1. Relief height; how steeply the folds shade.
warp0 to 1; default 0.5. Bends the folds so they gather and fork.
sheen0 to 1; default 0.6. Satin highlight strength.
light0 to 360; default 20. Light direction relative to the folds. 0 and 180 rake across them, 90 and 270 flatten the relief.
grain0 to 0.5; default 0.06. Film grain strength.

nacre

ParameterRange, default, and behavior
scale0.4 to 2; default 0.9. Lobe size.
flow0 to 1; default 0.5. Domain warp: 0 round pools, 1 pulled liquid.
crease0 to 1; default 0.6. Thin fold lines hugging the lobes’ edges.
depth0.2 to 2; default 1. Relief height and slope color shifts.
iridescence0 to 1; default 0.6. Amount of color change across the slopes; 0 keeps a lit gradient.
light0 to 360; default 40. Light direction, in degrees.
grain0 to 0.3; default 0.04. Film grain strength.

burst

ParameterRange, default, and behavior
rays0 to 1; default 0.45. Ray count: 8 broad rays at 0, 80 needles at 1.
sharp0 to 1; default 0.6. Ray contrast: 0 soft sectors, 1 hard-edged rays.
glow0 to 1; default 0.7. Center brightness, from dark to bright.
twist0 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.
grain0 to 0.3; default 0.14. Film grain strength.

glint

ParameterRange, default, and behavior
size0.01 to 0.06; default 0.03. Shard length, in frame heights.
density0.2 to 1; default 0.6. How many cells hold a shard.
bend0 to 1; default 0.5. How far the current arcs across the frame.
angle0 to 360; default 10. Direction of the current.
speed0.3 to 2; default 1. Streaming speed when not looping; a loop always travels one pattern period.
grain0 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

ParameterRange, default, and behavior
size2 to 160; default 13. Pixel cell size.
levels0 to 16; default 0. Color levels per channel; 0 preserves full color.
gap0 to 0.4; default 0.08. Grid-line width relative to cell size.
gapColorHex color; default #000000. Grid-line color.
blendBlend mode; default normal.
opacity0 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.

ParameterRange, default, and behavior
patternbayer2, bayer4, bayer8, blueNoise; default bayer8.
size1 to 16; default 3. Dithering cell size.
levels2 to 8; default 4. Tone or palette levels.
bias-0.5 to 0.5; default 0. Tone offset before quantization.
linearBoolean; default true. Threshold in linear light.
shimmer0 to 12; default 0. Pattern changes per second.
colorModesource, duotone, palette; default source.
inkHex color; default #000000. Duotone ink color.
paperHex color; default #ffffff. Duotone paper color.
invertBoolean; default false. Reverse the tone scale.
blendBlend mode; default softLight.
opacity0 to 1; default 0.6. Effect opacity.

Halftone

ParameterRange, default, and behavior
groundimage, paper; default image. Render marks over the image or on a flat background.
blendBlend mode; default screen.
opacity0 to 1; default 1. Mark opacity.
blur0 to 40; default 0. Backdrop blur with image ground.
gridsquare, hex; default square. Dot arrangement.
shapedot, line, square; default square. square at 45 degrees creates diamonds.
size6 to 160; default 20. Screen pitch.
angle0 to 180; default 45. Screen rotation in degrees.
radius0.2 to 1.5; default 0.75. Relative mark size.
softness0 to 1; default 0.1. Edge softness.
stylefilled, uniform; default filled. Tone-sized or fixed-size marks.
exposure-1 to 1; default 0. Tone adjustment for mark sizing.
contrast0 to 2; default 1.15. Tone contrast for mark sizing.
density0 to 1; default 1. Fraction of cells containing marks.
colorModesource, duotone, palette; default source.
inkHex color; default #111111. Single ink color in duotone mode.
paperHex color; default #f4f1ea. Background color when ground is paper.
invertBoolean; default false. Reverse tone response.

ASCII

ParameterRange, default, and behavior
groundimage, paper; default image. Characters over image or paper.
blendBlend mode; default colorDodge.
opacity0 to 1; default 1. Character opacity.
blur0 to 40; default 0. Backdrop blur with image ground.
charsetstandard, dense, blocks, minimal, binary, katakana; default standard.
size8 to 96; default 10. Character height.
smoothBoolean; default true. Dither between adjacent characters.
cycle0 to 12; default 2. Character rerolls per second.
cycleAmount0 to 1; default 0.2. Fraction of characters that reroll.
stylefilled, uniform; default filled. Tone-sized or fixed-size characters.
exposure-1 to 1; default 0. Tone adjustment for character selection.
contrast0 to 2; default 1.2. Tone contrast.
density0 to 1; default 1. Fraction of cells with characters.
colorModesource, duotone, palette; default source.
inkHex color; default #e8ffe8. Text color in duotone mode.
paperHex color; default #000000. Background when ground is paper.
invertBoolean; default false. Reverse tone response.

Tint

ParameterRange, default, and behavior
modeduotone, palette; default duotone. Map brightness through two colors or the full palette.
darkHex color; default #1b1a4a. Shadow color in duotone mode.
lightHex color; default #f2c6a0. Highlight color in duotone mode.
amount0 to 1; default 1. Recolor strength.

Alternatives and Related Resources

You Might Be Interested In:


Leave a Reply