cad-blueprint

Lightweight parametric 2D CAD engine for configurators: layers with hatches, GOST text and dimension styles, primitives, dimensions, blocks, viewports. SVG and DXF export, DXF import, compact JSON for databases, pan & zoom viewer, and a Three.js bridge.

Installation

pnpm add cad-blueprint
pnpm add three   # only needed for cad-blueprint/three
Entry pointContents
cad-blueprintcore: settings, layers, styles, primitives, dimensions, blocks, document, SVG, DXF, formats. DOM-free.
cad-blueprint/svg, /dxf, /formatindividual modules for smaller bundles
cad-blueprint/viewerCadViewer: pan & zoom viewer with layer toggles (requires DOM)
cad-blueprint/threecontours → THREE.Shape / ExtrudeGeometry, mesh sections
cad-blueprint/iifebundle for <script>: window.CadBlueprint

Quick start

import { CadDocument, CadPath, polygon, insert, dimLinear, dimChain, renderSvg, exportDxf, stringifyDocument } from 'cad-blueprint';

const doc = new CadDocument({ gost: true, settings: { scale: '1:10' } }); // GOST font, text and dimension styles
doc.layers.create('Outline', { color: '#0f172a', lineWeight: 0.5 });
doc.layers.create('Dimensions', { color: '#047857', lineWeight: 0.18 });

const tread = CadPath.start(0, 0).right(300).up(40).left(300).close().filletAll(5).build();
doc.blocks.define('Tread', [polygon(tread, { layer: 'Outline' })]);

doc.addSheet('Stairs', [
  ...[0, 1, 2, 3].map((i) => insert('Tread', [i * 280, i * 170])),
  dimChain([[0, 0], [280, 0], [560, 0], [840, 0]], { offset: -120, layer: 'Dimensions' }),
]);

const svg = renderSvg(doc);           // <svg> string sized in paper mm
const dxf = exportDxf(doc);           // DXF R2007, UTF-8
const json = stringifyDocument(doc);  // compact JSON for a database

Axes, angles, units

Layers & styles

doc.layers.create('Section', { color: '#1e3a8a', lineWeight: 0.5, hatch: 'steel-45' });
doc.layers.create('Axes', { color: '#dc2626', lineWeight: 0.18, lineType: 'dashdot' });
doc.layers.create('Mesh', {
  hatch: createHatchStyle({ families: [{ angle: 45, spacing: 3 }, { angle: 135, spacing: 3 }], background: '#f0fdfa' }),
});
doc.layers.update('Axes', { visible: false });

doc.dimStyles.update('GOST', { terminatorType: 'tick', textPosition: 'above', textOrientation: 'aligned' });

Hatches: steel-45, board-45, concrete, wall-45 and custom ones via createHatchStyle. An entity with fill: 'hatch' uses its layer's hatch. Terminators: arrow-closed, arrow-open, tick, dot, circle, none.

Primitives & CadPath

line([0, 0], [100, 0], { layer: 'Axes' });
rect(0, 0, 300, 200, { cornerRadius: 20, fill: 'hatch' });
circle([50, 50], 20);
arc([0, 0], 70, 20, 240);                  // center, radius, start & end angle
arcThrough(a, b, c);                      // arc through three points
ellipse([0, 0], 110, 65, { rotationDeg: 25 });
polyline(points); polygon(points, { holes: [hole] });
spline(points, { degree: 3 }); bezier(controlPoints); fitBezier(throughPoints);
text([0, 0], 'Label', { height: 3.5, anchor: 'middle-left' });
mtext([0, 0], 'Line 1\nLine 2', { height: 3.5 });
breakLine(a, b, { waves: 3 }); zigzagBreakLine(a, b);  // GOST 2.303 break lines

CadPath builds contours using turtle graphics with fillets and chamfers. Result fits polygon and polyline:

const profile = CadPath.start(0, 0)
  .right(80).up(60).left(25).down(18).left(30).up(18).left(25)
  .close().filletAll(4).build();

CadPath.start(0, 0).right(700).up(120).polar(220, 135).left(200).fillet(40).close().build();
CadPath.start(0, 0).right(80).arcTo(180, 200, { tangent: true }).build();

Dimensions & leaders

dimLinear(a, b, { offset: -60 });                     // horizontal by default
dimLinear(a, b, { direction: 'vertical', offset: 40 });
dimAligned(a, b, { offset: -30 });                    // parallel to segment
dimChain([p0, p1, p2, p3], { offset: -70, texts: [null, '<> (step)', null] });
dimBaseline(p0, [p1, p2, p3], { offset: -150 });
dimAngular(vertex, a, b, { radius: 110 });
dimDiameter(center, r, { angleDeg: 35 }); dimRadius(center, r, { angleDeg: -45 });
leader([[600, 60], [780, 220]], 'Steel St3sp, t = 8 mm');

<> inserts the measured value. If text does not fit between terminators, it is placed outside automatically.

Blocks & viewports

doc.blocks.define('Profile', [polygon(profile, { layer: 'Section', fill: 'hatch' })], { description: '80×60' });

insert('Profile', [1150, 0], { scaleX: -1, rotationDeg: 90, layer: 'Axes' }); // entities on layer "0" take the insert layer

viewport([insert('Profile', [0, 0]), dimLinear([0, 0], [80, 0], { offset: -14 })], {
  position: [150, -560],   // viewport position on the sheet
  target: [40, 30],        // model point at the center
  scale: '1:2',
  clip: { minX: -20, minY: -32, maxX: 112, maxY: 72 },
  frame: true,
  title: 'Detail A (1:2)',
});

Inside a viewport, text and arrows use its own scale, so on paper they match the outside sizes.

Document & sheets

const doc = new CadDocument({ gost: true, settings: { scale: '1:20', annotationScale: 'auto', padding: [12, 16] } });
const sheet = doc.addSheet('Facade', entities, 'facade'); // name, entities, id
sheet.add(e1, e2); sheet.remove('id'); sheet.replace('id', e); sheet.find('id');
doc.audit();     // missing layers, styles, blocks, fonts
doc.context();   // render context for custom renderers and bounds
entitiesBounds(sheet.entities, doc.context());

JSON & .vcad

const json = stringifyDocument(doc);   // tuple-JSON, much smaller than JSON.stringify(doc)
const copy = decodeDocument(json);     // full validation

const bytes = packVcad(doc, { assets: { 'fonts/gost.woff2': font }, meta: { order: 42 } }); // zip
const { document, assets, manifest } = unpackVcad(bytes);
const lib = unpackBlockLibrary(packBlockLibrary(doc.blocks));

SVG

renderSvg(doc, { sheet: 'facade', background: '#fff' });    // size: 'paper' | 'none' | { width }
renderSvg(doc, { hiddenLayers: 'hide' });                    // hidden layers with display:none

Blocks are emitted as <symbol>/<use>, hatches as <pattern>. Text in mirrored inserts stays readable (like MIRRTEXT=0).

DXF: export & import

exportDxf(doc, { sheet: 'facade' });                  // R2007, UTF-8, true color
exportDxf(doc, { version: 'R2000' });                 // for legacy software, non-ASCII as \U+XXXX

const { block, layers, warnings, fileUnits } = importDxf(fileBytes, { name: 'Profile', fill: 'hatch', basePoint: 'min' });
for (const l of layers) if (!doc.layers.has(l.name)) doc.layers.create(l.name, l);
doc.blocks.add(block);
doc.addSheet('Import', [insert('Profile', [0, 0])]);
Dimensions in DXF are written exploded (LINE, SOLID, TEXT), viewports as _VIEWPORT<n> blocks without clipping. Import: LINE, POINT, CIRCLE, ARC, ELLIPSE, LWPOLYLINE, POLYLINE, SPLINE, SOLID, TEXT, MTEXT, INSERT. Units come from $INSUNITS, nested closed contours become holes.

Viewer

import { CadViewer } from 'cad-blueprint/viewer';

const viewer = new CadViewer(container, doc, {
  sheet: 'facade', toolbar: false, background: 'transparent', paper: '#fff', fileName: 'order-42',
});
viewer.setSheet('plan');
viewer.setDocument(newDoc, { keepView: true });    // rebuild without resetting zoom
viewer.setLayerVisible('Axes', false); viewer.isolateLayer('Outline'); viewer.showAllLayers();
viewer.fitToView(); viewer.zoomIn(); viewer.zoomOut();
viewer.downloadSvg(); viewer.downloadDxf(); viewer.downloadVcad();
viewer.on((e) => {
  if (e.type === 'select') console.log(e.id, e.layer, e.point);  // click on an entity with id
  if (e.type === 'view') console.log(e.zoom);
});
viewer.destroy();

Wheel zooms to the cursor, drag pans, double-click fits. Pinch works on touch screens. Source can be a document, compact JSON or .vcad bytes.

No bundler (IIFE, Filament)

<script src="/js/cad-blueprint.iife.js"></script>
<div id="drawing" style="height: 480px"></div>
<script>
  CadBlueprint.mountCadViewer(document.getElementById('drawing'), drawingJson, { toolbar: true });
</script>

In Filament / Alpine: x-init="CadBlueprint.mountCadViewer($el, @js($record->drawing_json), { toolbar: true })" and wire:ignore on the container.

Three.js: 3D & sections

import { blockToExtrudeGeometry, sectionObject, sectionToBlock } from 'cad-blueprint/three';
import { Mesh, Plane, Vector3 } from 'three';

const mesh = new Mesh(blockToExtrudeGeometry(doc.blocks.require('Profile'), { depth: 400 })); // holes → shape.holes

const section = sectionObject(scene, new Plane(new Vector3(0, 0, 1), -180)); // plane Z = 180
doc.blocks.add(sectionToBlock(section, 'Section A-A', { layer: 'Section', fill: 'hatch' }));
sheet.add(insert('Section A-A', [0, 0]));

section.loops holds closed loops in plane coordinates, section.basis sets its origin and axes. For normal (0, 0, 1), the section X axis matches world X and Y matches world Y. In the demo, you can drag the red plane: on each move the section is recomputed and the "3D Section" sheet is rebuilt.