Mx2DNode Secondary Development API Reference (backend parametric drawing / data extraction)
Compiled from the project TypeScript source (
src/mxcad/*.ts,src/sample/*.ts); all signatures and return values are subject to the source code.
I. Usage Pattern
Create a new .ts file under src/, import the modules, and use them:
import { Mx2DDraw, MxBackstage, MxFun } from "../MxFun";
import { McDbDatabase } from "../mxcad/McDbDatabase";
import { McGePoint3d } from "../mxcad/McGePoint3d";
// ... import the remaining McDb* classes you need from ../mxcad/Typical flow (see sample/ParamDraw.ts):
// 1. Open the blank template (empty_template.dwg in the project directory)
if (!MxBackstage.openFile(Mx2DDraw.getEmptyTemplateDwgFilePath())) { /* failed */ }
// 2. Draw (see section 2)
Mx2DDraw.drawLine(new McGePoint3d([0,0,0]), new McGePoint3d([100,100,0]));
// 3. Save (DWG/DXF both fine; relative paths are relative to the project directory;
// without a DWG license module it auto-converts via mxcadassembly)
if (!MxBackstage.writeFile("out/test.dwg")) { /* failed */ }
Mx2DDraw,MxBackstage, andMxFunare singletons (MxFun.init()is called by the mxapp.js entry point) — use them directly; do notnewthem.
II. Mx2DDraw — 2D Drawing Class
2.1 Pre-drawing Settings
| Method | Description |
|---|---|
setColor(r, g, b) | Set the current color (RGB 0-255) |
setColorIndex(index) | Set the AutoCAD color index |
setLineWeight(lineWeight) | Set line weight, takes a LineWeight enum (kLnWt025 = 0.25 mm, kLnWtByLayer = -1 follows the layer) |
addLinetype(name, lineDefine) → linetype id | Add a linetype. lineDefine like "6,-10" (solid length, dash length…) |
addLinetypeEx(name, lineDefine, textStyle) → linetype id | Linetype with a text definition |
setLinetype(name) | Set the current linetype |
setLineTypeScale(scale) | Set the current linetype scale |
addLayer(name) → layer id | Add a layer |
setLayer(name) → bool | Set the current layer |
addTextStyle(name, shxFile, bigFontFile, xScale) → style id | Add an SHX text style |
addTextStyle2(name, trueTypeFont, xScale) → style id | Add a TrueType text style (e.g. SimHei, SimSun) |
setTextStyle(name) → bool | Set the current text style |
addDimStyle(name, doubleData, intData, stringData, idData) → style id | Add a dimension style (fails if a same-named style already exists) |
addPatternDefinition(name, definition) → bool | Add a hatch pattern definition. definition format: "((angle, xOrigin, yOrigin, dx, dy, dash1, dash2, ...))", e.g. "((45, 0,0, 0,0.125))" |
2.2 Basic Primitive Drawing (all return McDbObjectId)
| Method | Description |
|---|---|
drawLine(pt1, pt2) / drawLine2(x1,y1,x2,y2) | Line |
drawPoint(x, y, z=0) | Point |
drawCircle(center, r) / drawCircle2(cx, cy, r) | Circle |
drawArc(center, radius, startAngle, endAngle) | Arc |
drawEllipse(center, majorAxisX, majorAxisY, radiusRatio) / drawEllipse2(cx,cy,cz, ...) | Ellipse |
drawText(position, text, height, rotation, hMode, vMode, widthFactor=1) | Single-line text. hMode: 0 left / 1 center / 2 right; vMode: 1 bottom / 2 middle / 3 top; position may be an [x,y,z] array |
drawMText(location, contents, height, width, rotation, attachment) | MText. attachment 1–9 (nine-grid from top-left to bottom-right). Supports format codes, e.g. superscript 2: "\A2;Square method: m{\H0.3x;\S 2^;}" |
drawImage(position, width, height, rotation, imageFilePath) | Insert an image (JPG, etc.) |
drawEntity(ent: McDbEntity) | Draw a self-constructed entity object (e.g. build a McDbLine, set its properties, then submit) |
erase(id) → bool | Delete an object |
2.3 Path → Primitive (the path API accumulates points first, then generates the entity)
Mx2DDraw.pathMoveToEx(new McGePoint3d([600, 3300]), 0, 0, 0.3); // start point (incl. start/end widths, bulge)
Mx2DDraw.pathLineTo(700, 3300); // subsequent points
Mx2DDraw.pathLineTo(700, 3400);
Mx2DDraw.pathLineTo(600, 3300);
Mx2DDraw.pathMakeClosed(); // optional: close
Mx2DDraw.pathMakeExclude(true); // optional: mark as an excluded region (hole)Generated results (all return an id):
drawPathToPolyline()→ polylinedrawPathToSpline()→ splinedrawPathToHatch(patternName = "", scale = 1)→ hatch (the pattern name must be added via addPatternDefinition first; an empty string means solid fill)
2.4 Blocks
| Method | Description |
|---|---|
InsertBlock(fileName, blockName) → block table record id | Import a block definition from a DWG file (the block with the given name in the file); returns the new block record id. A relative fileName is based on the project directory |
drawBlockReference(pos, blkName, scale, angleDeg) → block reference id | Insert an existing block. angle unit: degrees |
Title block (attribute) filling example — see drawTq in sample/ParamDraw.ts:
let id = Mx2DDraw.drawBlockReference([100,100,0], "BT", 1.0, 0.0);
let blkRef = id.getEntity() as McDbBlockReference;
blkRef.createAttribute();
for (let i = 0; i < blkRef.attributeCount; i++) {
let attrib = blkRef.attributeItem(i);
attrib.textString = "John Doe"; // fill in by matching attrib.tag
}2.5 Dimensions
| Method | Description |
|---|---|
drawDimAligned(xLine1, xLine2, dimLinePoint) | Aligned dimension |
drawDimRotated(xLine1, xLine2, dimLinePoint, rotation) | Rotated (linear) dimension |
drawDimDiametric(chordPoint, farChordPoint, leaderLength) | Diametric dimension |
drawDimRadial(center, chordPoint, leaderLength) | Radial dimension |
drawDimAngular(arcPoint, xLine1, xLine2, sDimensionText) | Angular dimension |
Known source issue:
drawEllipseArcanddrawDimAngularinternally call the wrong method (a typo); verify before use or switch to the low-level API.
2.6 Database and Objects
| Method | Description |
|---|---|
currentDatabase() → McDbDatabase | The current drawing database (drawing context) |
backgroundDatabase() → McDbDatabase | The database of the drawing opened in the background |
objectIdToObject(id) → McDbObject|null | Convert an object id to an entity object (auto-mapped to the concrete type) |
handleToObjectId(handle) / objectIdToHandle(id) | Convert between handle and id |
compareObject(id1, id2) → number | Compare whether two objects are the same (0 = same) |
getEmptyTemplateDwgFilePath() | Path of the blank template DWG (empty_template.dwg in the project directory) |
getCurrentPath() | Current program path (project dir/../../) |
III. MxBackstage — Background File Handling
| Method | Description |
|---|---|
openFile(fileName, iReadContent = 0) → bool | Open a drawing. iReadContent: 0 default; pass 67904 (kReadDefault|kReadxData) when extended data must be read |
writeFile(fileName) → bool | Save as DWG/DXF/mxweb (by extension). Without a DWG write module it auto-converts via mxcadassembly |
writeWebGLFile(fileName) → bool | Output the frontend display file (mxweb) |
getDatabase() → McDbDatabase | Get the current drawing database |
initSet(iniJson) → bool | Initialize conversion settings (JSON string; generally no need to call) |
IV. McDbDatabase — Database Object
let db: McDbDatabase = new McDbDatabase(); // standalone instance (for reading another file then merging)
db.readDwgFile("a.dwg"); // relative paths are relative to the project directory; or get it from Mx2DDraw.currentDatabase()| Method/Property | Description |
|---|---|
readDwgFile(fileName) → bool | Load a DWG standalone into this instance (call free() when done) |
getBlockTable() / getLayerTable() / getDimStyleTable() / getLineTypeTable() / getTextStyleTable() | Get each symbol table (a table object has getAll() returning an array of record ids) |
currentSpace() / modelSpace() → McDbBlockTableRecord | Current space / model space |
currentSpace().getBoundingBox() → [minPt, maxPt] | Bounding rectangle of the space |
getUselessLayer() → id array | Unused layers |
marge(database, aryLayer?) → bool | Merge another database into this one (optionally only the specified layer array) |
insert(blkName, database) → bool | Insert a block from another database |
getSysVarString/setSysVarString(name, val) | System variables (string) |
getSysVarDouble/setSysVarDouble(name, val) | System variables (double), e.g. LTSCALE global linetype scale |
getSysVarLong/setSysVarLong, getSysVarPoint/setSysVarPoint | System variables (integer/point) |
Properties: currentlyColorIndex, currentlyLayerName, currentlyLineTypeName, currentlyTextStyle, currentlyTrueColor, insbase, lineTypeScale | Read/write the current drawing state |
free() | Release (must be called for standalone readDwgFile instances) |
LineWeight enum: kLnWt000~kLnWt211 (0/5/9/…/211), kLnWtByLayer=-1, kLnWtByBlock=-2, kLnWtByLwDefault=-3.
V. McDbEntity — Common Entity Parts
Properties and methods inherited by all concrete entities (Line/Circle/Polyline/Text/BlockReference/Dimension…):
| Property/Method | Description |
|---|---|
layer / layerId | Layer name / layer id (read-write) |
color / colorIndex | Color (McCmColor) / color index (read-write) |
linetype / linetypeId / linetypeScale | Linetype name / id / scale (read-write) |
visible | Whether visible |
textStyleId | Text style id |
getGeomExtents() → [minPt, maxPt] | Geometric bounding rectangle |
xdata(appName?) → MrxDbgRbList | Read all extended data |
setxDataString(appName, val, index=0) / getxDataString(appName, index=0) | String extended data |
setxDataDouble/ getxDataDouble, setxDataLong/getxDataLong | Double/integer extended data |
explode() → id array | Explode the entity (block references, polylines, etc.) |
intersectWith(ent, mode=0) → point array | Intersect with another entity |
VI. Concrete Entity Classes (commonly used members)
The following members are taken from the source and sample usage; full definitions live in the corresponding src/mxcad/ files:
- McDbLine:
startPoint,endPoint(McGePoint3d, read-write; withnew McDbLine()assign thenMx2DDraw.drawEntity(line)) - McDbCircle: center, radius
- McDbPolyline:
numVertsvertex count,getPointAt(i),getBulgeAt(i) - McDbText:
textString,position,alignmentPoint - McDbMText:
contents,getAllText() - McDbBlockReference:
position,blockName,blockTableRecordId,blockTransform,attributeCount,attributeItem(i)(returns McDbAttribute:tag,textString,position),createAttribute() - McDbDimension / McDbAlignedDimension / McDbRotatedDimension:
xLine1Point,xLine2Point,getDimVarObjectId(342/343/344)(get the dimension block) - McDbBlockTableRecord (space/block definition):
name,getAllEntity()→ array of entity ids inside the block - McDbLayerTableRecord:
name,colorIndex,color,off
VII. Selection Sets and Filtering
import { MrxDbgSelSet } from "../mxcad/MrxDbgSelSet";
import { MrxDbgRbList } from "../mxcad/MrxDbgRbList";
let ss = new MrxDbgSelSet();
let filter = new MrxDbgRbList();
filter.addString("LWPOLYLINE", 5020); // filter by type (5020 is the type code)
filter.addString("layer name", 8); // filter by layer (8 is the layer code)
ss.allSelect(filter); // or selectAtPoint(pt, filter, tol)
// crossingSelect(pt1, pt2) / windowSelect(pt1, pt2)
for (let i = 0; i < ss.count; i++) {
let ent = ss.item(i).getEntity(); // returns the concrete entity object
if (ent instanceof McDbText) { /* ... */ }
}MrxDbgRbList (resbuf list): count, atDouble/atLong/atString/atPoint(i), addDouble/addLong/addString/addPoint(v, dataType), itemDataType(i), removeAll().
VIII. Geometry Objects
- McGePoint3d:
x/y/z(read-write); construct withnew McGePoint3d()ornew McGePoint3d([x,y,z]);distanceTo(pt),add(pt),sum(pt),isEqualTo(pt),transformBy(mat) - McGeVector3d: vector
- McGeMatrix3d: matrix transformation,
preMultBy(mat)pre-multiply, etc.
IX. Secondary Development Guide
New drawing feature: create a .ts under
src/sample/, follow the TestDraw class structure of ParamDraw.ts (one primitive per draw method), register the command in MxCommand.tsData extraction feature: see GetDwgData.ts (selection set + filter + instanceof dispatch + JSON output)
⚠️ No existing command covers geometry extraction:
getcaddataextracts text and block attributes only — there is NO existing command for geometry entities such as lines/polylines/circles; secondary development is required. Minimal example (tested: extracts all lines to JSON; 105/105 lines matched exactly against the frontend mxcad export result):ts// src/sample/GetLines.ts import { Mx2DDraw, MxBackstage, MxFun } from "../MxFun"; import { McDbLine } from "../mxcad/McDbLine"; import { MrxDbgSelSet } from "../mxcad/MrxDbgSelSet"; import { MrxDbgRbList } from "../mxcad/MrxDbgRbList"; export function getlines(param: any) { if (!param.file) return { code: 3, message: "param.file error" }; if (!param.outfile) return { code: 4, message: "param.outfile error" }; let curPath = Mx2DDraw.getCurrentPath(); if (!MxBackstage.openFile(curPath + param.file, 67904)) return { code: 5, message: "openFile failed" }; let db = MxBackstage.getDatabase(); let ids = db.modelSpace().getAllEntity(); // all entity ids in model space let lines: any[] = []; for (let i = 0; i < ids.length; i++) { let ent = ids[i].getObject(); // id → concrete entity object if (!ent) continue; if (ent instanceof McDbLine) { let line: McDbLine = ent; lines.push({ type: "LINE", layer: line.layer, linetype: line.linetype, handle: line.handle.imp, // handle (string) startPoint: { x: line.startPoint.x, y: line.startPoint.y, z: line.startPoint.z }, endPoint: { x: line.endPoint.x, y: line.endPoint.y, z: line.endPoint.z } }); } } MxFun.writeFile(curPath + param.outfile, JSON.stringify({ count: lines.length, lines }, null, 1)); return { ret: 0, resultfile: param.outfile }; }Registration and invocation: add
import { getlines } from "./sample/GetLines";andMxProcessor.addCommand("getlines", getlines)inMxCommand.ts, then afternpm run buildrunbin\node.exe mxapp.js getlines file=t1.dwg outfile=t1_lines.json. Other entity types (circle/polyline/dimension, etc.) follow the same pattern: swap theinstanceofbranch + corresponding members (see section 6).Cutting/export features: see CutDwg.ts (title block frame detection + sorting), ExportPdf.ts (whole-drawing PDF + title block frame localization)
Compilation:
npm run build(tsc); after any modification you MUST recompile (the runtime executes the .js)All sample code lives in the
src/sample/directory and can be copied and adapted directly
