Skip to content
cadkithome

Build a browser viewer with cadkit-wasm

This guide builds a small viewer: open a local file, render it as SVG, click to identify an entity. The file is parsed in the browser and never uploaded. The demo is a fuller viewer built on the same package.

Three rules shape the design:

  1. Parse off the main thread. Reading a large drawing takes time and memory. In a Web Worker the page stays responsive, and a worker can be terminated.
  2. Bound every output. toSvgBounded and pickEntityBounded take byte budgets and either return a complete result or throw limit_exceeded; they never return a truncated one.
  3. Recover by starting over. After limit_exceeded, or a WebAssembly.RuntimeError trap, terminate the worker and create a new one: that is the only way to release a WebAssembly memory that has grown.
worker.js
// worker.js: parsing, rendering and picking run here, never on the main thread.
import init, { read } from "cadkit-wasm";
const MIB = 1024 * 1024;
const ready = init(); // fetches and instantiates cadkit_wasm_bg.wasm once
let doc = null;
self.onmessage = async ({ data }) => {
await ready;
try {
if (data.type === "open") {
doc?.free();
doc = null;
doc = read(new Uint8Array(data.bytes), { maxInputBytes: 64 * MIB, maxObjects: 2_000_000 });
// A complete SVG within the budget, or a limit_exceeded error; raster images left out.
const svg = doc.toSvgBounded({ widthPx: 1600, maxOutputBytes: 32 * MIB, images: false });
self.postMessage({ type: "opened", info: doc.info(), layers: doc.layers(), svg });
} else if (data.type === "pick" && doc) {
// World XY coordinates and tolerance in drawing units; metadata capped at 16 KiB.
const hit = doc.pickEntityBounded(0, data.x, data.y, data.tolerance, { maxOutputBytes: 16 * 1024 });
self.postMessage({ type: "picked", hit });
}
} catch (error) {
// error.kind: unknown_format, unsupported, invalid, truncated, limit_exceeded, ...
// Without a kind it is a WebAssembly trap: this instance is no longer usable.
self.postMessage({ type: "error", kind: error.kind ?? "trap", message: String(error.message ?? error) });
}
};
main.js
// main.js: UI only. The worker owns the WebAssembly instance and the parsed document.
const input = document.querySelector("#file");
const view = document.querySelector("#drawing");
const status = document.querySelector("#status");
let worker = startWorker();
function startWorker() {
const w = new Worker(new URL("./worker.js", import.meta.url), { type: "module" });
w.onmessage = ({ data }) => {
if (data.type === "opened") {
show(data.svg);
status.textContent = `${data.info.format} ${data.info.version}: ${data.info.models[0]?.entities ?? 0} entities, ${data.layers.length} layers`;
} else if (data.type === "picked") {
status.textContent = data.hit ? `${data.hit.kind} on ${data.hit.layer}` : "nothing here";
} else if (data.type === "error") {
status.textContent = `Could not open the file (${data.kind}): ${data.message}`;
// After a limit error or a trap, start over with a fresh WebAssembly memory.
if (data.kind === "limit_exceeded" || data.kind === "trap") {
worker.terminate();
worker = startWorker();
}
}
};
return w;
}
function show(svgText) {
const svg = new DOMParser().parseFromString(svgText, "image/svg+xml").documentElement;
if (svg.nodeName !== "svg") throw new Error("not an SVG document");
svg.removeAttribute("width"); // scale with the container; the viewBox keeps the drawing's units
svg.removeAttribute("height");
view.replaceChildren(document.importNode(svg, true));
}
input.addEventListener("change", async () => {
const file = input.files?.[0];
if (!file) return;
status.textContent = `Reading ${file.name}...`;
const bytes = await file.arrayBuffer();
worker.postMessage({ type: "open", bytes }, [bytes]); // transfer, do not copy
});
view.addEventListener("click", (event) => {
const svg = view.querySelector("svg");
const matrix = svg?.getScreenCTM()?.inverse();
if (!matrix) return;
// The SVG viewBox is in drawing units with Y pointing down: world Y is the negated SVG Y.
const p = new DOMPoint(event.clientX, event.clientY).matrixTransform(matrix);
const unitsPerPixel = 1 / (svg.getScreenCTM()?.a || 1);
worker.postMessage({ type: "pick", x: p.x, y: -p.y, tolerance: 4 * unitsPerPixel });
});
index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Drawing viewer</title>
<script type="module" src="./main.js"></script>
</head>
<body>
<label>Open a drawing <input id="file" type="file" accept=".dwg,.dgn,.dxf,.gml" /></label>
<p id="status" role="status"></p>
<div id="drawing"></div>
</body>
</html>

new Worker(new URL("./worker.js", import.meta.url), { type: "module" }) is the form bundlers such as Vite recognise: they bundle the worker and copy cadkit_wasm_bg.wasm. Without a bundler, import cadkit_wasm.js from a served copy of node_modules/cadkit-wasm/web/ instead of the bare cadkit-wasm specifier, because module workers do not use the page’s import map.

The SVG viewBox is in drawing units with Y pointing down, so a click maps to drawing coordinates through the inverse screen matrix of the <svg> element, with Y negated. pickEntityBounded(model, x, y, tolerance, options) returns the closest visible entity within tolerance drawing units, or null. It measures exact distances to lines and circular arcs, samples other curves and uses bounding boxes for annotations and hatches. It is a selection aid, not CAD snapping. The result holds the index, id, layer, kind, colour, bounding box, distance and short previews of text and attributes, capped by maxOutputBytes (at most 64 KiB); truncated says whether a preview was shortened. Layer and kind filters (excludedLayers, excludedKinds) let picking follow what the viewer shows.

WebAssembly needs 'wasm-unsafe-eval' in script-src; 'unsafe-eval' is not needed. Module workers need worker-src 'self'. A policy for the files above:

Content-Security-Policy: default-src 'self'; script-src 'self' 'wasm-unsafe-eval'; worker-src 'self'; img-src 'self' blob: data:; style-src 'self'; frame-ancestors 'none'

The SVG is inserted into the page so its layer groups (data-layer) and coordinates are available to script. With a policy like this one, inline scripts and event-handler attributes cannot run, whatever a drawing contains. When you need no interaction, show the SVG as an <img> from a blob: URL instead, as in the JavaScript quick start: images run no scripts and load nothing.