EditContext:updateCharacterBounds() 方法

可用性有限

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

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

EditContext.updateCharacterBounds() 方法是 EditContext 介面的一部分,應該在響應 characterboundsupdate 事件時呼叫,以將 EditContext 物件中字元的位置和大小告知作業系統。

characterboundsupdate 事件是您唯一需要呼叫 updateCharacterBounds() 方法的時候。

作業系統隨後會使用字元邊界資訊,在需要時正確地定位 輸入法編輯器 (IME) 視窗。在作業系統無法自動檢測字元位置和大小的情況下,例如在 <canvas> 元素中渲染文字時,這一點尤為重要。

語法

js
updateCharacterBounds(rangeStart, characterBounds)

引數

rangeStart

一個數字,表示提供字元邊界的文字範圍的開始。

characterBounds

一個包含 Array 的物件,其中包含表示字元邊界的 DOMRect 物件。

返回值

無 (undefined)。

異常

TypeError

如果方法呼叫的引數少於兩個,或者第一個引數不是數字,或者第二個引數不是可迭代物件(如陣列),則會丟擲此錯誤。

用法說明

避免 IME 視窗位置突然跳動

characterboundsupdate 事件中同步計算字元邊界並呼叫 updateCharacterBounds,可確保作業系統在顯示 IME 視窗時擁有所需的資訊。如果在事件處理程式中未同步呼叫 updateCharacterBounds(),使用者可能會看到 IME 視窗先顯示在錯誤位置,然後再移動到正確位置。

包含哪些字元

updateCharacterBounds() 方法應僅在作業系統指示需要該資訊時呼叫,並且僅針對當前 IME 組合中包含的字元呼叫。

傳遞給 characterboundsupdate 事件處理程式的事件物件包含 rangeStartrangeEnd 屬性,它們指示當前正在組合的字元範圍。updateCharacterBounds() 方法應僅針對此範圍內的字元呼叫。

示例

在需要時更新字元邊界

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

  editContext.updateCharacterBounds(e.rangeStart, charBounds);
});

規範

規範
EditContext API
# dom-editcontext-updatecharacterbounds

瀏覽器相容性

另見