Embeddable 2D Sketcher
This document covers the iframe-based Sketcher2DEmbed API for embedding the 2D sketcher in another app.
Demo Page
- Hosted examples index: https://BREP.io/apiExamples/index.html
- Hosted demo: https://BREP.io/apiExamples/Embeded_2D_Sketcher.html
- Repo demo page: apiExamples/Embeded_2D_Sketcher.html
- Source on GitHub: apiExamples/Embeded_2D_Sketcher.html
Import
Package usage:
import { Sketcher2DEmbed } from "brep-io-kernel/Sketcher2D";
// or: import { Sketcher2DEmbed } from "brep-io-kernel";Local repo/dev usage:
import { Sketcher2DEmbed } from "/src/Sketcher2D.js";Create and Mount
const sketcher = new Sketcher2DEmbed({
mountTo: "#sketch-host",
width: "100%",
height: "560px",
geometryColor: "#ffd400",
pointColor: "#8bc5ff",
constraintColor: "#6aa8ff",
backgroundColor: "#0b0f14",
pointSizePx: 10,
curveThicknessPx: 2,
sidebarExpanded: false,
gridVisible: true,
gridSpacing: 1,
cssText: ".sketch-dims .dim-label { border-color: #4f8cff !important; }",
onChange: (sketch, payload) => console.log("changed", sketch, payload),
onFinished: (sketch, payload) => console.log("finished", sketch, payload),
onCancelled: (payload) => console.log("cancelled", payload),
});
const iframe = await sketcher.mount(); // uses mountTo/containerOr pass a host element directly:
const host = document.getElementById("sketch-host");
await sketcher.mount(host);Runtime API
await sketcher.waitUntilReady();
await sketcher.setTheme({
geometryColor: "#ff5a00",
pointColor: "#98fb98",
constraintColor: "#00ff00",
backgroundColor: "#000000",
pointSizePx: 12,
curveThicknessPx: 2.5,
});
await sketcher.setSidebarExpanded(false);
await sketcher.setGrid({ visible: true, spacing: 2.5 });
await sketcher.setCss("#main-toolbar { background: #111 !important; }");
const sketch = await sketcher.getSketch();
await sketcher.setSketch(sketch);
const cachedSketch = await sketcher.getSketch({ preferCached: true });
const svg = await sketcher.exportSVG({
flipY: true,
precision: 3,
stroke: "#111111",
strokeWidth: 1.5,
fill: "none",
padding: 12,
curveResolution: 64,
});
const dxf = await sketcher.exportDXF({
units: "mm",
curveResolution: 64,
});
const poly3d = await sketcher.export3DPolylines({
curveResolution: 64,
origin: [0, 0, 0],
xAxis: [1, 0, 0],
yAxis: [0, 1, 0],
});
await sketcher.destroy();Properties
sketcher.iframe: iframe element aftermount(), otherwisenull.sketcher.instanceId: resolved instance id used for the message channel.
Constructor Options
mountToorcontainer: host selector or DOM element for iframe insertion.width,height: iframe size (defaults:100%,520px).title: iframe title attribute (default:BREP Sketcher 2D).iframeClassName: class applied to iframe element.iframeStyle: inline style object merged into iframe styles.iframeAttributes: extra iframe attributes map.initialSketch: initial sketch JSON loaded on init.cssText: custom CSS injected into the iframe document.geometryColor: default curve/edge color.pointColor: default point/handle color.constraintColor: default constraint glyph/dimension color.backgroundColor: iframe sketch viewport background.pointSizePxorpointSize: point handle size in pixels.curveThicknessPxorcurveThickness: curve stroke thickness in pixels.sidebarExpanded: initial sidebar state (true/false, defaultfalse).gridVisible: show/hide sketch grid (true/false, defaultfalse).gridSpacing: grid cell spacing in sketch units (default1).showGrid: alias forgridVisible.onChange(sketch, payload): fired when sketch changes.onFinished(sketch, payload): fired when user presses Finish.onCancelled(payload): fired when user presses Cancel.onFinish: alias ofonFinished.onCanceled: alias ofonCancelled.channel: postMessage channel id (advanced; defaultbrep:sketcher2d).instanceId: explicit iframe instance id.targetOrigin: postMessage target origin (default*).requestTimeoutMs: request timeout in milliseconds (default12000).frameModuleUrl: module URL used by the iframe to importbootSketcher2DFrame(advanced; defaults to current module URL).
Methods
mount(target?): mounts and initializes the iframe, returns the iframe element.waitUntilReady(): resolves when iframe bootstrap andinitare complete.getSketch(options?): returns current sketch JSON.setSketch(sketch): replaces current sketch JSON and returns applied sketch.setCss(cssText): applies custom CSS inside the iframe.setTheme(theme): applies runtime theme.setPointSize(pointSizePx): convenience wrapper forsetTheme({ pointSizePx }).setCurveThickness(curveThicknessPx): convenience wrapper forsetTheme({ curveThicknessPx }).setSidebarExpanded(boolean): toggles embedded sidebar.setGrid(options): updates grid settings. Supports{ visible, spacing }or{ gridVisible, gridSpacing }.setGridVisible(boolean): toggles grid visibility.setGridSpacing(number): updates grid spacing (must be > 0).exportSVG(options?): exports current sketch as SVG data (see below).exportDXF(options?): exports current sketch as a DXF string plus sampled polyline metadata.export3DPolylines(options?): exports each sketch curve as a separate sampled 3D polyline.destroy(): disposes iframe and message handlers.
getSketch({ preferCached: true }) returns the latest cached sketch from recent events or calls when available.
Sketch JSON Constraint Symbols
When you call setSketch(sketch) or read getSketch(), each constraint uses a Unicode type symbol.
Common symbols:
⏚ground (1 point)━horizontal (2 points)│vertical (2 points)≡coincident (2 points)⟺distance (2 points)↥line-to-point distance (3 points: lineA,Band pointC)∠angle (4 points)⟂perpendicular/tangent (4 points)∥parallel (4 points)⇌equal distance (4 points)⏛point on line (3 points)⋯midpoint (3 points)
For line-to-point distance, use ↥ everywhere in payloads and internal tooling.
Example:
await sketcher.setSketch({
points: [
{ id: 0, x: 0, y: 0, fixed: true },
{ id: 1, x: 100, y: 0, fixed: false },
{ id: 2, x: 30, y: 25, fixed: false },
],
geometries: [
{ id: 0, type: "line", points: [0, 1], construction: false },
],
constraints: [
{ id: 0, type: "⏚", points: [0] },
{ id: 1, type: "↥", points: [0, 1, 2], value: 25 },
],
});exportSVG() Options and Return
exportSVG(options) uses the same conversion pipeline as sketchToSVG().
Options:
precision(default3)padding(default10)stroke(default#111111)strokeWidth(default1.5)fill(defaultnone)background(defaultnull)flipY(defaulttrue)includeConstruction(defaultfalse)bezierSamples(default24)curveResolutionorresolution(optional; controls circle/arc/bezier sampling density)
Return shape:
svg: serialized<svg ...>string.paths: array of{ id, type, d, construction, closed }.bounds:{ minX, minY, maxX, maxY, contentWidth, contentHeight, width, height, padding, flipY, transform }.
exportDXF() Options and Return
exportDXF(options) uses the same sampled-curve geometry pipeline and writes one DXF polyline per sketch curve.
Options:
units(defaultunitless; supportsmm,cm,m,in)includeConstruction(defaultfalse)bezierSamples(default24)curveResolutionorresolution(optional; controls circle/arc/bezier sampling density)layerNameorlayer(defaultSKETCH)colorNumber(optional DXF ACI color index)lineType(optional DXF line type; defaults toContinuous)
Return shape:
dxf: DXF file contents as a string.polylines: array of{ id, type, construction, closed, points }wherepointsare[x,y]pairs.units: normalized units label (unitless,mm,cm,m,in).layerName: DXF layer name used for output entities.curveResolution: resolved curve resolution (nullwhen not explicitly set).bezierSamples: resolved bezier segment sampling count.
export3DPolylines() Options and Return
export3DPolylines(options) returns sampled curve geometry where each sketch curve is a separate 3D polyline.
Options:
includeConstruction(defaultfalse)bezierSamples(default24)curveResolutionorresolution(optional; controls circle/arc/bezier sampling density)origin(default[0,0,0])xAxis(default[1,0,0])yAxis(default[0,1,0])
Return shape:
polylines: array of{ id, type, construction, closed, points }wherepointsare[x,y,z]points.basis:{ origin, xAxis, yAxis, zAxis }basis used for the 2D->3D mapping.curveResolution: resolved curve resolution (nullwhen not explicitly set).bezierSamples: resolved bezier segment sampling count.
Lifecycle Notes
mount()is idempotent for an active instance: if already mounted, it returns the same iframe after readiness.- After
destroy(), the instance is terminal. Create a newSketcher2DEmbedinstance to mount again.