heerich.js A tiny engine for 3D voxel scenes rendered to SVG
heerich.js is a minimalist JavaScript engine that constructs 3D voxel compositions and distills them into pristine SVG. By extruding volumes, carving negative space, and applying boolean operations, you wield a programmatic chisel—projecting complex spatial arrangements into a flat, resolution-independent vector canvas.
While SVG trades raw frame-rates for architectural elegance, its integration with the DOM is profound. The resulting geometry sits natively within the browser, inviting manipulation through CSS and uncompromised infinite scaling. The output is not an ephemeral pixel buffer, but semantic, stylable, and enduring markup.
The visual language draws deep inspiration from the geometric rigor of Erwin Heerich† (1922–2004) — exploring stacked topologies, deliberate subtractions, and the quiet tension that exists between solid mass and absolute void.
This page serves as both a technical manual and an interactive gallery. Engage with the examples below to comprehend the mechanics of the engine one primitive at a time.
Creating an engine
A Heerich instance holds a 3D grid of voxels and knows
how to project them into 2D SVG. You initialize one by providing grid
dimensions, a rendering tile size in pixels, and an optional baseline
style applied universally across the active sequence.
import { Heerich } from './src/heerich.js'
const heerich = new Heerich({
camera: { type: 'oblique', angle: 315, distance: 25 },
style: { fill: '#ddd', stroke: '#333', strokeWidth: 0.5 },
gap: 0.05 // uniform spacing between voxels (0–0.5)
})
All parameters are optional — new Heerich() works with
sensible defaults. Call heerich.toSVG() to get an SVG
string you can drop into the DOM.
The SVG is automatically centered — the engine computes the exact
bounding box of all visible geometry and sets the
viewBox to fit it, with optional padding. No manual
positioning needed, even when shapes extend into negative coordinates.
// Auto-centered with padding
document.body.innerHTML = heerich.toSVG({ padding: 30 })
// Access raw bounds if you need them
const { x, y, w, h } = heerich.getBounds()
That's what you want when you show a shape from one perspective. If
your animation or interaction turns the camera, the outline changes
every frame, so the shape rescales and wiggles.
getFitFrame() covers that: it measures one frame that
holds the shape at every camera setting, and the shape turns around a
fixed point in the middle of it.
const frame = heerich.getFitFrame()
heerich.setCamera({ type: 'isometric', angle })
heerich.updateSVG(svg, { fit: frame })
Boxes
The most fundamental primitive is a box — a rectangular volume
anchored by a corner position and dimensions. You can
also use center instead — the engine offsets by half
the size automatically.
heerich.applyGeometry({
type: 'box',
position: [0, 0, 0],
size: [6, 4, 3]
})
Drag the sliders below — the engine clears and rebuilds the scene on
every frame. Because getFaces() utilizes a dirty-flag
cache, calculating rapid structural changes remains highly
efficient.
Spheres
applyGeometry({ type: 'sphere' }) plots a rounded
volume using an internal distance check. You can use
position (bounding-box corner) instead of
center, and size instead of
radius. Fractional offsets like .5 for
both radius and center (e.g., center: 4, radius:
4) tend to produce the cleanest symmetrical forms on
integer grids.
heerich.applyGeometry({
type: 'sphere',
center: [4.5, 4.5, 4.5],
radius: 4.5
})
Conversely, removeGeometry({ type: 'sphere' }) carves a
hollow void using the exact same parameters. Layer a sphere
subtraction into a solid box to effortlessly create arched doorways
or dome cutouts.
Lines
applyGeometry({ type: 'line' }) plots a continuous
voxelized path between two spatial coordinates. Lines are the only
shape that uses from/to instead of the
usual position/center + size.
You can thicken the stroke via radius, and alter its
joint geometry via shape — choosing either
'rounded' (a sequence of overlapping spheres) or
'square' (overlapping cubes).
heerich.applyGeometry({
type: 'line', from: [0, 0, 0], to: [8, 8, 8],
radius: 1.5, shape: 'rounded'
})
Custom shapes
applyGeometry({ type: 'fill' }) is the engine's
architectural bedrock — allowing you to define arbitrary
geometry as an evaluation function over
(x, y, z)
coordinates. You can specify the area with bounds, or
use position/center +
size like other shapes. Under the hood, boxes, spheres,
and lines are merely convenient wrappers around this core method.
heerich.applyGeometry({
type: 'fill', bounds: [[0, 0, 0], [s, s, s]],
test: (x, y, z) => {
const c = Math.ceil(s / 4)
const nearEdge = [x, y, z].filter(
v => v < c || v >= s - c
).length
return nearEdge < 3
}
})
The test method evaluates every coordinate within the
specified bounds — returning
true spawns a voxel. All standard properties (like
style, scale, or mode)
continue to apply.
Alignment
position always anchors to the minimum corner of the
shape's bounding box. To align objects of different sizes on a
shared surface, offset the smaller one manually.
const big = [6, 6, 6], small = [2, 2, 2]
// Align max corners (tops flush)
const max = big.map((b, i) => b - small[i])
// Center (works perfectly when difference is even)
const center = big.map((b, i) => (b - small[i]) / 2)
One subtraction per axis — the engine stays minimal and you stay in control. For pixel-perfect centering on an integer grid, use even-numbered size differences.
Boolean operations
Every shape primitive accepts a mode property dictating
how it weaves into the existing voxel grid:
- union — add voxels (default)
- subtract — remove voxels
- intersect — keep only the overlap
- exclude — XOR, toggle each voxel
heerich.applyGeometry({
type: 'box',
position: [0, 0, 0],
size: 6
})
// Carve a sphere out of the box
heerich.applyGeometry({
type: 'sphere', center: [3, 3, 3], radius: 3,
mode: 'subtract'
})
// Keep only where box and sphere overlap
heerich.applyGeometry({
type: 'sphere', center: [3, 3, 3], radius: 3,
mode: 'intersect'
})
removeGeometry() is a shortcut for
mode: 'subtract'. addGeometry() is a
shortcut for mode: 'union'.
Rotation
Every primitive accepts a rotate configuration mapped
to precise 90° increments. Simply specify a rotation
axis and the count of quarter-turns. By
default, shapes pivot around their local center, but arbitrary
custom origins are seamlessly supported.
// Build one arm, rotate a copy to make an L
heerich.applyGeometry({
type: 'box',
position: [0, 0, 0],
size: [2, 8, 2]
})
heerich.applyGeometry({
type: 'box', position: [0, 0, 0], size: [2, 8, 2],
rotate: { axis: 'z', turns: 1 }
})
// Rotate all existing voxels in place
heerich.rotate({ axis: 'y', turns: 2 })
This dramatically simplifies creating symmetrical structures: construct one facet, then repeatedly rotate clones around a central pivot. (For example, the Kreuzplastik in the gallery below derives entirely from a single arm sequence rotated into a cross.)
Smooth solids
By default, every 1×1×1 unit renders its own distinct
stroke. To fuse a shape into a single, visually seamless solid,
simply assign the
stroke the exact same color as the fill,
effectively rendering the internal grid geometry invisible.
heerich.applyGeometry({
type: 'box', position: [0, 0, 0], size: 4,
style: {
default: { fill: '#0e0e0e', stroke: '#0e0e0e' }
}
})
Untouched structural voxels retain their outlines, naturally producing a crisp contrast between smooth, monolithic volumes and articulated grids.
Styling faces
The engine tracks styles on a strict per-face basis:
top, front, left,
right, bottom, and back,
alongside a default fallback. The axis shorthands
x (left + right), y (top + bottom) and
z (front + back) paint both faces of an axis at once —
an explicit face still overrides them. You can inject these styles
during shape creation, or explicitly overwrite existing regions
later using applyStyle().
heerich.applyGeometry({
type: 'box', position: [0, 0, 0], size: 4,
style: {
default: { fill: '#eee', stroke: '#333' },
x: { fill: '#66ff66' }, // left + right
y: { fill: '#ff6666' }, // top + bottom
z: { fill: '#6666ff' } // front + back
}
})
Crucially, applyStyle() applies localized 'paint' to
existing
geometry without fabricating new voxels — ideal for shading specific
cross-sections after the overall volume is finalized.
Using decals
Register named <path> elements authored in a
0–1 unit coordinate space. Reference them by name in
any face style — the engine warps every path coordinate via bilinear
interpolation onto the projected face quad, so decals deform
correctly with both oblique and perspective cameras.
scene.defineDecal('cross', {
content: `<path
d="M0 0 L1 1 M1 0 L0 1"
stroke="#333"
fill="none"
vector-effect="non-scaling-stroke"
/>`
});
scene.addGeometry({
type: 'box', position: [0, 0, 0], size: 1,
style: {
top: { fill: '#fff', decal: 'cross' }
}
});
All path commands are supported, both absolute (M, L, H, V, C, S, Q,
T, A, Z) and relative (m, l, h, v, c, s, q, t, a, z) — arcs are
automatically converted to cubic beziers before warping. Only
<path> elements are supported for now; other
shapes must be converted to paths first.
Hatching
Add a hatch object to any face style to overlay
parallel lines. The lines are clipped precisely to the face polygon
— including partially-occluded faces when occlusion culling is
active.
heerich.addGeometry({
type: 'box', position: [0, 0, 0], size: 4,
style: {
top: {
fill: '#eee',
hatch: { angle: 45, period: 5 }
},
front: {
fill: '#ccc',
hatch: { angle: 90, period: 8, stroke: '#666' }
},
right: {
fill: '#ddd',
hatch: { angle: 0, period: 6, strokeWidth: 2 }
}
}
});
Options: angle (degrees, default 45),
period (px between lines, default 5),
stroke (color, defaults to currentColor),
strokeWidth (default 1), and
opacity. The same callback API as other styles applies
— pass a function to vary hatching per-voxel.
SVG style properties
Internal style objects map perfectly to native SVG attributes. If
SVG natively understands a property, you can pass it directly. This
unleashes the full rendering spec — enabling opacity,
dotted edges via strokeDasharray, rounded
strokeLinecap margins, or any other
presentation attribute.
heerich.applyGeometry({
type: 'box', position: [0, 0, 0], size: 5,
style: {
default: {
fill: 'var(--fill)',
stroke: 'var(--stroke-c)',
strokeWidth: 'var(--stroke-w)',
opacity: 0.6,
strokeDasharray: '4 2'
}
}
})
Because style values resolve as strings, you can seamlessly pass
native CSS
var() references. That strategy powers the interactive
controls across this documentation: the engine natively outputs
var(--fill), and the browser resolves the cascade
against document state in real time.
Functional styles
Instead of static objects, styles can be assigned as pure computing
functions tracking over (x, y, z) parameters.
This effortlessly powers cascading gradients, periodic patterns, or
geometry-dependent shading rules — bypassing the need to iterate
through individual voxels manually.
heerich.applyGeometry({
type: 'box', position: [0, 0, 0], size: 8,
style: {
default: (x, y, z) => {
const L = 0.4 + (y / 8) * 0.5
const C = 0.05 + (z / 8) * 0.2
const H = (x / 8) * 360
return {
fill: `oklch(${L} ${C} ${H})`,
stroke: `oklch(${L - 0.12} ${C} ${H})`
}
}
}
})
These callbacks are invoked exactly once at voxel creation. Individual faces can possess their own isolated functions — letting you freely cross-pollinate static hues with calculated spectral shifts.
Voxel scaling
Every single voxel supports an internal scale — an
[x, y, z] envelope mapped from 0 to 1 that collapses
the volume along internal axes. Scaled geometry automatically
triggers non-opaque rendering, correctly preserving visibility for
occluded geometry layered behind it.
// Static — same scale for every voxel
heerich.applyGeometry({
type: 'box', position: [0, 0, 0],
size: 1,
scale: [1, 0.5, 1],
scaleOrigin: [0.5, 1, 0.5]
})
// Functional — scale varies by position
heerich.applyGeometry({
type: 'box', position: [0, 0, 0],
size: 4,
scale: (x, y, z) => [1, 1 - y * 0.2, 1],
scaleOrigin: [0.5, 1, 0.5]
})
The scaleOrigin dictates the spatial pivot for this
scaling inside the 1×1×1 unit block — for example,
[0.5, 1, 0.5]
anchors geometry strictly to the bottom-center, creating natural
staircase topologies. As with styles, both vectors seamlessly accept
functional callbacks for dynamic parameter shifting.
Functional scale
As implied, evaluating scale as an
(x, y, z) function empowers you to calculate
spatial decay based exclusively on local position. You can instantly
engineer complex tapers, rounded organic falloffs, or gracefully
staggered architectural elements without stepping outside a single
generative routine.
heerich.applyGeometry({
type: 'box', position: [0, 0, 0], size: [s, s, s],
scale: (x, y, z) => {
const t = 1 - y / s
const f = 1 - t * taper
return [f, 1, f]
},
scaleOrigin: [0.5, 1, 0.5]
})
Return null from the function to leave a voxel at full
size.
Slopes
Pass slope to turn voxels into wedges. A ramp names the
direction it rises toward: '+x', '-x',
'+z' or '-z'. The slanted face is styled
with the slope key and falls back to top.
heerich.applyGeometry({
type: 'box', position: [0, 2, 0], size: [1, 1, 3],
slope: '+x',
style: { slope: { fill: '#18191b' } }
})
Where two ramps meet, 'outer+x+z' caps the outside
corner and 'inner+x+z' fills the inside one, both
rising toward the two directions they name. 'tip' is a
pyramid peak. Prefix any of them with 'ceiling:' to
hang it upside down, for arches and brackets. As with
scale, a function picks the shape per voxel; return
null for a plain cube.
slope: (x, y, z) => {
const ex = x === lo ? '+x' : x === hi ? '-x' : ''
const ez = z === lo ? '+z' : z === hi ? '-z' : ''
if (ex && ez) return 'outer' + ex + ez
return ex || ez || null
}
Gentle slopes
A ramp can also start and end partway up the cell. Pass
{ side, from, to }: from is the height at
the open end, to the height at the wall, both as a
fraction of the cell. Cells that continue where the last one stopped
form one straight slope at any angle, one cell at a time.
// a 1:3 slope across three cells
for (let i = 0; i < 3; i++) heerich.applyGeometry({
type: 'box', position: [i, 0, 0], size: [1, 1, 3],
slope: { side: '+x', from: i / 3, to: (i + 1) / 3 }
})
{ side: '+x', from: 0.5, to: 1 } on its own is a half
slope on a raised block. Corners and tips take heights the same way,
so a hip roof keeps its angle all the way around. Prefix the side
with 'ceiling:' to hang it.
slope: { side: 'outer+x+z', from: 0.5, to: 1 }
Transparent voxels
Set opaque: false and the voxel itself remains visible,
but adjacent voxels treat it as empty space — forcing their inner
faces to be drawn. Combine this with a transparent fill to construct
wireframe cages, bounding volumes, or see-through sculptural guides
anchored cleanly over solid geometry.
// Wireframe cage over a solid core
heerich.applyGeometry({
type: 'box',
position: [1, 1, 1],
size: 3
})
heerich.applyGeometry({
type: 'box', position: [0, 0, 0], size: 5,
opaque: false,
style: { default: { fill: 'none' } }
})
Content voxels
You can embed pure SVG arbitrarily into volumetric cells by
injecting a literal
content string. The engine intercepts these strings,
seamlessly calculates their projected 2D location alongside other
faces, enforces a strict Z-level depth sort, and encases everything
cleanly inside an integrated <g> element.
heerich.applyGeometry({
type: 'box', position: [3, 0, 6], size: 1,
opaque: false,
content: `<text
font-family="Aboreto"
font-size="20"
text-anchor="middle"
dominant-baseline="central"
>A</text>`
})
Ensuring opaque: false explicitly directs neighboring
elements to render their intersection faces accurately. Otherwise,
neighbors would falsely assume a solid structure is blocking their
boundaries.
The content is wrapped in a <g> with
transform="translate(x, y) scale(s)" and CSS custom
properties you can use for sizing:
--x,--y— projected 2D position--z— original z coordinate-
--scale— perspective foreshortening (1 in oblique) --tile— tile size in pixels
Querying voxels
A robust set of internal methods query localized voxel boundaries. This is fundamental for evaluating complex procedural decorations, handling adjacency logic, or driving edge-aware shading passes.
// Color voxels by how exposed they are
for (const voxel of heerich) {
const n = heerich.getNeighbors(
[voxel.x, voxel.y, voxel.z]
)
const exposed = Object.values(n)
.filter(v => !v).length
// exposed = number of open faces (0–6)
}
The getNeighbors() query explicitly retrieves adjacent
solid geometry across the six cardinal planes. In the interactive
demo, individual cubes compute their overall exposure count —
completely encased shapes remain flat, while openly protruding forms
inherit high-contrast luminance.
heerich.hasVoxel([3, 4, 5]) // boolean
heerich.getVoxel([3, 4, 5]) // voxel data or null
for (const voxel of heerich) { ... }
// Serialization
const json = heerich.toJSON()
const copy = Heerich.fromJSON(json)
Finding voxels
findVoxels(predicate) scans the entire voxel map and
returns every voxel for which the predicate returns
true. The most common pattern is tagging groups at add
time with a meta id, then querying by that id later.
h.addGeometry({
type: 'box', position: [0, 4, 0], size: [7, 2, 7],
meta: { id: 'base' }
})
h.addGeometry({
type: 'box', position: [2, 1, 2], size: [3, 3, 3],
meta: { id: 'tower' }
})
// Retrieve a named group
const tower = h.findVoxels(v => v.meta?.id === 'tower')
// Restyle the result
for (const voxel of tower) {
h.applyStyle({
type: 'box', size: 1,
position: [voxel.x, voxel.y, voxel.z],
style: { default: { fill: '#e05252' } }
})
}
Predicates can match on any voxel property — coordinates, style
values, or arbitrary meta fields. The returned array
contains live references to the stored voxel objects.
// Find all voxels at ground level
h.findVoxels(v => v.y === 0)
// Find within a coordinate range
h.findVoxels(v => v.x >= 2 && v.x <= 5)
Position queries
findByPosition([x, y]) performs a 2D screen-space hit
test against all projected faces, returning the frontmost voxel and
face at that position. Coordinates are in the same pixel space as
getFaces() — when working from mouse events on a
rendered SVG, use the SVG element's coordinate transform to convert:
svgEl.addEventListener('mousemove', e => {
const pt = svgEl.createSVGPoint()
pt.x = e.clientX; pt.y = e.clientY
const { x, y } = pt.matrixTransform(
svgEl.getScreenCTM().inverse()
)
const hit = h.findByPosition([x, y])
if (hit) {
console.log(hit.voxel.x, hit.voxel.y, hit.voxel.z)
console.log(hit.face.type) // 'top', 'front', …
}
})
getVoxelInfo(posOrVoxel) returns the projected
centroid, 2D bounding box, and normalized position for any voxel —
given either a coordinate array or a voxel reference directly from
findByPosition:
const { center2D, bounds2D, normalizedCenter2D } =
h.getVoxelInfo(hit.voxel)
// center2D — { x, y } in pixels
// bounds2D — { x, y, w, h } of visible faces, in pixels
// normalizedCenter2D — { x, y }, 0–1 in scene bounds
Animation
The heerich.js architecture strictly separates state
from timing — animation is driven entirely externally, hooking
directly into your own requestAnimationFrame loop. By
interpolating a fractional value and redrawing the active sequence
per frame, standard voxel functions progressively toggle discrete
coordinates — yielding snappy, pixel-aligned deconstruction.
const holes = [
{ x: 1, y: 1, targetDepth: 5 },
{ x: 5, y: 2, targetDepth: 4 },
]
function frame(now) {
heerich.clear()
heerich.applyGeometry({ type: 'box', ...})
holes.forEach((h, i) => {
const t = ease(elapsed / duration)
heerich.removeGeometry({
type: 'box', position: [h.x, h.y, 0],
size: [3, 3, Math.round(t * h.targetDepth)]
})
})
heerich.updateSVG(svg)
if (!done) requestAnimationFrame(frame)
}
Each frame ends with updateSVG rather than
toSVG. It keeps the elements from the last frame and
only writes the attributes that changed, so nothing gets rebuilt
from scratch.
Applying a stagger offset means each hole strictly starts animating instantly after the previous one, rendering a beautifully cascading reveal.
Rounding the depth is what makes each hole step one layer at a time.
For a floor that glides instead, set the demo to
Smooth. renderTest takes a
nearZ function, which places a voxel's camera-facing
side at a fractional depth and stretches its walls to meet it.
const faces = heerich.renderTest({
bounds: [[0, 0, 0], [10, 8, 7]],
test: (x, y, z) => !inHole(x, y) || z >= Math.ceil(depth),
nearZ: (x, y, z) => inHole(x, y) && z === Math.ceil(depth) ? depth : z,
})
heerich.updateSVG(svg, { faces })
Putting it all together
A dynamic, procedurally generated composition combining boxes, boolean carving, and functional styles. Recessed voids plunge into a full-width block, revealing depth-shaded walls, while towers steadily rise from within. Fractional voxel scaling smooths the transitions between integer depths, allowing layers to slide smoothly into place rather than abruptly snapping. Click the scene to regenerate.
After Heerich
Exacting recreations of physical cardboard and brass sculptures designed by Erwin Heerich, synthesized entirely in code using this engine.
Kreuzplastik (Brass Cross)
Schachbrett (Checkerboard)
Kartonplastik (Stepped Block)
Demos
Whole pages built with the engine, each on its own. Open one to play with it.