Repository files navigation

linework

npmcilicense: MITzero dependencieslive demo

A tiny true-3D renderer for annotated technical drawings, output as plain SVG strings. Rotate → project → depth-sort → paint. Zero dependencies, ~180-line core, fully tested.

A street lantern imported from a glTF mesh and rendered by linework as feature-edge linework, orbiting

Every frame above is a fresh SVG string — 5,394 triangles reduced to 2,490 feature edges, then rotated, projected and depth-sorted from scratch in ~2 ms. The lantern was imported from a glTF mesh, and the whole loop was rendered by the library itself, in Node, with zero client JavaScript (npm run gif). On the live demo it orbits under your pointer — and you can drop your own model.

Why

The category is empty. WebGL libraries (three.js) make shaded surfaces easy and annotated linework painful — thin strokes, dash patterns, line-weight hierarchy, text callouts are all fights. Pseudo-3D toys (Zdog — last release 2022) can't do text or fine-grained depth sorting. Nothing ships "parametric technical illustration": exploded diagrams, dimension lines, balloons, title blocks. This does exactly that, and nothing else.

  • The classic pipeline, honestly implemented — 3D points → yaw/pitch rotation → perspective projection → painter's-algorithm depth sorting per frame → SVG string. Paint order is computed, never authored.
  • Shapes built for drawings, not games — multi-stroke paths (hollow-tube outlines as one shape), discs that project to correct ellipses, backface-culled boxes, per-object sorting for animated parts.
  • SVG strings are the point — themeable with CSS variables, crawlable, printable, accessible, and renderable server-side at build time.
  • Styling is yours — the library emits class names you define; it never dictates a look.

The sketch layer — DX is a feature

Authoring should read like drafting, not like assembling tuples. Context blocks scope parts, tags and layering over everything drawn inside them:

import{sketch,scene}from"linework/sketch";consts=sketch({yaw: 0.5,pitch: 0.16,f: 1500,cx: 460,cy: 320});s.box(300,380,320,42,40,80);// base plates.part("housing",'class="prt"',()=>{// one <g>, one sort units.cyl([460,218],70,34,-34,"ink");// bearing bodys.bias(0.6,()=>s.cap([460,218],34,32,"ink"));// bore, layered above});s.tube(9).M([180,400]).Q([300,420],20,[420,340],10);// hollow frame tubes.note("320 mm",[460,452]);// paper-space annotationel.innerHTML=s.render();// depth-sorted SVG

For animation, scene() gives you the frame-loop idiom — define once, replay with a new view per frame:

constdraw=scene((s,{ explode })=>{/* build with s.* */});el.innerHTML=draw({ yaw, pitch,f: 1500,cx: 460,cy: 320},{ explode });// ~1 ms for a few hundred shapes — drag-to-orbit rebuilds are free

Prefer bare metal? linework exports the raw Shape types + render()/xform(), and linework/helpers sits in between.

Import a 3D model → a technical drawing

linework/import turns a 3D mesh — glTF/GLB, OBJ, STL, or a three.js BufferGeometry — into linework strokes. A shaded model carries no lines — its form lives in where the surface bends — so it recovers exactly the lines a draftsperson would draw: the outline and the hard creases, nothing from the smooth interior of a face. The result drops straight into render() and rotates like any other scene.

(That lantern in the header is exactly this: a CC0 glTF — 5,394 triangles of shaded mesh → ~2,500 feature edges → rotatable line drawing, in one meshToShapes() call. Drop your own .glb on the demo.)

import{parseGLB,meshToShapes}from"linework/import";import{render}from"linework";constmeshes=parseGLB(awaitfile.arrayBuffer());// parseOBJ · parseSTL · fromBufferGeometryconstshapes=meshToShapes(meshes,{angle: 25,// crease threshold°fit: {cx: 400,cy: 300,size: 440},// fit into a screen box});el.innerHTML=render(shapes,{yaw: 0.6,pitch: 0.35,f: 1400,cx: 400,cy: 300});

featureEdges(mesh) is exposed on its own if you want the raw edge list. Vertices are welded by position first, so meshes that split a shared edge across primitives still sort as one surface. No Draco, and geometry-only — textures and materials are ignored.

Formats:

InputFunctionNotes
glTF / GLBparseGLB(buffer)embedded buffers, node transforms; no Draco
OBJparseOBJ(text)fan-triangulated
STLparseSTL(buffer | text)binary or ASCII; the 3D-printing format
three.jsfromBufferGeometry(geo)reads the typed arrays; no three.js dependency
STEP / IGESfromOcct(result)via occt-import-js (OpenCASCADE WASM) — you bring the kernel; linework stays tiny

STEP is a trimmed-NURBS B-rep, not a mesh — tessellating it is a job for a real CAD kernel, so linework doesn't embed one. occt-import-js returns meshes that fromOcct() maps straight in, keeping the ~6 MB kernel an optional peer rather than a dependency.

Imported geometry is just shapes — so you layer paper-space annotations (overall dimensions, callout balloons, a title block) over an import exactly as you would a hand-authored scene. The live demo dimensions the lantern automatically from its mesh bounds and balloons its extreme features; toggle Annotate to see the annotation layer come and go over the same rotating model.

Coming from Zdog

Zdog is the closest thing to a predecessor, and its last npm release was v1.1.3 in January 2022. If you landed here looking for a maintained alternative, the mental model transfers — but two things differ in kind, not degree.

Zdog is pseudo-3D; this is true 3D. Zdog sorts by a single per-shape depth value, so shapes that interpenetrate resolve wrong and you nudge translate.z until it looks right. Here every vertex is transformed and shapes are depth-sorted per frame, with part() giving you explicit sort units and bias() for the rare tie you want to break by hand.

Zdog paints to canvas or SVG elements; this emits SVG strings. That difference is the whole point of the library: strings are server-renderable at build time, diffable in git, styleable from your own stylesheet, crawlable, and printable.

Zdoglinework
new Zdog.Illustration({element})sketch({ yaw, pitch, f, cx, cy }) — no canvas, no element
new Zdog.Box({...})s.box(x, y, w, h, z, dz)
new Zdog.Cylinder({...})s.cyl(centre, r, zNear, zFar)
new Zdog.Ellipse({...})s.disc(centre, z, r) / s.cap(...)
new Zdog.Shape({path: [...]})s.tube(w).M(...).Q(...) — multi-stroke, one sort unit
new Zdog.Anchor() for groupings.part(name, attrs, () => {...})
no text supports.note(text, point) — paper-space annotations, dimension lines, balloons
illo.rotate.y += 0.03; illo.updateRenderGraph()el.innerHTML = draw({ yaw, ... }) — rebuild the string, ~1 ms
renders to canvas or an SVG element treeemits an SVG string — server-renderable, diffable, printable

The trade is real and worth stating: Zdog's round-everything aesthetic and its canvas renderer are things this does not do. If you want soft, toy-like 3D, Zdog is still charming. If you want a drawing — hard edges, hairlines, callouts, a title block — this is built for that and nothing else.

Coordinates (read this once)

FieldMeaning
xright, in your SVG's user units
ydown — screen convention, not math convention
ztoward the viewer; negative recedes and depth-dims
view.yawrotation about the vertical axis through cx (radians)
view.pitchrotation about the horizontal axis through cy; positive looks down
view.fperspective focal distance — k = f/(f−z); larger = flatter
biasper-shape depth nudge for deliberate coplanar layering

Paper space: annotations (dimensions, balloons, title blocks) are strings appended after the sorted scene — they never rotate, exactly like a real drawing's notes. sketch.pt(p, z) projects model points so leaders can pin paper to model.

Known limitation (shared by every painter's-algorithm renderer): cyclic overlaps can't sort correctly — split long members into segments if you construct one.

Server-side rendering

render() is a pure string function. Static site generators can emit finished 3D-looking diagrams with zero client JS:

import{writeFileSync}from"node:fs";writeFileSync("diagram.svg",wrapInSvgTag(render(shapes,view)));

The lantern hero above is generated exactly this way — scripts/gen-import-demo.mjs imports the committed model and renders the SVG in Node (npm run images); the demo page runs the same code live. For a hand-authored server-side example, see docs/scene.js.

Install & test

npm i linework # ESM, types included
npm test# projection, parallax, paint order, culling,# sketch scoping, and feature-edge extraction

Compatibility

ESM-only (no CJS build), Node ≥ 18, zero runtime dependencies. Which entry runs where:

EntryRuns inNotes
linework · /helpers · /sketch · /importNode and browserpure functions; import uses TextDecoder/DataView, both universal
linework/orbitbrowser onlyuses requestAnimationFrame, matchMedia, performance

render() and the importers run server-side, so you can generate diagrams at build time (see Server-side rendering); only the drag-to-orbit helper needs a browser. Imported files are treated as untrusted input — see SECURITY.md for the parsing threat model.

Versioning: while 0.x, minor releases may contain breaking changes and patch releases won't. From 1.0, standard semver — a breaking change to the public API bumps the major. Releases publish from CI with provenance.

Contributing

Small, dependency-free, and test-driven on purpose — see CONTRIBUTING.md. Changes are tracked in CHANGELOG.md. Issues and PRs welcome.

Provenance

Extracted from Fitment — a "will that part fit your bike?" planner whose exploded service-manual drawings are rendered entirely by this engine, live-orbitable, with dimension callouts in paper space over the rotating model.

License

MIT © Isaac Rowntree

About

Tiny true-3D renderer for annotated technical drawings in SVG — rotate, project, depth-sort, emit strings. Zero dependencies.

Topics

Resources

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content

Repository files navigation

linework

npmcilicense: MITzero dependencieslive demo

A tiny true-3D renderer for annotated technical drawings, output as plain SVG strings. Rotate → project → depth-sort → paint. Zero dependencies, ~180-line core, fully tested.

A street lantern imported from a glTF mesh and rendered by linework as feature-edge linework, orbiting

Every frame above is a fresh SVG string — 5,394 triangles reduced to 2,490 feature edges, then rotated, projected and depth-sorted from scratch in ~2 ms. The lantern was imported from a glTF mesh, and the whole loop was rendered by the library itself, in Node, with zero client JavaScript (npm run gif). On the live demo it orbits under your pointer — and you can drop your own model.

Why

The category is empty. WebGL libraries (three.js) make shaded surfaces easy and annotated linework painful — thin strokes, dash patterns, line-weight hierarchy, text callouts are all fights. Pseudo-3D toys (Zdog — last release 2022) can't do text or fine-grained depth sorting. Nothing ships "parametric technical illustration": exploded diagrams, dimension lines, balloons, title blocks. This does exactly that, and nothing else.

  • The classic pipeline, honestly implemented — 3D points → yaw/pitch rotation → perspective projection → painter's-algorithm depth sorting per frame → SVG string. Paint order is computed, never authored.
  • Shapes built for drawings, not games — multi-stroke paths (hollow-tube outlines as one shape), discs that project to correct ellipses, backface-culled boxes, per-object sorting for animated parts.
  • SVG strings are the point — themeable with CSS variables, crawlable, printable, accessible, and renderable server-side at build time.
  • Styling is yours — the library emits class names you define; it never dictates a look.

The sketch layer — DX is a feature

Authoring should read like drafting, not like assembling tuples. Context blocks scope parts, tags and layering over everything drawn inside them:

import{sketch,scene}from"linework/sketch";consts=sketch({yaw: 0.5,pitch: 0.16,f: 1500,cx: 460,cy: 320});s.box(300,380,320,42,40,80);// base plates.part("housing",'class="prt"',()=>{// one <g>, one sort units.cyl([460,218],70,34,-34,"ink");// bearing bodys.bias(0.6,()=>s.cap([460,218],34,32,"ink"));// bore, layered above});s.tube(9).M([180,400]).Q([300,420],20,[420,340],10);// hollow frame tubes.note("320 mm",[460,452]);// paper-space annotationel.innerHTML=s.render();// depth-sorted SVG

For animation, scene() gives you the frame-loop idiom — define once, replay with a new view per frame:

constdraw=scene((s,{ explode })=>{/* build with s.* */});el.innerHTML=draw({ yaw, pitch,f: 1500,cx: 460,cy: 320},{ explode });// ~1 ms for a few hundred shapes — drag-to-orbit rebuilds are free

Prefer bare metal? linework exports the raw Shape types + render()/xform(), and linework/helpers sits in between.

Import a 3D model → a technical drawing

linework/import turns a 3D mesh — glTF/GLB, OBJ, STL, or a three.js BufferGeometry — into linework strokes. A shaded model carries no lines — its form lives in where the surface bends — so it recovers exactly the lines a draftsperson would draw: the outline and the hard creases, nothing from the smooth interior of a face. The result drops straight into render() and rotates like any other scene.

(That lantern in the header is exactly this: a CC0 glTF — 5,394 triangles of shaded mesh → ~2,500 feature edges → rotatable line drawing, in one meshToShapes() call. Drop your own .glb on the demo.)

import{parseGLB,meshToShapes}from"linework/import";import{render}from"linework";constmeshes=parseGLB(awaitfile.arrayBuffer());// parseOBJ · parseSTL · fromBufferGeometryconstshapes=meshToShapes(meshes,{angle: 25,// crease threshold°fit: {cx: 400,cy: 300,size: 440},// fit into a screen box});el.innerHTML=render(shapes,{yaw: 0.6,pitch: 0.35,f: 1400,cx: 400,cy: 300});

featureEdges(mesh) is exposed on its own if you want the raw edge list. Vertices are welded by position first, so meshes that split a shared edge across primitives still sort as one surface. No Draco, and geometry-only — textures and materials are ignored.

Formats:

InputFunctionNotes
glTF / GLBparseGLB(buffer)embedded buffers, node transforms; no Draco
OBJparseOBJ(text)fan-triangulated
STLparseSTL(buffer | text)binary or ASCII; the 3D-printing format
three.jsfromBufferGeometry(geo)reads the typed arrays; no three.js dependency
STEP / IGESfromOcct(result)via occt-import-js (OpenCASCADE WASM) — you bring the kernel; linework stays tiny

STEP is a trimmed-NURBS B-rep, not a mesh — tessellating it is a job for a real CAD kernel, so linework doesn't embed one. occt-import-js returns meshes that fromOcct() maps straight in, keeping the ~6 MB kernel an optional peer rather than a dependency.

Imported geometry is just shapes — so you layer paper-space annotations (overall dimensions, callout balloons, a title block) over an import exactly as you would a hand-authored scene. The live demo dimensions the lantern automatically from its mesh bounds and balloons its extreme features; toggle Annotate to see the annotation layer come and go over the same rotating model.

Coming from Zdog

Zdog is the closest thing to a predecessor, and its last npm release was v1.1.3 in January 2022. If you landed here looking for a maintained alternative, the mental model transfers — but two things differ in kind, not degree.

Zdog is pseudo-3D; this is true 3D. Zdog sorts by a single per-shape depth value, so shapes that interpenetrate resolve wrong and you nudge translate.z until it looks right. Here every vertex is transformed and shapes are depth-sorted per frame, with part() giving you explicit sort units and bias() for the rare tie you want to break by hand.

Zdog paints to canvas or SVG elements; this emits SVG strings. That difference is the whole point of the library: strings are server-renderable at build time, diffable in git, styleable from your own stylesheet, crawlable, and printable.

Zdoglinework
new Zdog.Illustration({element})sketch({ yaw, pitch, f, cx, cy }) — no canvas, no element
new Zdog.Box({...})s.box(x, y, w, h, z, dz)
new Zdog.Cylinder({...})s.cyl(centre, r, zNear, zFar)
new Zdog.Ellipse({...})s.disc(centre, z, r) / s.cap(...)
new Zdog.Shape({path: [...]})s.tube(w).M(...).Q(...) — multi-stroke, one sort unit
new Zdog.Anchor() for groupings.part(name, attrs, () => {...})
no text supports.note(text, point) — paper-space annotations, dimension lines, balloons
illo.rotate.y += 0.03; illo.updateRenderGraph()el.innerHTML = draw({ yaw, ... }) — rebuild the string, ~1 ms
renders to canvas or an SVG element treeemits an SVG string — server-renderable, diffable, printable

The trade is real and worth stating: Zdog's round-everything aesthetic and its canvas renderer are things this does not do. If you want soft, toy-like 3D, Zdog is still charming. If you want a drawing — hard edges, hairlines, callouts, a title block — this is built for that and nothing else.

Coordinates (read this once)

FieldMeaning
xright, in your SVG's user units
ydown — screen convention, not math convention
ztoward the viewer; negative recedes and depth-dims
view.yawrotation about the vertical axis through cx (radians)
view.pitchrotation about the horizontal axis through cy; positive looks down
view.fperspective focal distance — k = f/(f−z); larger = flatter
biasper-shape depth nudge for deliberate coplanar layering

Paper space: annotations (dimensions, balloons, title blocks) are strings appended after the sorted scene — they never rotate, exactly like a real drawing's notes. sketch.pt(p, z) projects model points so leaders can pin paper to model.

Known limitation (shared by every painter's-algorithm renderer): cyclic overlaps can't sort correctly — split long members into segments if you construct one.

Server-side rendering

render() is a pure string function. Static site generators can emit finished 3D-looking diagrams with zero client JS:

import{writeFileSync}from"node:fs";writeFileSync("diagram.svg",wrapInSvgTag(render(shapes,view)));

The lantern hero above is generated exactly this way — scripts/gen-import-demo.mjs imports the committed model and renders the SVG in Node (npm run images); the demo page runs the same code live. For a hand-authored server-side example, see docs/scene.js.

Install & test

npm i linework # ESM, types included
npm test# projection, parallax, paint order, culling,# sketch scoping, and feature-edge extraction

Compatibility

ESM-only (no CJS build), Node ≥ 18, zero runtime dependencies. Which entry runs where:

EntryRuns inNotes
linework · /helpers · /sketch · /importNode and browserpure functions; import uses TextDecoder/DataView, both universal
linework/orbitbrowser onlyuses requestAnimationFrame, matchMedia, performance

render() and the importers run server-side, so you can generate diagrams at build time (see Server-side rendering); only the drag-to-orbit helper needs a browser. Imported files are treated as untrusted input — see SECURITY.md for the parsing threat model.

Versioning: while 0.x, minor releases may contain breaking changes and patch releases won't. From 1.0, standard semver — a breaking change to the public API bumps the major. Releases publish from CI with provenance.

Contributing

Small, dependency-free, and test-driven on purpose — see CONTRIBUTING.md. Changes are tracked in CHANGELOG.md. Issues and PRs welcome.

Provenance

Extracted from Fitment — a "will that part fit your bike?" planner whose exploded service-manual drawings are rendered entirely by this engine, live-orbitable, with dimension callouts in paper space over the rotating model.

License

MIT © Isaac Rowntree

About

Tiny true-3D renderer for annotated technical drawings in SVG — rotate, project, depth-sort, emit strings. Zero dependencies.

Topics

Resources

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

linework

npmcilicense: MITzero dependencieslive demo

A tiny true-3D renderer for annotated technical drawings, output as plain SVG strings. Rotate → project → depth-sort → paint. Zero dependencies, ~180-line core, fully tested.

A street lantern imported from a glTF mesh and rendered by linework as feature-edge linework, orbiting

Every frame above is a fresh SVG string — 5,394 triangles reduced to 2,490 feature edges, then rotated, projected and depth-sorted from scratch in ~2 ms. The lantern was imported from a glTF mesh, and the whole loop was rendered by the library itself, in Node, with zero client JavaScript (npm run gif). On the live demo it orbits under your pointer — and you can drop your own model.

Why

The category is empty. WebGL libraries (three.js) make shaded surfaces easy and annotated linework painful — thin strokes, dash patterns, line-weight hierarchy, text callouts are all fights. Pseudo-3D toys (Zdog — last release 2022) can't do text or fine-grained depth sorting. Nothing ships "parametric technical illustration": exploded diagrams, dimension lines, balloons, title blocks. This does exactly that, and nothing else.

  • The classic pipeline, honestly implemented — 3D points → yaw/pitch rotation → perspective projection → painter's-algorithm depth sorting per frame → SVG string. Paint order is computed, never authored.
  • Shapes built for drawings, not games — multi-stroke paths (hollow-tube outlines as one shape), discs that project to correct ellipses, backface-culled boxes, per-object sorting for animated parts.
  • SVG strings are the point — themeable with CSS variables, crawlable, printable, accessible, and renderable server-side at build time.
  • Styling is yours — the library emits class names you define; it never dictates a look.

The sketch layer — DX is a feature

Authoring should read like drafting, not like assembling tuples. Context blocks scope parts, tags and layering over everything drawn inside them:

import{sketch,scene}from"linework/sketch";consts=sketch({yaw: 0.5,pitch: 0.16,f: 1500,cx: 460,cy: 320});s.box(300,380,320,42,40,80);// base plates.part("housing",'class="prt"',()=>{// one <g>, one sort units.cyl([460,218],70,34,-34,"ink");// bearing bodys.bias(0.6,()=>s.cap([460,218],34,32,"ink"));// bore, layered above});s.tube(9).M([180,400]).Q([300,420],20,[420,340],10);// hollow frame tubes.note("320 mm",[460,452]);// paper-space annotationel.innerHTML=s.render();// depth-sorted SVG

For animation, scene() gives you the frame-loop idiom — define once, replay with a new view per frame:

constdraw=scene((s,{ explode })=>{/* build with s.* */});el.innerHTML=draw({ yaw, pitch,f: 1500,cx: 460,cy: 320},{ explode });// ~1 ms for a few hundred shapes — drag-to-orbit rebuilds are free

Prefer bare metal? linework exports the raw Shape types + render()/xform(), and linework/helpers sits in between.

Import a 3D model → a technical drawing

linework/import turns a 3D mesh — glTF/GLB, OBJ, STL, or a three.js BufferGeometry — into linework strokes. A shaded model carries no lines — its form lives in where the surface bends — so it recovers exactly the lines a draftsperson would draw: the outline and the hard creases, nothing from the smooth interior of a face. The result drops straight into render() and rotates like any other scene.

(That lantern in the header is exactly this: a CC0 glTF — 5,394 triangles of shaded mesh → ~2,500 feature edges → rotatable line drawing, in one meshToShapes() call. Drop your own .glb on the demo.)

import{parseGLB,meshToShapes}from"linework/import";import{render}from"linework";constmeshes=parseGLB(awaitfile.arrayBuffer());// parseOBJ · parseSTL · fromBufferGeometryconstshapes=meshToShapes(meshes,{angle: 25,// crease threshold°fit: {cx: 400,cy: 300,size: 440},// fit into a screen box});el.innerHTML=render(shapes,{yaw: 0.6,pitch: 0.35,f: 1400,cx: 400,cy: 300});

featureEdges(mesh) is exposed on its own if you want the raw edge list. Vertices are welded by position first, so meshes that split a shared edge across primitives still sort as one surface. No Draco, and geometry-only — textures and materials are ignored.

Formats:

InputFunctionNotes
glTF / GLBparseGLB(buffer)embedded buffers, node transforms; no Draco
OBJparseOBJ(text)fan-triangulated
STLparseSTL(buffer | text)binary or ASCII; the 3D-printing format
three.jsfromBufferGeometry(geo)reads the typed arrays; no three.js dependency
STEP / IGESfromOcct(result)via occt-import-js (OpenCASCADE WASM) — you bring the kernel; linework stays tiny

STEP is a trimmed-NURBS B-rep, not a mesh — tessellating it is a job for a real CAD kernel, so linework doesn't embed one. occt-import-js returns meshes that fromOcct() maps straight in, keeping the ~6 MB kernel an optional peer rather than a dependency.

Imported geometry is just shapes — so you layer paper-space annotations (overall dimensions, callout balloons, a title block) over an import exactly as you would a hand-authored scene. The live demo dimensions the lantern automatically from its mesh bounds and balloons its extreme features; toggle Annotate to see the annotation layer come and go over the same rotating model.

Coming from Zdog

Zdog is the closest thing to a predecessor, and its last npm release was v1.1.3 in January 2022. If you landed here looking for a maintained alternative, the mental model transfers — but two things differ in kind, not degree.

Zdog is pseudo-3D; this is true 3D. Zdog sorts by a single per-shape depth value, so shapes that interpenetrate resolve wrong and you nudge translate.z until it looks right. Here every vertex is transformed and shapes are depth-sorted per frame, with part() giving you explicit sort units and bias() for the rare tie you want to break by hand.

Zdog paints to canvas or SVG elements; this emits SVG strings. That difference is the whole point of the library: strings are server-renderable at build time, diffable in git, styleable from your own stylesheet, crawlable, and printable.

Zdoglinework
new Zdog.Illustration({element})sketch({ yaw, pitch, f, cx, cy }) — no canvas, no element
new Zdog.Box({...})s.box(x, y, w, h, z, dz)
new Zdog.Cylinder({...})s.cyl(centre, r, zNear, zFar)
new Zdog.Ellipse({...})s.disc(centre, z, r) / s.cap(...)
new Zdog.Shape({path: [...]})s.tube(w).M(...).Q(...) — multi-stroke, one sort unit
new Zdog.Anchor() for groupings.part(name, attrs, () => {...})
no text supports.note(text, point) — paper-space annotations, dimension lines, balloons
illo.rotate.y += 0.03; illo.updateRenderGraph()el.innerHTML = draw({ yaw, ... }) — rebuild the string, ~1 ms
renders to canvas or an SVG element treeemits an SVG string — server-renderable, diffable, printable

The trade is real and worth stating: Zdog's round-everything aesthetic and its canvas renderer are things this does not do. If you want soft, toy-like 3D, Zdog is still charming. If you want a drawing — hard edges, hairlines, callouts, a title block — this is built for that and nothing else.

Coordinates (read this once)

FieldMeaning
xright, in your SVG's user units
ydown — screen convention, not math convention
ztoward the viewer; negative recedes and depth-dims
view.yawrotation about the vertical axis through cx (radians)
view.pitchrotation about the horizontal axis through cy; positive looks down
view.fperspective focal distance — k = f/(f−z); larger = flatter
biasper-shape depth nudge for deliberate coplanar layering

Paper space: annotations (dimensions, balloons, title blocks) are strings appended after the sorted scene — they never rotate, exactly like a real drawing's notes. sketch.pt(p, z) projects model points so leaders can pin paper to model.

Known limitation (shared by every painter's-algorithm renderer): cyclic overlaps can't sort correctly — split long members into segments if you construct one.

Server-side rendering

render() is a pure string function. Static site generators can emit finished 3D-looking diagrams with zero client JS:

import{writeFileSync}from"node:fs";writeFileSync("diagram.svg",wrapInSvgTag(render(shapes,view)));

The lantern hero above is generated exactly this way — scripts/gen-import-demo.mjs imports the committed model and renders the SVG in Node (npm run images); the demo page runs the same code live. For a hand-authored server-side example, see docs/scene.js.

Install & test

npm i linework # ESM, types included
npm test# projection, parallax, paint order, culling,# sketch scoping, and feature-edge extraction

Compatibility

ESM-only (no CJS build), Node ≥ 18, zero runtime dependencies. Which entry runs where:

EntryRuns inNotes
linework · /helpers · /sketch · /importNode and browserpure functions; import uses TextDecoder/DataView, both universal
linework/orbitbrowser onlyuses requestAnimationFrame, matchMedia, performance

render() and the importers run server-side, so you can generate diagrams at build time (see Server-side rendering); only the drag-to-orbit helper needs a browser. Imported files are treated as untrusted input — see SECURITY.md for the parsing threat model.

Versioning: while 0.x, minor releases may contain breaking changes and patch releases won't. From 1.0, standard semver — a breaking change to the public API bumps the major. Releases publish from CI with provenance.

Contributing

Small, dependency-free, and test-driven on purpose — see CONTRIBUTING.md. Changes are tracked in CHANGELOG.md. Issues and PRs welcome.

Provenance

Extracted from Fitment — a "will that part fit your bike?" planner whose exploded service-manual drawings are rendered entirely by this engine, live-orbitable, with dimension callouts in paper space over the rotating model.

License

MIT © Isaac Rowntree

About

Tiny true-3D renderer for annotated technical drawings in SVG — rotate, project, depth-sort, emit strings. Zero dependencies.

Topics

Resources

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

linework

npmcilicense: MITzero dependencieslive demo

A tiny true-3D renderer for annotated technical drawings, output as plain SVG strings. Rotate → project → depth-sort → paint. Zero dependencies, ~180-line core, fully tested.

A street lantern imported from a glTF mesh and rendered by linework as feature-edge linework, orbiting

Every frame above is a fresh SVG string — 5,394 triangles reduced to 2,490 feature edges, then rotated, projected and depth-sorted from scratch in ~2 ms. The lantern was imported from a glTF mesh, and the whole loop was rendered by the library itself, in Node, with zero client JavaScript (npm run gif). On the live demo it orbits under your pointer — and you can drop your own model.

Why

The category is empty. WebGL libraries (three.js) make shaded surfaces easy and annotated linework painful — thin strokes, dash patterns, line-weight hierarchy, text callouts are all fights. Pseudo-3D toys (Zdog — last release 2022) can't do text or fine-grained depth sorting. Nothing ships "parametric technical illustration": exploded diagrams, dimension lines, balloons, title blocks. This does exactly that, and nothing else.

  • The classic pipeline, honestly implemented — 3D points → yaw/pitch rotation → perspective projection → painter's-algorithm depth sorting per frame → SVG string. Paint order is computed, never authored.
  • Shapes built for drawings, not games — multi-stroke paths (hollow-tube outlines as one shape), discs that project to correct ellipses, backface-culled boxes, per-object sorting for animated parts.
  • SVG strings are the point — themeable with CSS variables, crawlable, printable, accessible, and renderable server-side at build time.
  • Styling is yours — the library emits class names you define; it never dictates a look.

The sketch layer — DX is a feature

Authoring should read like drafting, not like assembling tuples. Context blocks scope parts, tags and layering over everything drawn inside them:

import{sketch,scene}from"linework/sketch";consts=sketch({yaw: 0.5,pitch: 0.16,f: 1500,cx: 460,cy: 320});s.box(300,380,320,42,40,80);// base plates.part("housing",'class="prt"',()=>{// one <g>, one sort units.cyl([460,218],70,34,-34,"ink");// bearing bodys.bias(0.6,()=>s.cap([460,218],34,32,"ink"));// bore, layered above});s.tube(9).M([180,400]).Q([300,420],20,[420,340],10);// hollow frame tubes.note("320 mm",[460,452]);// paper-space annotationel.innerHTML=s.render();// depth-sorted SVG

For animation, scene() gives you the frame-loop idiom — define once, replay with a new view per frame:

constdraw=scene((s,{ explode })=>{/* build with s.* */});el.innerHTML=draw({ yaw, pitch,f: 1500,cx: 460,cy: 320},{ explode });// ~1 ms for a few hundred shapes — drag-to-orbit rebuilds are free

Prefer bare metal? linework exports the raw Shape types + render()/xform(), and linework/helpers sits in between.

Import a 3D model → a technical drawing

linework/import turns a 3D mesh — glTF/GLB, OBJ, STL, or a three.js BufferGeometry — into linework strokes. A shaded model carries no lines — its form lives in where the surface bends — so it recovers exactly the lines a draftsperson would draw: the outline and the hard creases, nothing from the smooth interior of a face. The result drops straight into render() and rotates like any other scene.

(That lantern in the header is exactly this: a CC0 glTF — 5,394 triangles of shaded mesh → ~2,500 feature edges → rotatable line drawing, in one meshToShapes() call. Drop your own .glb on the demo.)

import{parseGLB,meshToShapes}from"linework/import";import{render}from"linework";constmeshes=parseGLB(awaitfile.arrayBuffer());// parseOBJ · parseSTL · fromBufferGeometryconstshapes=meshToShapes(meshes,{angle: 25,// crease threshold°fit: {cx: 400,cy: 300,size: 440},// fit into a screen box});el.innerHTML=render(shapes,{yaw: 0.6,pitch: 0.35,f: 1400,cx: 400,cy: 300});

featureEdges(mesh) is exposed on its own if you want the raw edge list. Vertices are welded by position first, so meshes that split a shared edge across primitives still sort as one surface. No Draco, and geometry-only — textures and materials are ignored.

Formats:

InputFunctionNotes
glTF / GLBparseGLB(buffer)embedded buffers, node transforms; no Draco
OBJparseOBJ(text)fan-triangulated
STLparseSTL(buffer | text)binary or ASCII; the 3D-printing format
three.jsfromBufferGeometry(geo)reads the typed arrays; no three.js dependency
STEP / IGESfromOcct(result)via occt-import-js (OpenCASCADE WASM) — you bring the kernel; linework stays tiny

STEP is a trimmed-NURBS B-rep, not a mesh — tessellating it is a job for a real CAD kernel, so linework doesn't embed one. occt-import-js returns meshes that fromOcct() maps straight in, keeping the ~6 MB kernel an optional peer rather than a dependency.

Imported geometry is just shapes — so you layer paper-space annotations (overall dimensions, callout balloons, a title block) over an import exactly as you would a hand-authored scene. The live demo dimensions the lantern automatically from its mesh bounds and balloons its extreme features; toggle Annotate to see the annotation layer come and go over the same rotating model.

Coming from Zdog

Zdog is the closest thing to a predecessor, and its last npm release was v1.1.3 in January 2022. If you landed here looking for a maintained alternative, the mental model transfers — but two things differ in kind, not degree.

Zdog is pseudo-3D; this is true 3D. Zdog sorts by a single per-shape depth value, so shapes that interpenetrate resolve wrong and you nudge translate.z until it looks right. Here every vertex is transformed and shapes are depth-sorted per frame, with part() giving you explicit sort units and bias() for the rare tie you want to break by hand.

Zdog paints to canvas or SVG elements; this emits SVG strings. That difference is the whole point of the library: strings are server-renderable at build time, diffable in git, styleable from your own stylesheet, crawlable, and printable.

Zdoglinework
new Zdog.Illustration({element})sketch({ yaw, pitch, f, cx, cy }) — no canvas, no element
new Zdog.Box({...})s.box(x, y, w, h, z, dz)
new Zdog.Cylinder({...})s.cyl(centre, r, zNear, zFar)
new Zdog.Ellipse({...})s.disc(centre, z, r) / s.cap(...)
new Zdog.Shape({path: [...]})s.tube(w).M(...).Q(...) — multi-stroke, one sort unit
new Zdog.Anchor() for groupings.part(name, attrs, () => {...})
no text supports.note(text, point) — paper-space annotations, dimension lines, balloons
illo.rotate.y += 0.03; illo.updateRenderGraph()el.innerHTML = draw({ yaw, ... }) — rebuild the string, ~1 ms
renders to canvas or an SVG element treeemits an SVG string — server-renderable, diffable, printable

The trade is real and worth stating: Zdog's round-everything aesthetic and its canvas renderer are things this does not do. If you want soft, toy-like 3D, Zdog is still charming. If you want a drawing — hard edges, hairlines, callouts, a title block — this is built for that and nothing else.

Coordinates (read this once)

FieldMeaning
xright, in your SVG's user units
ydown — screen convention, not math convention
ztoward the viewer; negative recedes and depth-dims
view.yawrotation about the vertical axis through cx (radians)
view.pitchrotation about the horizontal axis through cy; positive looks down
view.fperspective focal distance — k = f/(f−z); larger = flatter
biasper-shape depth nudge for deliberate coplanar layering

Paper space: annotations (dimensions, balloons, title blocks) are strings appended after the sorted scene — they never rotate, exactly like a real drawing's notes. sketch.pt(p, z) projects model points so leaders can pin paper to model.

Known limitation (shared by every painter's-algorithm renderer): cyclic overlaps can't sort correctly — split long members into segments if you construct one.

Server-side rendering

render() is a pure string function. Static site generators can emit finished 3D-looking diagrams with zero client JS:

import{writeFileSync}from"node:fs";writeFileSync("diagram.svg",wrapInSvgTag(render(shapes,view)));

The lantern hero above is generated exactly this way — scripts/gen-import-demo.mjs imports the committed model and renders the SVG in Node (npm run images); the demo page runs the same code live. For a hand-authored server-side example, see docs/scene.js.

Install & test

npm i linework # ESM, types included
npm test# projection, parallax, paint order, culling,# sketch scoping, and feature-edge extraction

Compatibility

ESM-only (no CJS build), Node ≥ 18, zero runtime dependencies. Which entry runs where:

EntryRuns inNotes
linework · /helpers · /sketch · /importNode and browserpure functions; import uses TextDecoder/DataView, both universal
linework/orbitbrowser onlyuses requestAnimationFrame, matchMedia, performance

render() and the importers run server-side, so you can generate diagrams at build time (see Server-side rendering); only the drag-to-orbit helper needs a browser. Imported files are treated as untrusted input — see SECURITY.md for the parsing threat model.

Versioning: while 0.x, minor releases may contain breaking changes and patch releases won't. From 1.0, standard semver — a breaking change to the public API bumps the major. Releases publish from CI with provenance.

Contributing

Small, dependency-free, and test-driven on purpose — see CONTRIBUTING.md. Changes are tracked in CHANGELOG.md. Issues and PRs welcome.

Provenance

Extracted from Fitment — a "will that part fit your bike?" planner whose exploded service-manual drawings are rendered entirely by this engine, live-orbitable, with dimension callouts in paper space over the rotating model.

License

MIT © Isaac Rowntree

About

Tiny true-3D renderer for annotated technical drawings in SVG — rotate, project, depth-sort, emit strings. Zero dependencies.

Topics

Resources

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

Repository files navigation

linework

npmcilicense: MITzero dependencieslive demo

A tiny true-3D renderer for annotated technical drawings, output as plain SVG strings. Rotate → project → depth-sort → paint. Zero dependencies, ~180-line core, fully tested.

A street lantern imported from a glTF mesh and rendered by linework as feature-edge linework, orbiting

Every frame above is a fresh SVG string — 5,394 triangles reduced to 2,490 feature edges, then rotated, projected and depth-sorted from scratch in ~2 ms. The lantern was imported from a glTF mesh, and the whole loop was rendered by the library itself, in Node, with zero client JavaScript (npm run gif). On the live demo it orbits under your pointer — and you can drop your own model.

Why

The category is empty. WebGL libraries (three.js) make shaded surfaces easy and annotated linework painful — thin strokes, dash patterns, line-weight hierarchy, text callouts are all fights. Pseudo-3D toys (Zdog — last release 2022) can't do text or fine-grained depth sorting. Nothing ships "parametric technical illustration": exploded diagrams, dimension lines, balloons, title blocks. This does exactly that, and nothing else.

  • The classic pipeline, honestly implemented — 3D points → yaw/pitch rotation → perspective projection → painter's-algorithm depth sorting per frame → SVG string. Paint order is computed, never authored.
  • Shapes built for drawings, not games — multi-stroke paths (hollow-tube outlines as one shape), discs that project to correct ellipses, backface-culled boxes, per-object sorting for animated parts.
  • SVG strings are the point — themeable with CSS variables, crawlable, printable, accessible, and renderable server-side at build time.
  • Styling is yours — the library emits class names you define; it never dictates a look.

The sketch layer — DX is a feature

Authoring should read like drafting, not like assembling tuples. Context blocks scope parts, tags and layering over everything drawn inside them:

import{sketch,scene}from"linework/sketch";consts=sketch({yaw: 0.5,pitch: 0.16,f: 1500,cx: 460,cy: 320});s.box(300,380,320,42,40,80);// base plates.part("housing",'class="prt"',()=>{// one <g>, one sort units.cyl([460,218],70,34,-34,"ink");// bearing bodys.bias(0.6,()=>s.cap([460,218],34,32,"ink"));// bore, layered above});s.tube(9).M([180,400]).Q([300,420],20,[420,340],10);// hollow frame tubes.note("320 mm",[460,452]);// paper-space annotationel.innerHTML=s.render();// depth-sorted SVG

For animation, scene() gives you the frame-loop idiom — define once, replay with a new view per frame:

constdraw=scene((s,{ explode })=>{/* build with s.* */});el.innerHTML=draw({ yaw, pitch,f: 1500,cx: 460,cy: 320},{ explode });// ~1 ms for a few hundred shapes — drag-to-orbit rebuilds are free

Prefer bare metal? linework exports the raw Shape types + render()/xform(), and linework/helpers sits in between.

Import a 3D model → a technical drawing

linework/import turns a 3D mesh — glTF/GLB, OBJ, STL, or a three.js BufferGeometry — into linework strokes. A shaded model carries no lines — its form lives in where the surface bends — so it recovers exactly the lines a draftsperson would draw: the outline and the hard creases, nothing from the smooth interior of a face. The result drops straight into render() and rotates like any other scene.

(That lantern in the header is exactly this: a CC0 glTF — 5,394 triangles of shaded mesh → ~2,500 feature edges → rotatable line drawing, in one meshToShapes() call. Drop your own .glb on the demo.)

import{parseGLB,meshToShapes}from"linework/import";import{render}from"linework";constmeshes=parseGLB(awaitfile.arrayBuffer());// parseOBJ · parseSTL · fromBufferGeometryconstshapes=meshToShapes(meshes,{angle: 25,// crease threshold°fit: {cx: 400,cy: 300,size: 440},// fit into a screen box});el.innerHTML=render(shapes,{yaw: 0.6,pitch: 0.35,f: 1400,cx: 400,cy: 300});

featureEdges(mesh) is exposed on its own if you want the raw edge list. Vertices are welded by position first, so meshes that split a shared edge across primitives still sort as one surface. No Draco, and geometry-only — textures and materials are ignored.

Formats:

InputFunctionNotes
glTF / GLBparseGLB(buffer)embedded buffers, node transforms; no Draco
OBJparseOBJ(text)fan-triangulated
STLparseSTL(buffer | text)binary or ASCII; the 3D-printing format
three.jsfromBufferGeometry(geo)reads the typed arrays; no three.js dependency
STEP / IGESfromOcct(result)via occt-import-js (OpenCASCADE WASM) — you bring the kernel; linework stays tiny

STEP is a trimmed-NURBS B-rep, not a mesh — tessellating it is a job for a real CAD kernel, so linework doesn't embed one. occt-import-js returns meshes that fromOcct() maps straight in, keeping the ~6 MB kernel an optional peer rather than a dependency.

Imported geometry is just shapes — so you layer paper-space annotations (overall dimensions, callout balloons, a title block) over an import exactly as you would a hand-authored scene. The live demo dimensions the lantern automatically from its mesh bounds and balloons its extreme features; toggle Annotate to see the annotation layer come and go over the same rotating model.

Coming from Zdog

Zdog is the closest thing to a predecessor, and its last npm release was v1.1.3 in January 2022. If you landed here looking for a maintained alternative, the mental model transfers — but two things differ in kind, not degree.

Zdog is pseudo-3D; this is true 3D. Zdog sorts by a single per-shape depth value, so shapes that interpenetrate resolve wrong and you nudge translate.z until it looks right. Here every vertex is transformed and shapes are depth-sorted per frame, with part() giving you explicit sort units and bias() for the rare tie you want to break by hand.

Zdog paints to canvas or SVG elements; this emits SVG strings. That difference is the whole point of the library: strings are server-renderable at build time, diffable in git, styleable from your own stylesheet, crawlable, and printable.

Zdoglinework
new Zdog.Illustration({element})sketch({ yaw, pitch, f, cx, cy }) — no canvas, no element
new Zdog.Box({...})s.box(x, y, w, h, z, dz)
new Zdog.Cylinder({...})s.cyl(centre, r, zNear, zFar)
new Zdog.Ellipse({...})s.disc(centre, z, r) / s.cap(...)
new Zdog.Shape({path: [...]})s.tube(w).M(...).Q(...) — multi-stroke, one sort unit
new Zdog.Anchor() for groupings.part(name, attrs, () => {...})
no text supports.note(text, point) — paper-space annotations, dimension lines, balloons
illo.rotate.y += 0.03; illo.updateRenderGraph()el.innerHTML = draw({ yaw, ... }) — rebuild the string, ~1 ms
renders to canvas or an SVG element treeemits an SVG string — server-renderable, diffable, printable

The trade is real and worth stating: Zdog's round-everything aesthetic and its canvas renderer are things this does not do. If you want soft, toy-like 3D, Zdog is still charming. If you want a drawing — hard edges, hairlines, callouts, a title block — this is built for that and nothing else.

Coordinates (read this once)

FieldMeaning
xright, in your SVG's user units
ydown — screen convention, not math convention
ztoward the viewer; negative recedes and depth-dims
view.yawrotation about the vertical axis through cx (radians)
view.pitchrotation about the horizontal axis through cy; positive looks down
view.fperspective focal distance — k = f/(f−z); larger = flatter
biasper-shape depth nudge for deliberate coplanar layering

Paper space: annotations (dimensions, balloons, title blocks) are strings appended after the sorted scene — they never rotate, exactly like a real drawing's notes. sketch.pt(p, z) projects model points so leaders can pin paper to model.

Known limitation (shared by every painter's-algorithm renderer): cyclic overlaps can't sort correctly — split long members into segments if you construct one.

Server-side rendering

render() is a pure string function. Static site generators can emit finished 3D-looking diagrams with zero client JS:

import{writeFileSync}from"node:fs";writeFileSync("diagram.svg",wrapInSvgTag(render(shapes,view)));

The lantern hero above is generated exactly this way — scripts/gen-import-demo.mjs imports the committed model and renders the SVG in Node (npm run images); the demo page runs the same code live. For a hand-authored server-side example, see docs/scene.js.

Install & test

npm i linework # ESM, types included
npm test# projection, parallax, paint order, culling,# sketch scoping, and feature-edge extraction

Compatibility

ESM-only (no CJS build), Node ≥ 18, zero runtime dependencies. Which entry runs where:

EntryRuns inNotes
linework · /helpers · /sketch · /importNode and browserpure functions; import uses TextDecoder/DataView, both universal
linework/orbitbrowser onlyuses requestAnimationFrame, matchMedia, performance

render() and the importers run server-side, so you can generate diagrams at build time (see Server-side rendering); only the drag-to-orbit helper needs a browser. Imported files are treated as untrusted input — see SECURITY.md for the parsing threat model.

Versioning: while 0.x, minor releases may contain breaking changes and patch releases won't. From 1.0, standard semver — a breaking change to the public API bumps the major. Releases publish from CI with provenance.

Contributing

Small, dependency-free, and test-driven on purpose — see CONTRIBUTING.md. Changes are tracked in CHANGELOG.md. Issues and PRs welcome.

Provenance

Extracted from Fitment — a "will that part fit your bike?" planner whose exploded service-manual drawings are rendered entirely by this engine, live-orbitable, with dimension callouts in paper space over the rotating model.

License

MIT © Isaac Rowntree

About

Tiny true-3D renderer for annotated technical drawings in SVG — rotate, project, depth-sort, emit strings. Zero dependencies.

Topics

Resources

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

linework

npmcilicense: MITzero dependencieslive demo

A tiny true-3D renderer for annotated technical drawings, output as plain SVG strings. Rotate → project → depth-sort → paint. Zero dependencies, ~180-line core, fully tested.

A street lantern imported from a glTF mesh and rendered by linework as feature-edge linework, orbiting

Every frame above is a fresh SVG string — 5,394 triangles reduced to 2,490 feature edges, then rotated, projected and depth-sorted from scratch in ~2 ms. The lantern was imported from a glTF mesh, and the whole loop was rendered by the library itself, in Node, with zero client JavaScript (npm run gif). On the live demo it orbits under your pointer — and you can drop your own model.

Why

The category is empty. WebGL libraries (three.js) make shaded surfaces easy and annotated linework painful — thin strokes, dash patterns, line-weight hierarchy, text callouts are all fights. Pseudo-3D toys (Zdog — last release 2022) can't do text or fine-grained depth sorting. Nothing ships "parametric technical illustration": exploded diagrams, dimension lines, balloons, title blocks. This does exactly that, and nothing else.

  • The classic pipeline, honestly implemented — 3D points → yaw/pitch rotation → perspective projection → painter's-algorithm depth sorting per frame → SVG string. Paint order is computed, never authored.
  • Shapes built for drawings, not games — multi-stroke paths (hollow-tube outlines as one shape), discs that project to correct ellipses, backface-culled boxes, per-object sorting for animated parts.
  • SVG strings are the point — themeable with CSS variables, crawlable, printable, accessible, and renderable server-side at build time.
  • Styling is yours — the library emits class names you define; it never dictates a look.

The sketch layer — DX is a feature

Authoring should read like drafting, not like assembling tuples. Context blocks scope parts, tags and layering over everything drawn inside them:

import{sketch,scene}from"linework/sketch";consts=sketch({yaw: 0.5,pitch: 0.16,f: 1500,cx: 460,cy: 320});s.box(300,380,320,42,40,80);// base plates.part("housing",'class="prt"',()=>{// one <g>, one sort units.cyl([460,218],70,34,-34,"ink");// bearing bodys.bias(0.6,()=>s.cap([460,218],34,32,"ink"));// bore, layered above});s.tube(9).M([180,400]).Q([300,420],20,[420,340],10);// hollow frame tubes.note("320 mm",[460,452]);// paper-space annotationel.innerHTML=s.render();// depth-sorted SVG

For animation, scene() gives you the frame-loop idiom — define once, replay with a new view per frame:

constdraw=scene((s,{ explode })=>{/* build with s.* */});el.innerHTML=draw({ yaw, pitch,f: 1500,cx: 460,cy: 320},{ explode });// ~1 ms for a few hundred shapes — drag-to-orbit rebuilds are free

Prefer bare metal? linework exports the raw Shape types + render()/xform(), and linework/helpers sits in between.

Import a 3D model → a technical drawing

linework/import turns a 3D mesh — glTF/GLB, OBJ, STL, or a three.js BufferGeometry — into linework strokes. A shaded model carries no lines — its form lives in where the surface bends — so it recovers exactly the lines a draftsperson would draw: the outline and the hard creases, nothing from the smooth interior of a face. The result drops straight into render() and rotates like any other scene.

(That lantern in the header is exactly this: a CC0 glTF — 5,394 triangles of shaded mesh → ~2,500 feature edges → rotatable line drawing, in one meshToShapes() call. Drop your own .glb on the demo.)

import{parseGLB,meshToShapes}from"linework/import";import{render}from"linework";constmeshes=parseGLB(awaitfile.arrayBuffer());// parseOBJ · parseSTL · fromBufferGeometryconstshapes=meshToShapes(meshes,{angle: 25,// crease threshold°fit: {cx: 400,cy: 300,size: 440},// fit into a screen box});el.innerHTML=render(shapes,{yaw: 0.6,pitch: 0.35,f: 1400,cx: 400,cy: 300});

featureEdges(mesh) is exposed on its own if you want the raw edge list. Vertices are welded by position first, so meshes that split a shared edge across primitives still sort as one surface. No Draco, and geometry-only — textures and materials are ignored.

Formats:

InputFunctionNotes
glTF / GLBparseGLB(buffer)embedded buffers, node transforms; no Draco
OBJparseOBJ(text)fan-triangulated
STLparseSTL(buffer | text)binary or ASCII; the 3D-printing format
three.jsfromBufferGeometry(geo)reads the typed arrays; no three.js dependency
STEP / IGESfromOcct(result)via occt-import-js (OpenCASCADE WASM) — you bring the kernel; linework stays tiny

STEP is a trimmed-NURBS B-rep, not a mesh — tessellating it is a job for a real CAD kernel, so linework doesn't embed one. occt-import-js returns meshes that fromOcct() maps straight in, keeping the ~6 MB kernel an optional peer rather than a dependency.

Imported geometry is just shapes — so you layer paper-space annotations (overall dimensions, callout balloons, a title block) over an import exactly as you would a hand-authored scene. The live demo dimensions the lantern automatically from its mesh bounds and balloons its extreme features; toggle Annotate to see the annotation layer come and go over the same rotating model.

Coming from Zdog

Zdog is the closest thing to a predecessor, and its last npm release was v1.1.3 in January 2022. If you landed here looking for a maintained alternative, the mental model transfers — but two things differ in kind, not degree.

Zdog is pseudo-3D; this is true 3D. Zdog sorts by a single per-shape depth value, so shapes that interpenetrate resolve wrong and you nudge translate.z until it looks right. Here every vertex is transformed and shapes are depth-sorted per frame, with part() giving you explicit sort units and bias() for the rare tie you want to break by hand.

Zdog paints to canvas or SVG elements; this emits SVG strings. That difference is the whole point of the library: strings are server-renderable at build time, diffable in git, styleable from your own stylesheet, crawlable, and printable.

Zdoglinework
new Zdog.Illustration({element})sketch({ yaw, pitch, f, cx, cy }) — no canvas, no element
new Zdog.Box({...})s.box(x, y, w, h, z, dz)
new Zdog.Cylinder({...})s.cyl(centre, r, zNear, zFar)
new Zdog.Ellipse({...})s.disc(centre, z, r) / s.cap(...)
new Zdog.Shape({path: [...]})s.tube(w).M(...).Q(...) — multi-stroke, one sort unit
new Zdog.Anchor() for groupings.part(name, attrs, () => {...})
no text supports.note(text, point) — paper-space annotations, dimension lines, balloons
illo.rotate.y += 0.03; illo.updateRenderGraph()el.innerHTML = draw({ yaw, ... }) — rebuild the string, ~1 ms
renders to canvas or an SVG element treeemits an SVG string — server-renderable, diffable, printable

The trade is real and worth stating: Zdog's round-everything aesthetic and its canvas renderer are things this does not do. If you want soft, toy-like 3D, Zdog is still charming. If you want a drawing — hard edges, hairlines, callouts, a title block — this is built for that and nothing else.

Coordinates (read this once)

FieldMeaning
xright, in your SVG's user units
ydown — screen convention, not math convention
ztoward the viewer; negative recedes and depth-dims
view.yawrotation about the vertical axis through cx (radians)
view.pitchrotation about the horizontal axis through cy; positive looks down
view.fperspective focal distance — k = f/(f−z); larger = flatter
biasper-shape depth nudge for deliberate coplanar layering

Paper space: annotations (dimensions, balloons, title blocks) are strings appended after the sorted scene — they never rotate, exactly like a real drawing's notes. sketch.pt(p, z) projects model points so leaders can pin paper to model.

Known limitation (shared by every painter's-algorithm renderer): cyclic overlaps can't sort correctly — split long members into segments if you construct one.

Server-side rendering

render() is a pure string function. Static site generators can emit finished 3D-looking diagrams with zero client JS:

import{writeFileSync}from"node:fs";writeFileSync("diagram.svg",wrapInSvgTag(render(shapes,view)));

The lantern hero above is generated exactly this way — scripts/gen-import-demo.mjs imports the committed model and renders the SVG in Node (npm run images); the demo page runs the same code live. For a hand-authored server-side example, see docs/scene.js.

Install & test

npm i linework # ESM, types included
npm test# projection, parallax, paint order, culling,# sketch scoping, and feature-edge extraction

Compatibility

ESM-only (no CJS build), Node ≥ 18, zero runtime dependencies. Which entry runs where:

EntryRuns inNotes
linework · /helpers · /sketch · /importNode and browserpure functions; import uses TextDecoder/DataView, both universal
linework/orbitbrowser onlyuses requestAnimationFrame, matchMedia, performance

render() and the importers run server-side, so you can generate diagrams at build time (see Server-side rendering); only the drag-to-orbit helper needs a browser. Imported files are treated as untrusted input — see SECURITY.md for the parsing threat model.

Versioning: while 0.x, minor releases may contain breaking changes and patch releases won't. From 1.0, standard semver — a breaking change to the public API bumps the major. Releases publish from CI with provenance.

Contributing

Small, dependency-free, and test-driven on purpose — see CONTRIBUTING.md. Changes are tracked in CHANGELOG.md. Issues and PRs welcome.

Provenance

Extracted from Fitment — a "will that part fit your bike?" planner whose exploded service-manual drawings are rendered entirely by this engine, live-orbitable, with dimension callouts in paper space over the rotating model.

License

MIT © Isaac Rowntree

About

Tiny true-3D renderer for annotated technical drawings in SVG — rotate, project, depth-sort, emit strings. Zero dependencies.

Topics

Resources

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

linework

npmcilicense: MITzero dependencieslive demo

A tiny true-3D renderer for annotated technical drawings, output as plain SVG strings. Rotate → project → depth-sort → paint. Zero dependencies, ~180-line core, fully tested.

A street lantern imported from a glTF mesh and rendered by linework as feature-edge linework, orbiting

Every frame above is a fresh SVG string — 5,394 triangles reduced to 2,490 feature edges, then rotated, projected and depth-sorted from scratch in ~2 ms. The lantern was imported from a glTF mesh, and the whole loop was rendered by the library itself, in Node, with zero client JavaScript (npm run gif). On the live demo it orbits under your pointer — and you can drop your own model.

Why

The category is empty. WebGL libraries (three.js) make shaded surfaces easy and annotated linework painful — thin strokes, dash patterns, line-weight hierarchy, text callouts are all fights. Pseudo-3D toys (Zdog — last release 2022) can't do text or fine-grained depth sorting. Nothing ships "parametric technical illustration": exploded diagrams, dimension lines, balloons, title blocks. This does exactly that, and nothing else.

  • The classic pipeline, honestly implemented — 3D points → yaw/pitch rotation → perspective projection → painter's-algorithm depth sorting per frame → SVG string. Paint order is computed, never authored.
  • Shapes built for drawings, not games — multi-stroke paths (hollow-tube outlines as one shape), discs that project to correct ellipses, backface-culled boxes, per-object sorting for animated parts.
  • SVG strings are the point — themeable with CSS variables, crawlable, printable, accessible, and renderable server-side at build time.
  • Styling is yours — the library emits class names you define; it never dictates a look.

The sketch layer — DX is a feature

Authoring should read like drafting, not like assembling tuples. Context blocks scope parts, tags and layering over everything drawn inside them:

import{sketch,scene}from"linework/sketch";consts=sketch({yaw: 0.5,pitch: 0.16,f: 1500,cx: 460,cy: 320});s.box(300,380,320,42,40,80);// base plates.part("housing",'class="prt"',()=>{// one <g>, one sort units.cyl([460,218],70,34,-34,"ink");// bearing bodys.bias(0.6,()=>s.cap([460,218],34,32,"ink"));// bore, layered above});s.tube(9).M([180,400]).Q([300,420],20,[420,340],10);// hollow frame tubes.note("320 mm",[460,452]);// paper-space annotationel.innerHTML=s.render();// depth-sorted SVG

For animation, scene() gives you the frame-loop idiom — define once, replay with a new view per frame:

constdraw=scene((s,{ explode })=>{/* build with s.* */});el.innerHTML=draw({ yaw, pitch,f: 1500,cx: 460,cy: 320},{ explode });// ~1 ms for a few hundred shapes — drag-to-orbit rebuilds are free

Prefer bare metal? linework exports the raw Shape types + render()/xform(), and linework/helpers sits in between.

Import a 3D model → a technical drawing

linework/import turns a 3D mesh — glTF/GLB, OBJ, STL, or a three.js BufferGeometry — into linework strokes. A shaded model carries no lines — its form lives in where the surface bends — so it recovers exactly the lines a draftsperson would draw: the outline and the hard creases, nothing from the smooth interior of a face. The result drops straight into render() and rotates like any other scene.

(That lantern in the header is exactly this: a CC0 glTF — 5,394 triangles of shaded mesh → ~2,500 feature edges → rotatable line drawing, in one meshToShapes() call. Drop your own .glb on the demo.)

import{parseGLB,meshToShapes}from"linework/import";import{render}from"linework";constmeshes=parseGLB(awaitfile.arrayBuffer());// parseOBJ · parseSTL · fromBufferGeometryconstshapes=meshToShapes(meshes,{angle: 25,// crease threshold°fit: {cx: 400,cy: 300,size: 440},// fit into a screen box});el.innerHTML=render(shapes,{yaw: 0.6,pitch: 0.35,f: 1400,cx: 400,cy: 300});

featureEdges(mesh) is exposed on its own if you want the raw edge list. Vertices are welded by position first, so meshes that split a shared edge across primitives still sort as one surface. No Draco, and geometry-only — textures and materials are ignored.

Formats:

InputFunctionNotes
glTF / GLBparseGLB(buffer)embedded buffers, node transforms; no Draco
OBJparseOBJ(text)fan-triangulated
STLparseSTL(buffer | text)binary or ASCII; the 3D-printing format
three.jsfromBufferGeometry(geo)reads the typed arrays; no three.js dependency
STEP / IGESfromOcct(result)via occt-import-js (OpenCASCADE WASM) — you bring the kernel; linework stays tiny

STEP is a trimmed-NURBS B-rep, not a mesh — tessellating it is a job for a real CAD kernel, so linework doesn't embed one. occt-import-js returns meshes that fromOcct() maps straight in, keeping the ~6 MB kernel an optional peer rather than a dependency.

Imported geometry is just shapes — so you layer paper-space annotations (overall dimensions, callout balloons, a title block) over an import exactly as you would a hand-authored scene. The live demo dimensions the lantern automatically from its mesh bounds and balloons its extreme features; toggle Annotate to see the annotation layer come and go over the same rotating model.

Coming from Zdog

Zdog is the closest thing to a predecessor, and its last npm release was v1.1.3 in January 2022. If you landed here looking for a maintained alternative, the mental model transfers — but two things differ in kind, not degree.

Zdog is pseudo-3D; this is true 3D. Zdog sorts by a single per-shape depth value, so shapes that interpenetrate resolve wrong and you nudge translate.z until it looks right. Here every vertex is transformed and shapes are depth-sorted per frame, with part() giving you explicit sort units and bias() for the rare tie you want to break by hand.

Zdog paints to canvas or SVG elements; this emits SVG strings. That difference is the whole point of the library: strings are server-renderable at build time, diffable in git, styleable from your own stylesheet, crawlable, and printable.

Zdoglinework
new Zdog.Illustration({element})sketch({ yaw, pitch, f, cx, cy }) — no canvas, no element
new Zdog.Box({...})s.box(x, y, w, h, z, dz)
new Zdog.Cylinder({...})s.cyl(centre, r, zNear, zFar)
new Zdog.Ellipse({...})s.disc(centre, z, r) / s.cap(...)
new Zdog.Shape({path: [...]})s.tube(w).M(...).Q(...) — multi-stroke, one sort unit
new Zdog.Anchor() for groupings.part(name, attrs, () => {...})
no text supports.note(text, point) — paper-space annotations, dimension lines, balloons
illo.rotate.y += 0.03; illo.updateRenderGraph()el.innerHTML = draw({ yaw, ... }) — rebuild the string, ~1 ms
renders to canvas or an SVG element treeemits an SVG string — server-renderable, diffable, printable

The trade is real and worth stating: Zdog's round-everything aesthetic and its canvas renderer are things this does not do. If you want soft, toy-like 3D, Zdog is still charming. If you want a drawing — hard edges, hairlines, callouts, a title block — this is built for that and nothing else.

Coordinates (read this once)

FieldMeaning
xright, in your SVG's user units
ydown — screen convention, not math convention
ztoward the viewer; negative recedes and depth-dims
view.yawrotation about the vertical axis through cx (radians)
view.pitchrotation about the horizontal axis through cy; positive looks down
view.fperspective focal distance — k = f/(f−z); larger = flatter
biasper-shape depth nudge for deliberate coplanar layering

Paper space: annotations (dimensions, balloons, title blocks) are strings appended after the sorted scene — they never rotate, exactly like a real drawing's notes. sketch.pt(p, z) projects model points so leaders can pin paper to model.

Known limitation (shared by every painter's-algorithm renderer): cyclic overlaps can't sort correctly — split long members into segments if you construct one.

Server-side rendering

render() is a pure string function. Static site generators can emit finished 3D-looking diagrams with zero client JS:

import{writeFileSync}from"node:fs";writeFileSync("diagram.svg",wrapInSvgTag(render(shapes,view)));

The lantern hero above is generated exactly this way — scripts/gen-import-demo.mjs imports the committed model and renders the SVG in Node (npm run images); the demo page runs the same code live. For a hand-authored server-side example, see docs/scene.js.

Install & test

npm i linework # ESM, types included
npm test# projection, parallax, paint order, culling,# sketch scoping, and feature-edge extraction

Compatibility

ESM-only (no CJS build), Node ≥ 18, zero runtime dependencies. Which entry runs where:

EntryRuns inNotes
linework · /helpers · /sketch · /importNode and browserpure functions; import uses TextDecoder/DataView, both universal
linework/orbitbrowser onlyuses requestAnimationFrame, matchMedia, performance

render() and the importers run server-side, so you can generate diagrams at build time (see Server-side rendering); only the drag-to-orbit helper needs a browser. Imported files are treated as untrusted input — see SECURITY.md for the parsing threat model.

Versioning: while 0.x, minor releases may contain breaking changes and patch releases won't. From 1.0, standard semver — a breaking change to the public API bumps the major. Releases publish from CI with provenance.

Contributing

Small, dependency-free, and test-driven on purpose — see CONTRIBUTING.md. Changes are tracked in CHANGELOG.md. Issues and PRs welcome.

Provenance

Extracted from Fitment — a "will that part fit your bike?" planner whose exploded service-manual drawings are rendered entirely by this engine, live-orbitable, with dimension callouts in paper space over the rotating model.

License

MIT © Isaac Rowntree

About

Tiny true-3D renderer for annotated technical drawings in SVG — rotate, project, depth-sort, emit strings. Zero dependencies.

Topics

Resources

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

Repository files navigation

linework

npmcilicense: MITzero dependencieslive demo

A tiny true-3D renderer for annotated technical drawings, output as plain SVG strings. Rotate → project → depth-sort → paint. Zero dependencies, ~180-line core, fully tested.

A street lantern imported from a glTF mesh and rendered by linework as feature-edge linework, orbiting

Every frame above is a fresh SVG string — 5,394 triangles reduced to 2,490 feature edges, then rotated, projected and depth-sorted from scratch in ~2 ms. The lantern was imported from a glTF mesh, and the whole loop was rendered by the library itself, in Node, with zero client JavaScript (npm run gif). On the live demo it orbits under your pointer — and you can drop your own model.

Why

The category is empty. WebGL libraries (three.js) make shaded surfaces easy and annotated linework painful — thin strokes, dash patterns, line-weight hierarchy, text callouts are all fights. Pseudo-3D toys (Zdog — last release 2022) can't do text or fine-grained depth sorting. Nothing ships "parametric technical illustration": exploded diagrams, dimension lines, balloons, title blocks. This does exactly that, and nothing else.

  • The classic pipeline, honestly implemented — 3D points → yaw/pitch rotation → perspective projection → painter's-algorithm depth sorting per frame → SVG string. Paint order is computed, never authored.
  • Shapes built for drawings, not games — multi-stroke paths (hollow-tube outlines as one shape), discs that project to correct ellipses, backface-culled boxes, per-object sorting for animated parts.
  • SVG strings are the point — themeable with CSS variables, crawlable, printable, accessible, and renderable server-side at build time.
  • Styling is yours — the library emits class names you define; it never dictates a look.

The sketch layer — DX is a feature

Authoring should read like drafting, not like assembling tuples. Context blocks scope parts, tags and layering over everything drawn inside them:

import{sketch,scene}from"linework/sketch";consts=sketch({yaw: 0.5,pitch: 0.16,f: 1500,cx: 460,cy: 320});s.box(300,380,320,42,40,80);// base plates.part("housing",'class="prt"',()=>{// one <g>, one sort units.cyl([460,218],70,34,-34,"ink");// bearing bodys.bias(0.6,()=>s.cap([460,218],34,32,"ink"));// bore, layered above});s.tube(9).M([180,400]).Q([300,420],20,[420,340],10);// hollow frame tubes.note("320 mm",[460,452]);// paper-space annotationel.innerHTML=s.render();// depth-sorted SVG

For animation, scene() gives you the frame-loop idiom — define once, replay with a new view per frame:

constdraw=scene((s,{ explode })=>{/* build with s.* */});el.innerHTML=draw({ yaw, pitch,f: 1500,cx: 460,cy: 320},{ explode });// ~1 ms for a few hundred shapes — drag-to-orbit rebuilds are free

Prefer bare metal? linework exports the raw Shape types + render()/xform(), and linework/helpers sits in between.

Import a 3D model → a technical drawing

linework/import turns a 3D mesh — glTF/GLB, OBJ, STL, or a three.js BufferGeometry — into linework strokes. A shaded model carries no lines — its form lives in where the surface bends — so it recovers exactly the lines a draftsperson would draw: the outline and the hard creases, nothing from the smooth interior of a face. The result drops straight into render() and rotates like any other scene.

(That lantern in the header is exactly this: a CC0 glTF — 5,394 triangles of shaded mesh → ~2,500 feature edges → rotatable line drawing, in one meshToShapes() call. Drop your own .glb on the demo.)

import{parseGLB,meshToShapes}from"linework/import";import{render}from"linework";constmeshes=parseGLB(awaitfile.arrayBuffer());// parseOBJ · parseSTL · fromBufferGeometryconstshapes=meshToShapes(meshes,{angle: 25,// crease threshold°fit: {cx: 400,cy: 300,size: 440},// fit into a screen box});el.innerHTML=render(shapes,{yaw: 0.6,pitch: 0.35,f: 1400,cx: 400,cy: 300});

featureEdges(mesh) is exposed on its own if you want the raw edge list. Vertices are welded by position first, so meshes that split a shared edge across primitives still sort as one surface. No Draco, and geometry-only — textures and materials are ignored.

Formats:

InputFunctionNotes
glTF / GLBparseGLB(buffer)embedded buffers, node transforms; no Draco
OBJparseOBJ(text)fan-triangulated
STLparseSTL(buffer | text)binary or ASCII; the 3D-printing format
three.jsfromBufferGeometry(geo)reads the typed arrays; no three.js dependency
STEP / IGESfromOcct(result)via occt-import-js (OpenCASCADE WASM) — you bring the kernel; linework stays tiny

STEP is a trimmed-NURBS B-rep, not a mesh — tessellating it is a job for a real CAD kernel, so linework doesn't embed one. occt-import-js returns meshes that fromOcct() maps straight in, keeping the ~6 MB kernel an optional peer rather than a dependency.

Imported geometry is just shapes — so you layer paper-space annotations (overall dimensions, callout balloons, a title block) over an import exactly as you would a hand-authored scene. The live demo dimensions the lantern automatically from its mesh bounds and balloons its extreme features; toggle Annotate to see the annotation layer come and go over the same rotating model.

Coming from Zdog

Zdog is the closest thing to a predecessor, and its last npm release was v1.1.3 in January 2022. If you landed here looking for a maintained alternative, the mental model transfers — but two things differ in kind, not degree.

Zdog is pseudo-3D; this is true 3D. Zdog sorts by a single per-shape depth value, so shapes that interpenetrate resolve wrong and you nudge translate.z until it looks right. Here every vertex is transformed and shapes are depth-sorted per frame, with part() giving you explicit sort units and bias() for the rare tie you want to break by hand.

Zdog paints to canvas or SVG elements; this emits SVG strings. That difference is the whole point of the library: strings are server-renderable at build time, diffable in git, styleable from your own stylesheet, crawlable, and printable.

Zdoglinework
new Zdog.Illustration({element})sketch({ yaw, pitch, f, cx, cy }) — no canvas, no element
new Zdog.Box({...})s.box(x, y, w, h, z, dz)
new Zdog.Cylinder({...})s.cyl(centre, r, zNear, zFar)
new Zdog.Ellipse({...})s.disc(centre, z, r) / s.cap(...)
new Zdog.Shape({path: [...]})s.tube(w).M(...).Q(...) — multi-stroke, one sort unit
new Zdog.Anchor() for groupings.part(name, attrs, () => {...})
no text supports.note(text, point) — paper-space annotations, dimension lines, balloons
illo.rotate.y += 0.03; illo.updateRenderGraph()el.innerHTML = draw({ yaw, ... }) — rebuild the string, ~1 ms
renders to canvas or an SVG element treeemits an SVG string — server-renderable, diffable, printable

The trade is real and worth stating: Zdog's round-everything aesthetic and its canvas renderer are things this does not do. If you want soft, toy-like 3D, Zdog is still charming. If you want a drawing — hard edges, hairlines, callouts, a title block — this is built for that and nothing else.

Coordinates (read this once)

FieldMeaning
xright, in your SVG's user units
ydown — screen convention, not math convention
ztoward the viewer; negative recedes and depth-dims
view.yawrotation about the vertical axis through cx (radians)
view.pitchrotation about the horizontal axis through cy; positive looks down
view.fperspective focal distance — k = f/(f−z); larger = flatter
biasper-shape depth nudge for deliberate coplanar layering

Paper space: annotations (dimensions, balloons, title blocks) are strings appended after the sorted scene — they never rotate, exactly like a real drawing's notes. sketch.pt(p, z) projects model points so leaders can pin paper to model.

Known limitation (shared by every painter's-algorithm renderer): cyclic overlaps can't sort correctly — split long members into segments if you construct one.

Server-side rendering

render() is a pure string function. Static site generators can emit finished 3D-looking diagrams with zero client JS:

import{writeFileSync}from"node:fs";writeFileSync("diagram.svg",wrapInSvgTag(render(shapes,view)));

The lantern hero above is generated exactly this way — scripts/gen-import-demo.mjs imports the committed model and renders the SVG in Node (npm run images); the demo page runs the same code live. For a hand-authored server-side example, see docs/scene.js.

Install & test

npm i linework # ESM, types included
npm test# projection, parallax, paint order, culling,# sketch scoping, and feature-edge extraction

Compatibility

ESM-only (no CJS build), Node ≥ 18, zero runtime dependencies. Which entry runs where:

EntryRuns inNotes
linework · /helpers · /sketch · /importNode and browserpure functions; import uses TextDecoder/DataView, both universal
linework/orbitbrowser onlyuses requestAnimationFrame, matchMedia, performance

render() and the importers run server-side, so you can generate diagrams at build time (see Server-side rendering); only the drag-to-orbit helper needs a browser. Imported files are treated as untrusted input — see SECURITY.md for the parsing threat model.

Versioning: while 0.x, minor releases may contain breaking changes and patch releases won't. From 1.0, standard semver — a breaking change to the public API bumps the major. Releases publish from CI with provenance.

Contributing

Small, dependency-free, and test-driven on purpose — see CONTRIBUTING.md. Changes are tracked in CHANGELOG.md. Issues and PRs welcome.

Provenance

Extracted from Fitment — a "will that part fit your bike?" planner whose exploded service-manual drawings are rendered entirely by this engine, live-orbitable, with dimension callouts in paper space over the rotating model.

License

MIT © Isaac Rowntree

About

Tiny true-3D renderer for annotated technical drawings in SVG — rotate, project, depth-sort, emit strings. Zero dependencies.

Topics

Resources

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages