Mx2DNode 二开 API 参考(后台参数化绘图 / 数据提取)
基于工程 TypeScript 源码整理(
src/mxcad/*.ts、src/sample/*.ts),所有签名与返回值以源码为准。
一、使用模式
在 src/ 下新增 .ts 文件,导入模块后使用:
import { Mx2DDraw, MxBackstage, MxFun } from "../MxFun";
import { McDbDatabase } from "../mxcad/McDbDatabase";
import { McGePoint3d } from "../mxcad/McGePoint3d";
// ...其余所需 McDb* 类从 ../mxcad/ 导入典型流程(参考 sample/ParamDraw.ts):
// 1. 打开空白模板(工程目录下 empty_template.dwg)
if (!MxBackstage.openFile(Mx2DDraw.getEmptyTemplateDwgFilePath())) { /* 失败 */ }
// 2. 绘图(见第二节)
Mx2DDraw.drawLine(new McGePoint3d([0,0,0]), new McGePoint3d([100,100,0]));
// 3. 保存(DWG/DXF 均可;相对路径相对工程目录;无 DWG 授权模块时自动经 mxcadassembly 转换)
if (!MxBackstage.writeFile("out/test.dwg")) { /* 失败 */ }
Mx2DDraw、MxBackstage、MxFun是单例(MxFun.init()由 mxapp.js 入口调用),直接使用,不要 new。
二、Mx2DDraw —— 2D 绘图类
2.1 绘图前置设置
| 方法 | 说明 |
|---|---|
setColor(r, g, b) | 设置当前颜色(RGB 0-255) |
setColorIndex(index) | 设置 AutoCAD 颜色索引 |
setLineWeight(lineWeight) | 设置线宽,取 LineWeight 枚举(kLnWt025=25 千分之一毫米,kLnWtByLayer=-1 随层) |
addLinetype(name, lineDefine) → 线型id | 添加线型。lineDefine 如 "6,-10"(实长,虚长…) |
addLinetypeEx(name, lineDefine, textStyle) → 线型id | 带文字定义的线型 |
setLinetype(name) | 设置当前线型 |
setLineTypeScale(scale) | 设置当前线型比例 |
addLayer(name) → 图层id | 新增图层 |
setLayer(name) → bool | 设置当前图层 |
addTextStyle(name, shxFile, bigFontFile, xScale) → 样式id | 添加 SHX 文字样式 |
addTextStyle2(name, trueTypeFont, xScale) → 样式id | 添加 TrueType 文字样式(如黑体、宋体) |
setTextStyle(name) → bool | 设置当前文字样式 |
addDimStyle(name, doubleData, intData, stringData, idData) → 样式id | 添加标注样式(同名已存在则失败) |
addPatternDefinition(name, definition) → bool | 添加填充图案定义。definition 格式:"((角度, x原点, y原点, dx, dy, dash1, dash2, ...))",如 "((45, 0,0, 0,0.125))" |
2.2 基本图元绘制(均返回 McDbObjectId)
| 方法 | 说明 |
|---|---|
drawLine(pt1, pt2) / drawLine2(x1,y1,x2,y2) | 直线 |
drawPoint(x, y, z=0) | 点 |
drawCircle(center, r) / drawCircle2(cx, cy, r) | 圆 |
drawArc(center, radius, startAngle, endAngle) | 圆弧 |
drawEllipse(center, majorAxisX, majorAxisY, radiusRatio) / drawEllipse2(cx,cy,cz, ...) | 椭圆 |
drawText(position, text, height, rotation, hMode, vMode, widthFactor=1) | 单行文字。hMode:0左/1中/2右;vMode:1下/2中/3上;position 可为 [x,y,z] 数组 |
drawMText(location, contents, height, width, rotation, attachment) | 多行文字。attachment 1~9(左上~右下九宫格)。支持格式码,如平方:"\A2;平方方法: m{\H0.3x;\S 2^;}" |
drawImage(position, width, height, rotation, imageFilePath) | 插入图片(JPG 等) |
drawEntity(ent: McDbEntity) | 绘制一个自行构造好的实体对象(如 new McDbLine 后设置属性再提交) |
erase(id) → bool | 删除对象 |
2.3 路径 → 图元(路径 API 先积累点,再生成实体)
Mx2DDraw.pathMoveToEx(new McGePoint3d([600, 3300]), 0, 0, 0.3); // 起点(含起终点宽度、bulge)
Mx2DDraw.pathLineTo(700, 3300); // 后续点
Mx2DDraw.pathLineTo(700, 3400);
Mx2DDraw.pathLineTo(600, 3300);
Mx2DDraw.pathMakeClosed(); // 可选:闭合
Mx2DDraw.pathMakeExclude(true); // 可选:设为排除区域(挖空)生成结果(均返回 id):
drawPathToPolyline()→ 多段线drawPathToSpline()→ 样条线drawPathToHatch(patternName = "", scale = 1)→ 填充(图案名需先 addPatternDefinition;空串为实心)
2.4 图块
| 方法 | 说明 |
|---|---|
InsertBlock(fileName, blockName) → 块表记录id | 从 DWG 文件导入图块定义(文件内指定名的块),返回新块记录 id。fileName 为相对路径时基于工程目录 |
drawBlockReference(pos, blkName, scale, angleDeg) → 块引用id | 插入已存在的图块。angle 单位:度 |
图签填写(属性)示例,见 sample/ParamDraw.ts drawTq:
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 = "张三"; // 按 attrib.tag 匹配填写
}2.5 标注
| 方法 | 说明 |
|---|---|
drawDimAligned(xLine1, xLine2, dimLinePoint) | 对齐标注 |
drawDimRotated(xLine1, xLine2, dimLinePoint, rotation) | 旋转(线性)标注 |
drawDimDiametric(chordPoint, farChordPoint, leaderLength) | 直径标注 |
drawDimRadial(center, chordPoint, leaderLength) | 半径标注 |
drawDimAngular(arcPoint, xLine1, xLine2, sDimensionText) | 角度标注 |
已知源码问题:
drawEllipseArc与drawDimAngular内部调用了错误的方法(笔误),使用前需验证或改用底层 API。
2.6 数据库与对象
| 方法 | 说明 |
|---|---|
currentDatabase() → McDbDatabase | 当前图纸数据库(绘图上下文) |
backgroundDatabase() → McDbDatabase | 后台打开的图纸数据库 |
objectIdToObject(id) → McDbObject|null | 对象 id 转实体对象(自动映射为具体类型) |
handleToObjectId(handle) / objectIdToHandle(id) | 句柄与 id 互转 |
compareObject(id1, id2) → number | 比较两对象是否相同(0 相同) |
getEmptyTemplateDwgFilePath() | 空白模板 DWG 路径(工程目录 empty_template.dwg) |
getCurrentPath() | 当前程序路径(工程目录/../../) |
三、MxBackstage —— 后台文件处理
| 方法 | 说明 |
|---|---|
openFile(fileName, iReadContent = 0) → bool | 打开图纸。iReadContent:0 默认;需读扩展数据传 67904(kReadDefault|kReadxData) |
writeFile(fileName) → bool | 保存为 DWG/DXF/mxweb(按后缀)。无 DWG 写模块时自动经 mxcadassembly 转换 |
writeWebGLFile(fileName) → bool | 输出前端显示文件(mxweb) |
getDatabase() → McDbDatabase | 获取当前图纸数据库 |
initSet(iniJson) → bool | 初始化转换设置(JSON 字符串,一般无需调用) |
四、McDbDatabase —— 数据库对象
let db: McDbDatabase = new McDbDatabase(); // 独立实例(用于读其他文件后合并)
db.readDwgFile("a.dwg"); // 相对路径相对工程目录;或从 Mx2DDraw.currentDatabase() 获取| 方法/属性 | 说明 |
|---|---|
readDwgFile(fileName) → bool | 独立加载一个 DWG 到本实例(用完 free()) |
getBlockTable() / getLayerTable() / getDimStyleTable() / getLineTypeTable() / getTextStyleTable() | 获取各符号表(表对象有 getAll() 返回记录 id 数组) |
currentSpace() / modelSpace() → McDbBlockTableRecord | 当前空间 / 模型空间 |
currentSpace().getBoundingBox() → [minPt, maxPt] | 空间外包矩形 |
getUselessLayer() → id数组 | 未使用的图层 |
marge(database, aryLayer?) → bool | 把另一数据库合并进本库(可只合并指定图层数组) |
insert(blkName, database) → bool | 从另一数据库插入图块 |
getSysVarString/setSysVarString(name, val) | 系统变量(字符串) |
getSysVarDouble/setSysVarDouble(name, val) | 系统变量(浮点),如 LTSCALE 全局线型比例 |
getSysVarLong/setSysVarLong、getSysVarPoint/setSysVarPoint | 系统变量(整数/点) |
属性:currentlyColorIndex、currentlyLayerName、currentlyLineTypeName、currentlyTextStyle、currentlyTrueColor、insbase、lineTypeScale | 当前绘图状态读写 |
free() | 释放(独立 readDwgFile 的实例必须调用) |
LineWeight 枚举:kLnWt000~kLnWt211(0/5/9/…/211),kLnWtByLayer=-1、kLnWtByBlock=-2、kLnWtByLwDefault=-3。
五、McDbEntity —— 实体公共部分
所有具体实体(Line/Circle/Polyline/Text/BlockReference/Dimension…)继承的属性与方法:
| 属性/方法 | 说明 |
|---|---|
layer / layerId | 图层名 / 图层 id(可读写) |
color / colorIndex | 颜色(McCmColor)/ 颜色索引(可读写) |
linetype / linetypeId / linetypeScale | 线型名 / id / 比例(可读写) |
visible | 是否可见 |
textStyleId | 文字样式 id |
getGeomExtents() → [minPt, maxPt] | 几何外包矩形 |
xdata(appName?) → MrxDbgRbList | 读取全部扩展数据 |
setxDataString(appName, val, index=0) / getxDataString(appName, index=0) | 字符串型扩展数据 |
setxDataDouble/ getxDataDouble、setxDataLong/getxDataLong | 浮点/整型扩展数据 |
explode() → id数组 | 分解实体(块引用、多段线等) |
intersectWith(ent, mode=0) → 点数组 | 与另一实体求交 |
六、具体实体类(常用成员)
以下成员摘自源码与示例用法,完整定义见 src/mxcad/ 对应文件:
- McDbLine:
startPoint、endPoint(McGePoint3d,可读写,构造时 new McDbLine() 赋值后 Mx2DDraw.drawEntity(line)) - McDbCircle:圆心、半径
- McDbPolyline:
numVerts顶点数、getPointAt(i)、getBulgeAt(i) - McDbText:
textString、position、alignmentPoint - McDbMText:
contents、getAllText() - McDbBlockReference:
position、blockName、blockTableRecordId、blockTransform、attributeCount、attributeItem(i)(返回 McDbAttribute:tag、textString、position)、createAttribute() - McDbDimension / McDbAlignedDimension / McDbRotatedDimension:
xLine1Point、xLine2Point、getDimVarObjectId(342/343/344)(获取标注块) - McDbBlockTableRecord(空间/块定义):
name、getAllEntity()→ 块内实体 id 数组 - McDbLayerTableRecord:
name、colorIndex、color、off
七、选择集与过滤
import { MrxDbgSelSet } from "../mxcad/MrxDbgSelSet";
import { MrxDbgRbList } from "../mxcad/MrxDbgRbList";
let ss = new MrxDbgSelSet();
let filter = new MrxDbgRbList();
filter.addString("LWPOLYLINE", 5020); // 按类型过滤(5020 为类型码)
filter.addString("图层名", 8); // 按图层过滤(8 为图层码)
ss.allSelect(filter); // 或 selectAtPoint(pt, filter, tol)
// crossingSelect(pt1, pt2) / windowSelect(pt1, pt2)
for (let i = 0; i < ss.count; i++) {
let ent = ss.item(i).getEntity(); // 返回具体实体对象
if (ent instanceof McDbText) { /* ... */ }
}MrxDbgRbList(resbuf 链表):count、atDouble/atLong/atString/atPoint(i)、addDouble/addLong/addString/addPoint(v, dataType)、itemDataType(i)、removeAll()。
八、几何对象
- McGePoint3d:
x/y/z(可读写);构造new McGePoint3d()或new McGePoint3d([x,y,z]);distanceTo(pt)、add(pt)、sum(pt)、isEqualTo(pt)、transformBy(mat) - McGeVector3d:向量
- McGeMatrix3d:矩阵变换,
preMultBy(mat)前乘等
九、二开指引
新增绘图功能:在
src/sample/新建 .ts,参考 ParamDraw.ts 的 TestDraw 类结构(每个 draw 方法一个图元),在 MxCommand.ts 注册命令数据提取类功能:参考 GetDwgData.ts(选择集 + 过滤 + instanceof 分发 + JSON 输出)
⚠️ 现成命令不覆盖几何提取:
getcaddata只提取文字与块属性,直线/多段线/圆等几何实体没有任何现成命令,必须二开。最小范例(已实测:提取全部直线为 JSON,105/105 条与前端 mxcad 导出结果精确核对一致):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 参数错误" }; if (!param.outfile) return { code: 4, message: "param.outfile 参数错误" }; let curPath = Mx2DDraw.getCurrentPath(); if (!MxBackstage.openFile(curPath + param.file, 67904)) return { code: 5, message: "openFile文件出错" }; let db = MxBackstage.getDatabase(); let ids = db.modelSpace().getAllEntity(); // 模型空间全部实体 id let lines: any[] = []; for (let i = 0; i < ids.length; i++) { let ent = ids[i].getObject(); // id → 具体实体对象 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, // 句柄(字符串) 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 }; }注册与调用:
MxCommand.ts中加import { getlines } from "./sample/GetLines";和MxProcessor.addCommand("getlines", getlines),npm run build后执行bin\node.exe mxapp.js getlines file=t1.dwg outfile=t1_lines.json。其他实体类型(圆/多段线/标注等)同理:换instanceof分支 + 对应成员(见第六节)。切图/导出类功能:参考 CutDwg.ts(图框识别 + 排序)、ExportPdf.ts(整图 PDF + 图框定位)
编译:
npm run build(tsc),修改后必须重新编译(运行的是 .js)全部示例代码位于
src/sample/目录,可直接复制改造
