CharacterBoundsUpdateEvent
CharacterBoundsUpdateEvent 介面是一個 DOM 事件,它代表了作業系統請求獲知附加到 EditContext 例項的可編輯區域內特定字元邊界的需求。
此介面繼承自 Event 介面的屬性。
建構函式
CharacterBoundsUpdateEvent()實驗性-
建立一個新的
CharacterBoundsUpdateEvent物件。
例項屬性
CharacterBoundsUpdateEvent.rangeStart只讀 實驗性-
作業系統需要獲取邊界的可編輯區域文字中第一個字元的偏移量。
CharacterBoundsUpdateEvent.rangeEnd只讀 實驗性-
作業系統需要獲取邊界的可編輯區域文字中最後一個字元的偏移量。
示例
在需要時更新字元邊界
此示例演示瞭如何使用 characterboundsupdate 事件和 updateCharacterBounds 方法來告知作業系統其所需的字元邊界。請注意,僅在使用 IME 視窗或其他特定於平臺的編輯 UI 表面來組合文字時,才會呼叫事件監聽器回撥。
html
<canvas id="editor-canvas"></canvas>
js
const FONT_SIZE = 40;
const FONT = `${FONT_SIZE}px Arial`;
const canvas = document.getElementById("editor-canvas");
const ctx = canvas.getContext("2d");
ctx.font = FONT;
const editContext = new EditContext();
canvas.editContext = editContext;
function computeCharacterBound(offset) {
// Measure the width from the start of the text to the character.
const widthBeforeChar = ctx.measureText(
editContext.text.substring(0, offset),
).width;
// Measure the character width.
const charWidth = ctx.measureText(editContext.text[offset]).width;
const charX = canvas.offsetLeft + widthBeforeChar;
const charY = canvas.offsetTop;
// Return a DOMRect representing the character bounds.
return DOMRect.fromRect({
x: charX,
y: charY - FONT_SIZE,
width: charWidth,
height: FONT_SIZE,
});
}
editContext.addEventListener("characterboundsupdate", (e) => {
const charBounds = [];
for (let offset = e.rangeStart; offset < e.rangeEnd; offset++) {
charBounds.push(computeCharacterBound(offset));
}
// Update the character bounds in the EditContext instance.
editContext.updateCharacterBounds(e.rangeStart, charBounds);
console.log(
"The required character bounds are",
charBounds
.map(
(bound) =>
`(x: ${bound.x}, y: ${bound.y}, width: ${bound.width}, height: ${bound.height})`,
)
.join(", "),
);
});
規範
| 規範 |
|---|
| EditContext API # dom-characterboundsupdateevent |
瀏覽器相容性
載入中…