元素
元素是 Board 上的可見內容:文字、圖片、形狀和連線線。透過 FBoard facade 修改元素會經過標準命令鏈路,因此這些改動同樣支援撤銷、重做和協同編輯。
讀取元素
讀取活動頁面之前,先取得活動 Board。如果只需要穩定的 ID、型別、邊界和層級順序,請使用描述資訊,不要依賴完整的內部快照。
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。
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() 替換全部文字,並透過字型、顏色和對齊方法設定格式。
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();對獨立建置器的修改不會自動寫回。更多選項見文字樣式和文字框內邊距與版面配置。
const richText = univerAPI.newRichText() .text('Quarterly ') .bold('review')shapeText.setRichText(richText)連接元素
連線線可以連線到已有元素的 ID。後續需要修改樣式、標籤或端點時,請保留返回的連線線或其 ID。
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。
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 以原子方式批次刪除。兩者都會返回命令是否執行成功。
if (!board.removeElements([connector.id, target.getId()])) { throw new Error('Cannot remove elements')}需要建立帶邊框的分組或泳道時,請繼續閱讀容器與泳道。Boards facade 參考和 Board 元素資料模型提供了更多細節。
你覺得這篇文檔如何?