值
一个字符串,包含已附加到 EditContext 对象的元素的当前可编辑内容。其初始值为空字符串。
此字符串可能与与 EditContext 关联的 DOM 元素的 textContent 属性的值相等,也可能不相等。关联的元素可能是一个 <canvas> 元素,它没有 textContent 属性。或者,关联的元素可能是一个 <div> 元素,其中包含与 EditContext.text 值不同的文本,以便进行更高级的渲染。
EditContext 对象上的 text 属性可用作可编辑文本区域的模型。EditContext 对象上的其他属性,例如 selectionStart 和 selectionEnd,指的是 text 字符串中的偏移量。
示例
使用 text 在可编辑画布中渲染文本
在以下示例中,EditContext API 用于渲染用户在 <canvas> 元素中输入的文本。
html
<canvas id="editor-canvas"></canvas>
js
const canvas = document.getElementById("editor-canvas");
const ctx = canvas.getContext("2d");
const editContext = new EditContext();
canvas.editContext = editContext;
editContext.addEventListener("textupdate", (e) => {
// When the user has focus on the <canvas> and enters text,
// this event is fired, and we use it to re-render the text.
console.log(
`The user entered the text: ${e.text}. Re-rendering the full EditContext text`,
);
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillText(editContext.text, 10, 10);
});
规范
| 规范 |
|---|
| EditContext API # dom-editcontext-text |
浏览器兼容性
加载中…