Skip to content

元素创建

vkedit 的元素操作基于 IGraphicElement 实例对象,而非普通数据对象。本文档介绍正确的元素创建模式。

创建流程

1. ElementManagerPlugin.createElement(type)  -> 创建元素实例
2. 设置元素属性(xmm/ymm/wmm/hmm 等)
3. AddElementCommand(host, element)           -> 创建添加命令
4. host.executeCommand(command)               -> 执行命令,元素出现在画布

通过代码创建

typescript
import { AddElementCommand } from 'vkedit'

const elementManager = host.getPlugin('element-manager-plugin')

// 创建矩形元素实例
const rect = elementManager.createElement('rect')

// 设置位置和尺寸(毫米单位)
rect.xmm = 10   // X 坐标
rect.ymm = 10   // Y 坐标
rect.wmm = 50   // 宽度
rect.hmm = 30   // 高度

// 设置样式
rect.fill = '#6366f1'
rect.stroke = '#4338ca'
rect.strokeWidthMM = 0.2

// 执行添加命令
host.executeCommand(new AddElementCommand(host, rect))

可用的元素类型

元素类型取决于已安装的图形插件:

元素类型对应插件元素类
'rect'RectPluginRectElement
'text'TextPluginTextElement
'line'LinePluginLineElement
'table'TablePluginTableElement
'qr'QrcodePluginQrcodeElement
'barcode'BarcodePluginBarcodeElement
'chart'ChartPluginChartElement

坐标系统

元素位置以毫米为单位存储:

属性说明
xmmX 坐标(毫米)
ymmY 坐标(毫米)
wmm宽度(毫米)
hmm高度(毫米)

对应的像素属性(xywidthheight)是计算属性,由毫米值乘以 DPM 得出。设置像素属性时会自动反算毫米值,但建议直接使用毫米属性。

typescript
// 推荐:直接设置毫米属性
rect.xmm = 10
rect.wmm = 50

// 不推荐:设置像素属性(会自动反算毫米值)
rect.x = 80    // 10mm * 8dpm = 80px
rect.width = 400 // 50mm * 8dpm = 400px

更新元素属性

已添加到画布的元素可通过 UpdatePropertyCommand 更新属性(支持撤销重做):

typescript
import { UpdatePropertyCommand } from 'vkedit'

// 参数:host, element, 属性路径, 旧值, 新值
host.executeCommand(new UpdatePropertyCommand(host, rect, 'fill', '#6366f1', '#10B981'))

属性路径支持点号语法访问嵌套属性:

typescript
// 更新嵌套属性
host.executeCommand(new UpdatePropertyCommand(host, table, 'cells.0.0.text', '旧文本', '新文本'))

也可直接修改元素属性(不进入撤销栈):

typescript
rect.fill = '#10B981'

直接修改不进入撤销栈

直接修改元素属性不会进入撤销栈。如需可撤销的属性变更,请使用 UpdatePropertyCommandelement.updateProperty() 方法。

批量创建

typescript
import { BatchCommand, AddElementCommand } from 'vkedit'

const commands = [
  new AddElementCommand(host, elementManager.createElement('rect')),
  new AddElementCommand(host, elementManager.createElement('text')),
  new AddElementCommand(host, elementManager.createElement('line')),
]

host.executeCommand(new BatchCommand(host, commands, '批量添加元素'))

删除元素

typescript
import { RemoveElementCommand } from 'vkedit'

// 参数:host, element(元素实例)
host.executeCommand(new RemoveElementCommand(host, rect))

也可通过 ElementManagerPlugin 直接删除(不进入撤销栈):

typescript
elementManager.removeElement(rect.id)

序列化与反序列化

元素支持 serialize()deserialize() 方法,用于 JSON 导入导出:

typescript
// 序列化为普通对象
const data = rect.serialize()

// 从普通对象反序列化
const newRect = elementManager.createElement('rect')
newRect.deserialize(data)
newRect.id = data.id // 恢复原 ID

host.toJSON() / host.loadJSON()

通常不需要手动调用序列化方法。host.toJSON() 会自动序列化所有元素,host.loadJSON() 会自动反序列化。

下一步

基于 MIT 许可发布