TextFormatUpdateEvent

可用性有限

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

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

TextFormatUpdateEvent 介面是一個 DOM 事件,它表示輸入法編輯器 (IME) 視窗想要應用於附加到 EditContext 例項的可編輯區域中正在組合的文字的文字格式列表。

此介面繼承自 Event 介面的屬性。

Event TextFormatUpdateEvent

建構函式

TextFormatUpdateEvent() 實驗性

建立一個新的 TextFormatUpdateEvent 物件。

例項方法

TextFormatUpdateEvent.getTextFormats 實驗性

返回一個 Array,其中包含表示 IME 視窗想要應用於文字的格式的 TextFormat 物件。

示例

為 IME 組合的文字設定樣式

在以下示例中,textformatupdate 事件用於更新可編輯區域中文字的格式。

html
<canvas id="editor-canvas"></canvas>
js
const TEXT_X = 10;
const TEXT_Y = 10;

const canvas = document.getElementById("editor-canvas");
const ctx = canvas.getContext("2d");

const editContext = new EditContext();
canvas.editContext = editContext;

editContext.addEventListener("textformatupdate", (e) => {
  // Clear the canvas.
  ctx.clearRect(0, 0, canvas.width, canvas.height);

  // Render the text.
  ctx.fillText(editContext.text, TEXT_X, TEXT_Y);
  console.log(`Rendering text: ${editContext.text}`);

  // Get the text formats that the IME window wants to apply.
  const formats = e.getTextFormats();

  // Iterate over the text formats
  for (const format of formats) {
    const { rangeStart, rangeEnd, underlineStyle, underlineThickness } = format;

    console.log(
      `Applying underline ${underlineThickness} ${underlineStyle} between ${rangeStart} and ${rangeEnd}.`,
    );

    const underlineXStart = ctx.measureText(
      editContext.text.substring(0, rangeStart),
    ).width;
    const underlineXEnd = ctx.measureText(
      editContext.text.substring(0, rangeEnd),
    ).width;
    const underlineY = TEXT_Y + 3;

    // For brevity, this example only draws a simple underline.
    // Use underlineStyle and underlineThickness to draw the correct underline.

    ctx.beginPath();
    ctx.moveTo(TEXT_X + underlineXStart, underlineY);
    ctx.lineTo(TEXT_X + underlineXEnd, underlineY);
    ctx.stroke();
  }
});

規範

規範
EditContext API
# dom-textformatupdateevent

瀏覽器相容性