@tool3/svgfx
v0.1.0
Published
Post-processing effects for any SVG. Scanlines, bloom, glitch, halftone and more — in, out, still an SVG.
Maintainers
Readme
svgfx
Post-processing effects for any SVG. Give it an SVG, get back an SVG — now with scanlines, bloom, glitch, halftone, duotone or a dozen other looks baked in.
import { svgfx, scanlines, bloom } from '@tool3/svgfx'
const output = svgfx(input, [bloom({ radius: 6 }), scanlines({ gap: 3 })])- Vector in, vector out. No canvas, no rasterizing, no
<image>payloads. The result is a real SVG that still scales, still has your paths in it, and still opens in a design tool. - Runs anywhere. Zero runtime dependencies and no DOM. Node, Bun, Deno, edge functions, build scripts, browsers.
- Deterministic. Same input and settings produce byte-identical output, so it drops into a build pipeline and a snapshot test without surprises.
- 14 KB gzipped, fully tree-shakeable. Import one effect, ship one effect.
- Self-contained motion. Opt into
animateand the output loops on its own — inside an<img>tag, with no JavaScript attached.
Install
npm install @tool3/svgfxQuick start
import { readFileSync, writeFileSync } from 'node:fs'
import { svgfx, crt } from '@tool3/svgfx'
const source = readFileSync('logo.svg', 'utf8')
writeFileSync('logo-crt.svg', svgfx(source, [crt()]))Effects are applied in order, exactly as you would stack them in an editor:
import { svgfx, duotone, halftone, grain } from '@tool3/svgfx'
const poster = svgfx(source, [
duotone({ shadow: '#111d4a', highlight: '#ff6b6b' }),
halftone({ size: 5, angle: 15 }),
grain({ amount: 0.4 }),
])API
svgfx(source, effects?, settings?)
Takes an SVG string, returns an SVG string.
const output = svgfx(source, [bloom()], { seed: 'hero', format: 'pretty' })createPipeline(effects, settings?)
A reusable, named stack of effects. Build it once, apply it to many files.
import { createPipeline, duotone, grain } from '@tool3/svgfx'
const brand = createPipeline([duotone({ shadow: '#001427' }), grain()], { seed: 'brand' })
icons.map(brand.apply)compose(name, effects)
Collapses several effects into one, so a house style becomes a single effect that can be passed around, exported, and stacked with others.
export const houseStyle = compose('house-style', [contrast({ amount: 1.1 }), grain(), vignette()])toDataUri(svg, options?)
element.style.backgroundImage = `url("${toDataUri(svgfx(source, [crt()]))}")`URI-encoded by default (smaller and readable); pass { base64: true } if you need it.
Settings
| Setting | Default | What it does |
| --------- | ------------ | ------------ |
| seed | 'svgfx' | Seeds every random decision. Change it to reroll a glitch or a grain field; keep it to get the same output forever. |
| prefix | 'svgfx' | Prefix for every generated id and class. |
| scope | auto | Id namespace. Derived from the source, seed and effects so several svgfx outputs can be inlined in one page without colliding. Set it yourself for stable, readable ids. |
| animate | true | Global switch for motion. false strips animation from every effect that asked for it — useful for print, PDF or snapshot tests. |
| format | 'preserve' | 'preserve' keeps the input's whitespace, 'pretty' re-indents, 'minify' drops comments and layout whitespace. |
Effects
Light
| Effect | Options |
| ------ | ------- |
| blur | radius 3, axis 'both' \| 'horizontal' \| 'vertical' |
| bloom | radius 8, threshold 0.55, intensity 1.1 |
| glow | color '#ffffff', radius 6, spread 0, intensity 1 |
| shadow | x 3, y 4, blur 4, color '#000000', opacity 0.4 |
Colour
| Effect | Options |
| ------ | ------- |
| grayscale | amount 1 |
| saturate | amount 1.4 |
| hueRotate | angle 90 |
| invert | amount 1 |
| brightness | amount 1.15 |
| contrast | amount 1.25 |
| sepia | amount 1 |
| fade | amount 0.7 |
| posterize | steps 5, includeAlpha false |
| threshold | level 0.5, dark '#000000', light '#ffffff' |
| duotone | shadow '#12263a', highlight '#f4d35e', mix 1 |
| tint | color '#ff2d55', amount 0.45 |
Texture and distortion
| Effect | Options |
| ------ | ------- |
| grain | amount 0.32, size 0.8, monochrome true, blend 'overlay', animate false, speed 12 |
| scanlines | gap 4, thickness 1.5, opacity 0.28, color '#000000', angle 0, blend 'multiply', animate false, speed 6 |
| chromaticAberration | offset 2, angle 0 |
| glitch | intensity 0.5, slices 7, colorShift true, animate false, speed 1 |
| pixelate | size 8 |
| halftone | size 6, angle 45, levels 4, color '#111111', background '#ffffff', keepSource false |
| vignette | amount 0.65, radius 0.6, softness 0.7, color '#000000' |
| outline | width 2, color '#000000', position 'outside' \| 'inside' |
| wave | amplitude 12, frequency 0.02, octaves 2, animate false, speed 0.15 |
| emboss | depth 1, angle 135, desaturate true |
| sharpen | amount 1 |
Every option is optional. bloom() on its own is tuned to look right.
Presets
Finished looks, each one a compose of the effects above.
import { crt, vhs, riso, xerox, neon, film, newsprint, cyberpunk } from '@tool3/svgfx'
svgfx(source, [crt({ animate: true })])
svgfx(source, [riso({ shadow: '#2b3a67', highlight: '#ff5a5f' })])
svgfx(source, [neon({ color: '#4cc9f0' })])| Preset | Look |
| ------ | ---- |
| crt | Phosphor glow, scanlines, colour fringing, vignette |
| vhs | Tape wobble, heavy fringing, rolling lines, noise |
| riso | Two-colour risograph with paper grain |
| xerox | Blown-out photocopy |
| neon | Saturated sign glow |
| film | Halation, grain and a soft vignette |
| newsprint | Halftone dots on off-white stock |
| cyberpunk | Sliced, shifted, bloomed, scanned |
Examples
Every effect and preset ships as a runnable TypeScript script under
examples/ — the linked name opens the code, which shows the exact options
used. Each script writes a before/after pair into examples/svgs, and runs as-is with
no build step.
npm run examples # render all 37
node examples/effects/halftone.ts # or just one
npm run gallery # side-by-side overview pageEffect examples
| Example | Before | After |
| ------- | ------ | ----- |
| blur | | |
| bloom | | |
| glow | | |
| shadow | | |
| grayscale | | |
| saturate | | |
| hue-rotate | | |
| invert | | |
| brightness | | |
| contrast | | |
| sepia | | |
| fade | | |
| posterize | | |
| threshold | | |
| duotone | | |
| tint | | |
| grain | | |
| scanlines | | |
| chromatic-aberration | | |
| glitch | | |
| pixelate | | |
| halftone | | |
| vignette | | |
| outline | | |
| wave | | |
| emboss | | |
| sharpen | | |
Preset examples
| Example | Before | After |
| ------- | ------ | ----- |
| crt | | |
| cyberpunk | | |
| film | | |
| neon | | |
| newsprint | | |
| riso | | |
| vhs | | |
| xerox | | |
Animated examples
Applied to examples/sources/motion.svg, which loops on its own in plain SMIL. Both
columns are playing: the source keeps its motion, and the second adds svgfx's on top.
| Example | Before | After |
| ------- | ------ | ----- |
| motion-crt | | |
| motion-layered | | |
Motion
Effects with an animate option emit their own <animate> elements and CSS
keyframes into the output. Nothing is attached at runtime, so the file animates on its
own — as an <img src>, a CSS background-image, or inlined in a page.
const banner = svgfx(source, [scanlines({ animate: true, speed: 4 }), grain({ animate: true })])Turn all of it off in one place when you need a still frame:
svgfx(source, [crt({ animate: true })], { animate: false })Animated SVGs go in, animated SVGs come out
An input that already animates keeps animating. <animate>, <animateTransform>,
<set> and CSS keyframes in the source are carried through untouched — the artwork is
wrapped, never rewritten — and the effect is applied to every frame as it plays.
const styled = svgfx(spinner, [crt()])Your motion and svgfx's motion compose, in one self-contained file:
const banner = svgfx(spinner, [
bloom({ radius: 6, threshold: 0.45 }),
glitch({ intensity: 0.6, animate: true }),
scanlines({ gap: 3, animate: true }),
grain({ amount: 0.35, animate: true }),
])Both are in the animated examples above, rendered from a looping source.
Writing your own effect
An effect is a name plus a list of stages, and there are two kinds of stage. A
filter stage contributes SVG filter primitives; consecutive filter stages are merged
into a single <filter> element automatically. A layer stage restructures the
artwork — wrapping it, duplicating it, or laying something over it.
import { defineEffect, filterStage, series } from '@tool3/svgfx'
export const solarize = ({ level = 0.5 } = {}) =>
defineEffect('solarize', [
filterStage(
(io) => ({
primitives: series(io, [
{ name: 'feComponentTransfer', children: [/* ... */] },
{ name: 'feColorMatrix', attributes: { type: 'saturate', values: 1.4 } },
]),
}),
{ margin: 10 },
),
])series wires in and result down the chain for you. Reach for io.input and
io.output directly when an effect needs to branch — bloom and chromaticAberration
are worked examples.
A layer stage receives the current artwork and returns the new artwork, plus anything
it needs in <defs> or in a <style> block:
import { cover, defineEffect, group, layerStage } from '@tool3/svgfx'
export const wash = ({ color = '#ff2d55' } = {}) =>
defineEffect('wash', [
layerStage((content, context) => ({
content: group([content, cover(context.viewport, { fill: color, opacity: 0.2 })]),
})),
])The context handed to every stage carries the resolved viewport, a seeded
random(key) and range(min, max, key), and uid(hint) for collision-free ids.
Randomness is keyed rather than sequential, which is what keeps output byte-stable.
Recipes
React
import { useMemo } from 'react'
import { svgfx, crt } from '@tool3/svgfx'
const Poster = ({ svg }: { svg: string }) => {
const html = useMemo(() => svgfx(svg, [crt()]), [svg])
return <div dangerouslySetInnerHTML={{ __html: html }} />
}Build step
import { readdirSync, readFileSync, writeFileSync } from 'node:fs'
import { createPipeline, duotone, grain } from '@tool3/svgfx'
const brand = createPipeline([duotone(), grain()], { format: 'minify' })
readdirSync('icons').forEach((file) => {
writeFileSync(`dist/${file}`, brand.apply(readFileSync(`icons/${file}`, 'utf8')))
})In the browser
const styled = svgfx(await fetch('/logo.svg').then((response) => response.text()), [neon()])
document.querySelector('#logo')!.innerHTML = styledNotes
- Browser support. Everything is standard SVG 1.1 filters plus
mix-blend-mode, which covers every current browser.pixelateleans onfeTileand renders slightly differently in Safari. - Resolution. Browsers rasterize filter regions at the SVG's own coordinate scale.
If a filtered SVG is displayed much larger than its
viewBox, the filtered parts can soften. Author at the size you intend to display, or scale theviewBoxup. - Ids. Generated ids are namespaced per document, so several svgfx outputs can live
in one page. Pass
scopeif you want to name that namespace yourself. - Structure. Non-rendering nodes —
<title>,<desc>,<defs>,<style>,<metadata>— are left where they are. Only the drawn content is wrapped.
Development
npm test # 89 tests, no test framework needed
npm run typecheck
npm run build # ESM + CJS + types
npm run examples # renders examples/svgs
npm run gallery # renders examples/gallery.htmlThe repo is TypeScript end to end — source, tests, examples and build scripts. Nothing is written in JavaScript, and Node runs all of it directly.
License
MIT © Tal Hayut
