Skip to content

CSS Variables & Canvas Export

CSS variable utilities

ts
import { extractGradientVariables, resolveGradientVariables } from 'css-magic-gradient'

const gradient = 'linear-gradient(var(--start, #ff0000), var(--end))'

// Extract all CSS custom property names
extractGradientVariables(gradient)
// → ['--start', '--end']

// Substitute variables from a map; falls back to inline fallback or preserves var()
resolveGradientVariables(gradient, { '--end': '#0000ff' })
// → 'linear-gradient(#ff0000, #0000ff)'

Canvas & image export

Render gradients to canvas or image data — useful for Open Graph image generation, canvas-based UIs, or server-side rendering with a canvas library (e.g. the canvas npm package).

gradientToCanvasGradient

Creates a CanvasGradient object from the given parameters and applies all color stops.

ts
import { gradientToCanvasGradient } from 'css-magic-gradient'

const gradient = gradientToCanvasGradient(
  {
    type: 'linear',
    stops: [
      { color: '#ff9a3c', offset: 0 },
      { color: '#c0357a', offset: 1 },
    ],
  },
  ctx,
)

ctx.fillStyle = gradient
ctx.fillRect(0, 0, canvas.width, canvas.height)

Gradient types:

ts
// Linear (x0,y0) → (x1,y1); defaults: left-to-right across canvas
{ type: 'linear', stops, x0?, y0?, x1?, y1? }

// Radial — two circles; defaults: concentric circles centered in canvas
{ type: 'radial', stops, x0?, y0?, r0?, x1?, y1?, r1? }

// Conic — startAngle in radians; defaults: center of canvas, 0 rad
{ type: 'conic', stops, startAngle?, x?, y? }

gradientToImageData

Renders the gradient into an ImageData object of the given size.

ts
import { gradientToImageData } from 'css-magic-gradient'

const imageData = gradientToImageData(
  {
    type: 'radial',
    stops: [
      { color: '#ffffff', offset: 0 },
      { color: '#3498db', offset: 1 },
    ],
  },
  800,
  600,
)

gradientToDataURL

Renders the gradient as a PNG data URL (e.g. for <img src> or CSS background).

ts
import { gradientToDataURL } from 'css-magic-gradient'

const dataUrl = gradientToDataURL(
  {
    type: 'linear',
    stops: [
      { color: '#ff9a3c', offset: 0 },
      { color: '#c0357a', offset: 1 },
    ],
  },
  400,
  200,
)
// → 'data:image/png;base64,…'

Note: Canvas functions require a browser or a server-side canvas implementation. In environments without document or OffscreenCanvas, they throw a descriptive error.