值
一個字串,包含已附加到 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 |
瀏覽器相容性
載入中…