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

浏览器兼容性