@kanjieteam/kjdraw
KJDraw Editor APIKJDraw 编辑器 API
Mount a complete CAD editor with one function, then control drawings, files, commands and selection through a small typed API.一个函数挂载完整 CAD 编辑器,再通过小而清晰的类型化 API 控制图档、文件、命令与选择。
npm install @kanjieteam/kjdraw@1.0.0Quickstart快速接入
Give the host element a height, create the editor, then wait for ready before using the current drawing.先给容器设置高度,创建编辑器,再等待 ready 完成后操作当前图档。
<div id="cad"></div>
<style>
#cad { width: 100%; height: 720px; }
</style>
import { createKJDrawEditor } from '@kanjieteam/kjdraw'
const editor = createKJDrawEditor('#cad', {
document: 'sample',
locale: 'en',
theme: 'dark',
onChange: ({ revision, entityCount }) => {
console.log({ revision, entityCount })
},
})
await editor.ready
await editor.execute('CREATE', {
type: 'CIRCLE',
payload: { center: [40, 30, 0], radius: 12 },
})
editor.fit()
const kjd = await editor.save({ format: 'KJD', download: false })
// Call editor.dispose() when the owning screen unmounts.
Options
Pass these values as the second argument to createKJDrawEditor().将这些选项作为 createKJDrawEditor() 的第二个参数传入。
| Option选项 | Type | Default默认值 | Purpose用途 |
|---|---|---|---|
document | KJDocument | 'sample' | 'blank' | null | active SDK document or 'sample' | Initial drawing. 'sample' opens the included example; 'blank' and null create an empty drawing.初始图档。'sample' 打开内置示例;'blank' 与 null 创建空白图档。 |
sdk | KJDrawSDK | new SDK | Reuse an application SDK so commands, plugins and documents share one registry.复用应用 SDK,让命令、插件与图档共享同一注册表。 |
locale | 'en' | 'zh-CN' | 'en' | Initial workbench language.工作台初始语言。 |
theme | 'dark' | 'light' | 'dark' | Initial panel and canvas appearance.面板与画布的初始外观。 |
layout | 'classic' | 'compact' | 'focus' | 'classic' | Workbench arrangement: full CAD ribbon and panels, a shorter compact ribbon, or a canvas-first focus view. Available since 1.0.0-rc.3.工作台布局:完整 CAD Ribbon 与面板、较矮的紧凑 Ribbon,或画布优先的专注视图。自 1.0.0-rc.3 起提供。 |
readonly | boolean | false | Keep inspection, navigation and export while disabling editing controls.保留检查、导航与导出,同时禁用编辑控件。 |
grid | boolean | true | Show the drawing grid initially.初始显示绘图网格。 |
toolbar | boolean | true | Show the ribbon toolbar.显示 Ribbon 工具栏。 |
layers | boolean | true | Show the layers panel.显示图层面板。 |
properties | boolean | true | Show the properties inspector.显示属性检查器。 |
title | string | drawing ID | Override the drawing title displayed in the workbench header.覆盖工作台顶部显示的图档标题。 |
maxFileBytes | number | 20 MiB | Maximum input size checked before an opened file is read.打开文件前检查的最大输入字节数。 |
onReady | (editor: KJDrawEditor) => void | — | Called after the initial drawing and renderer are ready.初始图档与渲染器就绪后调用。 |
onChange | (event: KJDrawWorkbenchChange) => void | — | Receives the document, revision and entity count after a drawing change.图档变化后接收 document、revision 与 entityCount。 |
onSelectionChange | (event: KJDrawEditorSelectionEvent) => void | — | Receives the active document and selected object IDs.接收活动图档与已选对象 ID。 |
onError | (error: unknown) => void | — | Receives initialization, file and command errors.接收初始化、文件与命令错误。 |
Properties
Read current editor state and reach lower-level integration points when needed.读取当前编辑器状态,并在需要时进入更底层的集成入口。
| Property | Type | Purpose用途 |
|---|---|---|
ready | Promise<KJDrawEditor> | Resolves after the initial drawing is mounted and fitted.初始图档完成挂载和适配后 resolve。 |
element | HTMLElement | Mounted editor root element.已挂载的编辑器根元素。 |
document | KJDocument | null | Current drawing after ready resolves.ready 完成后的当前图档。 |
sdk | KJDrawSDK | SDK used by the editor. Register plugins here; use editor.execute() or pass a document explicitly for commands when several editors share this SDK.编辑器使用的 SDK,可在此注册插件。多个编辑器共享时,使用 editor.execute() 或显式指定 document 来确定命令操作的图纸。 |
workbench | KJDrawWorkbench | Advanced workbench access for custom tools and renderer integration.面向自定义工具与渲染集成的高级工作台入口。 |
locale | 'en' | 'zh-CN' | Current UI language.当前界面语言。 |
theme | 'dark' | 'light' | Current appearance.当前外观。 |
layout | 'classic' | 'compact' | 'focus' | Current workbench arrangement.当前工作台布局。 |
disposed | boolean | Whether dispose() has released the editor.dispose() 是否已释放编辑器。 |
Methods
File operations and edits that return promises can be awaited in application workflows.文件操作与返回 Promise 的编辑方法可直接纳入应用异步流程。
editor.open(source, options?)
↗Open DXF or KJD content. File names can supply format detection.打开 DXF 或 KJD 内容;可通过文件名自动识别格式。
- Parameters参数
Blob | string | ArrayBuffer | ArrayBufferView; KJWorkbenchOpenOptions- Returns返回
Promise<KJDocument>
editor.save(options?)
↗Save KJD by default or DXF when selected. Set download:false to handle the result yourself.默认保存 KJD,也可选择 DXF;设 download:false 后自行处理结果。
- Parameters参数
KJDrawEditorSaveOptions- Returns返回
Promise<string | Uint8Array>
editor.execute(command, args?)
↗Run a command against the current drawing and receive its revisioned receipt.对当前图档执行命令并获得带修订信息的回执。
- Parameters参数
string; KJCommandArguments- Returns返回
Promise<KJSDKCommandEnvelopeReceipt<T>>
editor.undo()
↗Undo the most recent committed transaction.撤销最近一次已提交事务。
- Parameters参数
—- Returns返回
Promise<KJSDKCommandEnvelopeReceipt>
editor.redo()
↗Redo the next transaction in session history.重做当前会话历史中的下一项事务。
- Parameters参数
—- Returns返回
Promise<KJSDKCommandEnvelopeReceipt>
editor.fit()
↗Fit the active drawing to the current viewport.将活动图档适配到当前视口。
- Parameters参数
—- Returns返回
KJDrawEditor
editor.setDocument(drawing)
↗Attach and activate an existing document.挂接并激活一个现有图档。
- Parameters参数
KJDocument- Returns返回
Promise<KJDrawEditor>
editor.setSelection(ids)
↗Replace selection through the serialized command queue and return the accepted IDs.通过串行命令队列替换选择集,并返回已接受的 ID。
- Parameters参数
readonly string[]- Returns返回
Promise<readonly string[]>
editor.getSelection()
↗Read the current selected object IDs.读取当前已选对象 ID。
- Parameters参数
—- Returns返回
readonly string[]
editor.setTheme(theme)
↗Switch panel and canvas appearance immediately.立即切换面板与画布外观。
- Parameters参数
'dark' | 'light'- Returns返回
KJDrawEditor
editor.setLayout(layout)
↗Switch workbench chrome in place without replacing the editor, drawing or undo history. Available since 1.0.0-rc.3.原位切换工作台界面,不替换编辑器、图档或撤销历史。自 1.0.0-rc.3 起提供。
- Parameters参数
'classic' | 'compact' | 'focus'- Returns返回
KJDrawEditor
editor.setLocale(locale)
↗Switch workbench language immediately.立即切换工作台语言。
- Parameters参数
'en' | 'zh-CN'- Returns返回
KJDrawEditor
editor.setTool(tool)
↗Activate select, pan, move, copy or measure; drawing tools include line, polyline, circle, arc, ellipse, rectangle, polygon, spline, hatch, dimension, point, ray, xline and text. Configure construction modes in the workbench Drawing options dialog.启用 select、pan、move、copy、measure,或 line、polyline、circle、arc、ellipse、rectangle、polygon、spline、hatch、dimension、point、ray、xline、text 绘图工具。构造方式可在工作台绘图参数对话框中设置。
- Parameters参数
KJWorkbenchTool- Returns返回
KJDrawEditor
editor.setTitle(title)
↗Update the title displayed above the drawing.更新图档上方显示的标题。
- Parameters参数
string- Returns返回
KJDrawEditor
editor.setOptions(options)
↗Update layout, editor chrome, editing mode and file-size limit without replacing the drawing or its undo history.原位更新布局、编辑器界面、编辑模式与文件大小限制,不替换图档或撤销历史。
- Parameters参数
Pick<KJDrawEditorOptions, 'layout' | 'readonly' | 'grid' | 'toolbar' | 'layers' | 'properties' | 'title' | 'maxFileBytes'>- Returns返回
KJDrawEditor
editor.on(name, listener)
↗Subscribe to an editor event and receive an unsubscribe function.订阅编辑器事件,并获得取消订阅函数。
- Parameters参数
keyof KJDrawEditorEvents; listener- Returns返回
() => boolean
editor.dispose()
↗Unmount and release listeners and renderer resources. Safe to call twice.卸载并释放监听与渲染资源;可安全重复调用。
- Parameters参数
—- Returns返回
void
Events
Use constructor callbacks for common events or editor.on() for every event.常用事件可通过初始化回调处理,全部事件都可用 editor.on() 订阅。
const off = editor.on('selectionchange', ({ ids }) => {
console.log(ids)
})
// Later
off()
| Event | Payload | Callback快捷回调 | When触发时机 |
|---|---|---|---|
ready | KJDrawEditor | onReady | Initial drawing and renderer are ready.初始图档与渲染器已经就绪。 |
change | { document, revision, entityCount } | onChange | A drawing change has committed.一次图档变更已提交。 |
selectionchange | { document, ids } | onSelectionChange | The selected object IDs changed.已选对象 ID 发生变化。 |
documentchange | { document } | editor.on() | Open or setDocument activated another drawing.open 或 setDocument 激活了另一张图档。 |
error | unknown | onError | Initialization, file or queued command failed.初始化、文件操作或队列命令失败。 |
dispose | undefined | editor.on() | The editor released its mounted resources.编辑器已释放挂载资源。 |
React / Vue
React
import { useRef } from 'react'
import { KJDraw, type KJDrawEditor } from '@kanjieteam/kjdraw/react'
export function DrawingEditor() {
const editor = useRef<KJDrawEditor | null>(null)
async function moveSelection() {
const instance = editor.current
const ids = instance?.getSelection() ?? []
if (!instance || !ids.length) return
await instance.execute('MOVE', { ids, dx: 10, dy: 0 })
}
return (
<>
<button onClick={() => void moveSelection()}>Move selected</button>
<KJDraw ref={editor} document="sample" style={{ height: 720 }} />
</>
)
}Vue
<script setup lang="ts">
import { ref } from 'vue'
import { KJDraw, type KJDrawExposed } from '@kanjieteam/kjdraw/vue'
const editor = ref<KJDrawExposed | null>(null)
async function moveSelection() {
const instance = editor.value
const ids = instance?.getSelection() ?? []
if (!instance || !ids.length) return
await instance.execute('MOVE', { ids, dx: 10, dy: 0 })
}
</script>
<template>
<button @click="moveSelection">Move selected</button>
<KJDraw ref="editor" document="sample" style="height: 720px" />
</template>