元素

元素是 Board 上的可见内容:文本、图片、形状和连接线。通过 FBoard facade 修改元素会经过标准命令链路,因此这些改动同样支持撤销、重做和协同编辑。

读取元素

读取活动页面之前,先获取活动 Board。如果只需要稳定的 ID、类型、边界和层级顺序,请使用描述信息,不要依赖完整的内部快照。

TypeScript
const board = univerAPI.getActiveBoard()if (!board) throw new Error('No active board')const elements = board.describeElements()const shapes = board.findElements({  elementType: univerAPI.Enum.BoardElementType.Shape,})

插入形状和文本

插入元素时使用语义方法,不要自行构造底层元素快照。insertShape 的几何信息放在 transform 中,返回的实时形状对象提供文本和样式 API。

TypeScript
const shape = board.insertShape({  shapeType: univerAPI.Enum.ShapeTypeEnum.RoundRect,  transform: { left: 80, top: 80, width: 180, height: 100 },  name: 'Review card',})if (!shape) throw new Error('Cannot insert shape')shape.getText().setText('Review')shape.setRotation(6)

独立文本通过 insertText 添加,图片通过 insertImage 添加。需要在同一条命令中添加多个元素时,使用对应的批量方法。

编辑形状文字

使用下例中 insertShape() 返回的形状,或上一节得到的形状。getText() 返回实时的 FShapeText 对象。调用 getPlainText() 读取纯文本,调用 setText() 替换全部文字,并通过字体、颜色和对齐方法设置格式。

TypeScript
if (!shape) throw new Error('Shape is not available')const shapeText = shape.getText()console.log(shapeText.getPlainText())shapeText  .setText('Quarterly review')  .setFontSize(18)  .setColor('#2563eb')  .setBold(true)  .setHorizontalAlign(univerAPI.Enum.HorizontalAlign.CENTER)  .setVerticalAlign(univerAPI.Enum.VerticalAlign.MIDDLE)

setText() 会替换已有文字。同一个形状需要多种样式时,使用 setRichText()。修改现有富文本时,先调用 getRichText()?.copy(),在构建器上完成修改后传给 setRichText();对独立构建器的修改不会自动写回。更多选项见文字样式和文本框内边距与布局。

TypeScript
const richText = univerAPI.newRichText()  .text('Quarterly ')  .bold('review')shapeText.setRichText(richText)

连接元素

连接线可以连接到已有元素的 ID。后续需要修改样式、标签或端点时,请保留返回的连接线或其 ID。

TypeScript
const target = board.insertShape({  shapeType: univerAPI.Enum.ShapeTypeEnum.Rect,  transform: { left: 360, top: 80, width: 180, height: 100 },})if (!target) throw new Error('Cannot insert target')const connector = board.insertConnector({  fromElementId: shape.getId(),  toElementId: target.getId(),  style: { endMarker: { type: 'filledTriangle', size: 'md' } },})if (!connector) throw new Error('Cannot insert connector')

变换和排列元素

只传入需要修改的属性。层级顺序、对齐、分布和自动布局方法同样接受元素 ID。

TypeScript
if (!board.setElementTransform(shape.getId(), { left: 120, top: 140, rotation: 12 })) {  throw new Error('Cannot transform shape')}if (!board.bringElementsToFront([shape.getId()])) {  throw new Error('Cannot bring shape to front')}

删除元素

removeElement 删除单个元素,removeElements 以原子方式批量删除。两者都会返回命令是否执行成功。

TypeScript
if (!board.removeElements([connector.id, target.getId()])) {  throw new Error('Cannot remove elements')}

需要创建带边框的分组或泳道时,请继续阅读容器与泳道。Boards facade 参考和 Board 元素数据模型提供了更多细节。

你觉得这篇文档如何?

© 2026 DreamNum Co., Ltd.