EditContext: selectionEnd プロパティ

Limited availability

This feature is not Baseline because it does not work in some of the most widely-used browsers.

Experimental: これは実験的な機能です。
本番で使用する前にブラウザー互換性一覧表をチェックしてください。

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);

  // まず、テキストコンテンツ全体を描画します。
  ctx.fillStyle = "black";
  ctx.fillText(editContext.text, ANCHOR_X, ANCHOR_Y);

  // テキストの始点から選択範囲の始点までの幅を取得します。
  const selectionStartX = ctx.measureText(
    editContext.text.substring(0, editContext.selectionStart),
  );

  // 選択範囲の幅を取得します。
  const selectionWidth = ctx.measureText(
    editContext.text.substring(
      editContext.selectionStart,
      editContext.selectionEnd,
    ),
  );

  // 選択範囲を表すため、テキストの上に長方形を描画します。
  ctx.fillStyle = "blue";
  ctx.fillRect(
    selectionStartX.width + ANCHOR_X,
    ANCHOR_Y - FONT_SIZE,
    selectionWidth.width,
    FONT_SIZE,
  );

  // 選択されたテキストを白で、長方形の上に再描画します。
  ctx.fillStyle = "white";
  ctx.fillText(
    editContext.text.substring(
      editContext.selectionStart,
      editContext.selectionEnd,
    ),
    selectionStartX.width + ANCHOR_X,
    ANCHOR_Y,
  );
}

render();

仕様書

Specification
EditContext API
# dom-editcontextinit-selectionend

ブラウザーの互換性

Report problems with this compatibility data on GitHub
desktopmobile
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
selectionEnd
Experimental

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support
No support
No support
Experimental. Expect behavior to change in the future.