EditContext: characterboundsupdate 事件

可用性有限

此特性不是基線特性,因為它在一些最廣泛使用的瀏覽器中不起作用。

實驗性: 這是一項實驗性技術
在生產中使用此技術之前,請仔細檢查瀏覽器相容性表格

當作業系統需要了解 EditContext 物件中可編輯文字區域內特定字元的邊界時,會觸發 characterboundsupdate 事件。

這發生在作業系統需要顯示平臺特定的與編輯相關的 UI 表面(例如 輸入法編輯器 (IME) 視窗)時。

characterboundsupdate 事件觸發時,您應該計算文字的字元邊界,然後呼叫 EditContext.updateCharacterBounds() 方法,將作業系統所需的資訊提供給它。

有關何時以及如何使用 characterboundsupdate 事件的更多資訊,請參閱 updateCharacterBounds 方法的文件。

語法

在諸如 addEventListener() 之類的方法中使用事件名稱,或設定事件處理程式屬性。

js
addEventListener("characterboundsupdate", (event) => { })

oncharacterboundsupdate = (event) => { }

事件型別

一個 CharacterBoundsUpdateEvent。繼承自 Event

事件屬性

除了下面列出的屬性之外,父介面 Event 的屬性也可使用。

CharacterBoundsUpdateEvent.rangeStart 只讀

作業系統需要邊界的第一個字元在可編輯區域文字中的偏移量。

CharacterBoundsUpdateEvent.rangeEnd 只讀

作業系統需要邊界的最後一個字元在可編輯區域文字中的偏移量。

示例

在需要時更新字元邊界

此示例展示了當作業系統指示需要資訊時,如何使用 updateCharacterBounds 方法來更新 canvas 元素 EditContext 中的字元邊界。請注意,事件監聽器回撥僅在使用 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));
  }

  console.log("The required character bounds are", charBounds);
  editContext.updateCharacterBounds(e.rangeStart, charBounds);
});

規範

規範
EditContext API
# dom-editcontext-oncharacterboundsupdate

瀏覽器相容性