EditContext: selectionEnd 属性
EditContext 的只读属性 selectionEnd 指的是当前选区在可编辑文本内容中的结束偏移量。
值
一个 Number
示例
使用 selectionEnd 在可编辑画布中渲染用户选区
此示例演示了如何使用 selectionStart 和 selectionEnd 属性来绘制与 EditContext 关联的 <canvas> 元素中的当前选区。
html
<canvas id="editor-canvas"></canvas>
js
const ANCHOR_X = 10;
const ANCHOR_Y = 30;
const FONT_SIZE = 20;
const canvas = document.getElementById("editor-canvas");
const ctx = canvas.getContext("2d");
ctx.font = `${FONT_SIZE}px Arial`;
const editContext = new EditContext({
text: "Hello world!",
selectionStart: 6,
selectionEnd: 11,
});
canvas.editContext = editContext;
function render() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Render the entire text content first.
ctx.fillStyle = "black";
ctx.fillText(editContext.text, ANCHOR_X, ANCHOR_Y);
// Get the width from the start of the text to the start of the selection.
const selectionStartX = ctx.measureText(
editContext.text.substring(0, editContext.selectionStart),
);
// Get the width of the selection.
const selectionWidth = ctx.measureText(
editContext.text.substring(
editContext.selectionStart,
editContext.selectionEnd,
),
);
// Draw a rectangle on top of the text to represent the selection.
ctx.fillStyle = "blue";
ctx.fillRect(
selectionStartX.width + ANCHOR_X,
ANCHOR_Y - FONT_SIZE,
selectionWidth.width,
FONT_SIZE,
);
// Re-render just the selected text in white, over the rectangle.
ctx.fillStyle = "white";
ctx.fillText(
editContext.text.substring(
editContext.selectionStart,
editContext.selectionEnd,
),
selectionStartX.width + ANCHOR_X,
ANCHOR_Y,
);
}
render();
规范
| 规范 |
|---|
| EditContext API # dom-editcontextinit-selectionend |
浏览器兼容性
加载中…