Advanced Usage
Deep dive into Mesh Gradient configuration, performance tuning, and production patterns.
In this section, we will cover some advanced usage of the library.
Canvas layout & HiDPI
The gradient measures your <canvas> with getBoundingClientRect() and sizes the WebGL framebuffer using that logical CSS size times pixelRatio (typically device pixel ratio, capped).
Always give the canvas a real layout footprint in CSS (fixed width/height, utility classes, flex/grid parent, etc.). On each resize the renderer sets inline width/height in CSS pixels so the backing store can be larger than the layout box without the element exploding in size — avoiding a destructive feedback loop between layout and ResizeObserver.
Prefer explicit sizing in your markup or styles; do not rely on default canvas dimensions alone in production layouts.
Instance methods
Methods which are available on the MeshGradient instance. API reference
init(element, options?)
Initializes the gradient. Requires the HTML canvas element to be passed as the first argument. Supports optional smooth appearance animation.
const gradient = new MeshGradient();
// Alternatively, you can pass the element as a string selector
const canvas = document.getElementById('gradient');
gradient.init(canvas, {
appearance: 'smooth', // default is 'smooth'
appearanceDuration: 300, // default is 300ms
});update(options?)
Updates the initialized gradient with the new options. Supports fade transition between the old and new options.
const gradient = new MeshGradient();
gradient.init('#gradient'); // Initialize the gradient first
gradient.update({
colors: ["#8a519a", "#6101c1", "#e24097", "#f3121d"],
transition: true, // default is true
transitionDuration: 300, // default is 300ms
});destroy()
Destroys the initialized gradient instance. Helps to free up memory and prevent memory leaks (especially in SPA applications).
const gradient = new MeshGradient();
gradient.init('#gradient'); // Initialize the gradient
gradient.destroy();pause() and play()
Animation playback control methods.
const gradient = new MeshGradient();
gradient.pause(); // Pauses the gradient animation
gradient.play(); // Resumes the gradient animationGradient options
All available options for the gradient.
You can generate the code for the options using the Playground.
colors
Array of colors. Must be an array of strings in the format #RRGGBB or #RGB. If not provided, the gradient will use the random colors on each initialization or update.
const options: MeshGradientOptions = {
colors: ['#8a519a', '#6101c1', '#e24097', '#f3121d'],
};seed
Seed (initial pattern) for the gradient. If not provided, the gradient will use the random seed on each initialization or update.
const options: MeshGradientOptions = {
seed: 1,
};animationSpeed
Animation speed multiplier. Higher values make animation faster, lower values make it slower. Performance remains constant regardless of speed value.
const options: MeshGradientOptions = {
animationSpeed: 1.5, // 1.5x faster than default
};frequency
Frequency for the gradient. Can be a single number or an object with x, y, and delta properties.
const options: MeshGradientOptions = {
// Single number
frequency: 0.0002,
// Or object with specific values
frequency: {
x: 0.00014,
y: 0.00029,
delta: 0.0001
},
};The delta field is added to y in the internal noiseFreq uniform (second frequency component). Omit it to leave that offset at 0.
activeColors
Active colors for the gradient. Controls which of the 4 colors are visible.
const options: MeshGradientOptions = {
activeColors: {
1: true, // First color is active
2: false, // Second color is inactive
3: true, // Third color is active
4: true, // Fourth color is active
},
};isStatic
Static mode. If true, the gradient will not animate. Optimized for performance.
const options: MeshGradientOptions = {
isStatic: true, // No animation, better performance
};pauseOnOutsideViewport
Auto pause when gradient goes out of viewport. Powered by Intersection Observer API.
const options: MeshGradientOptions = {
pauseOnOutsideViewport: true, // Pause when not visible
};pauseObserverOptions
Intersection observer options for pause on outside viewport option.
const options: MeshGradientOptions = {
pauseObserverOptions: {
root: document.body,
rootMargin: '0px',
threshold: 0.05
},
};resizeDelay
Resize delay after canvas is resized. Helps to optimize performance.
const options: MeshGradientOptions = {
resizeDelay: 300, // 300ms delay after resize
};cssVariablesFallback
Fallback to CSS variables instead of random colors if colors are not provided.
const options: MeshGradientOptions = {
cssVariablesFallback: true,
};:root {
--mesh-gradient-color-1: #ff0080;
--mesh-gradient-color-2: #0080ff;
--mesh-gradient-color-3: #80ff00;
--mesh-gradient-color-4: #ff8000;
}Scene & mesh
Optional tuning for the generated plane mesh and drawing mode:
const options: MeshGradientOptions = {
density: [0.06, 0.16], // scales segment counts with CSS size
wireframe: false,
zoom: 1,
rotation: 0,
presetName: 'my-preset',
};pixelRatio
Scale factor for the WebGL backing store (defaults to a capped device pixel ratio in the browser). Logical mesh size still follows CSS layout; only the internal buffer resolution changes.
const options: MeshGradientOptions = {
pixelRatio: 1.5,
};maxSegments
Upper bound per axis on mesh segments after density math — useful on very large layouts.
darkenTop
Boolean to enable the “darken top” shading pass (prefer over legacy data-js-darken-top on the canvas when possible).
callbacks
Hooks for lifecycle integration:
const options: MeshGradientOptions = {
callbacks: {
onReady: () => {},
onError: (error) => console.error(error),
onResize: ({ cssWidth, cssHeight }) => {},
},
};webglContextAttributes
Merged into HTMLCanvasElement.getContext for WebGL contexts (for example { alpha: false }, { preserveDrawingBuffer: true }).
targetFps
Caps time updates to a desired frame budget (helps steady pacing vs. display refresh).
reducedMotion
Respects prefers-reduced-motion when 'auto' (default), or force static rendering with 'force-static' / 'ignore'.
allowDocumentCanvasFallback
When true, if init(selector) resolves no element, falls back to document.querySelector('canvas'). Off by default — enable only for legacy pages.
useLegacyLoadedClassBehavior
When false, skips adding the historical isLoaded class to the canvas and its parent. Prefer callbacks.onReady for new code.
Init-only: appearance & appearanceDuration
These live on MeshGradientInitOptions and apply to .init() only (see API for types). Control the initial fade-in (appearance: 'smooth' | 'default').
Update-only: transition & transitionDuration
Part of MeshGradientUpdateOptions for .update(): cross-fade between previous and new configuration (enabled by default; set transition: false for a hot path without full re-init).
See the full field list in the API reference.