CharacterBoundsUpdateEvent

可用性有限

此特性不是基线特性,因为它在一些最广泛使用的浏览器中不起作用。

实验性: 这是一项实验性技术
在生产中使用此技术之前,请仔细检查浏览器兼容性表格

CharacterBoundsUpdateEvent 接口是一个 DOM 事件,它代表了操作系统请求获知附加到 EditContext 实例的可编辑区域内特定字符边界的需求。

此接口继承自 Event 接口的属性。

Event CharacterBoundsUpdateEvent

构造函数

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

浏览器兼容性