/
index.md
95 lines (73 loc) · 2.25 KB
/
index.md
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
---
title: "EditContext: selectionEnd property"
short-title: selectionEnd
slug: Web/API/EditContext/selectionEnd
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.EditContext.selectionEnd
---
{{APIRef("EditContext API")}}{{SeeCompatTable}}
The **`selectionEnd`** read-only property of the {{domxref("EditContext")}} refers to the offset, within the editable text content, of the end of the current selection.
## Value
A {{jsxref("Number")}}
## Examples
### Using `selectionEnd` to render the user selection in an editable canvas
This example shows how to use the `selectionStart` and `selectionEnd` properties to draw the current selection in a `<canvas>` element that's associated to an `EditContext`.
```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();
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}