EditContext: selectionEnd property - Web APIs

EditContext: selectionEnd property
==================================

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

The **`selectionEnd`** read-only property of the `EditContext` refers to the offset, within the editable text content, of the end of the current selection.

Value
-----

A `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
--------------

| Specification |
| --- |
| EditContext API # dom-editcontextinit-selectionend |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


EditContext: attachedElements() method - Web APIs

EditContext: attachedElements() method
======================================

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

The **`attachedElements()`** method of the `EditContext` interface returns an `Array` that contains only one item. This item is the element that's associated with the `EditContext` object.

Syntax
------

```js
attachedElements()
```

### Return value

An `Array` containing one `HTMLElement` object.

There can only be one element associated to an `EditContext` instance, so the returned array will always contain one element. If the API is extended in the future to support multiple associated elements, the return value will be an array containing multiple elements.

Examples
--------

### Getting the element associated with an `EditContext` instance

This example shows how to use the `attachedElements` method to get the element that's associated with an `EditContext` instance.

```html
<canvas id="editor-canvas"></canvas>
```

```js
const canvas = document.getElementById("editor-canvas");
const editContext = new EditContext();
canvas.editContext = editContext;

const attachedElements = editContext.attachedElements();
console.log(attachedElements[0] === canvas); // true
```

Specifications
--------------

| Specification |
| --- |
| EditContext API # dom-editcontext-attachedelements |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* The `EditContext` interface it belongs to.


EditContext: textupdate event - Web APIs

EditContext: textupdate event
=============================

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

The `textupdate` event of the `EditContext` interface fires when the user has made changes to the text or selection of an editable region that's attached to an `EditContext` instance.

This event makes it possible to render the updated text and selection in the UI, in response to user input.

Syntax
------

Use the event name in methods like `addEventListener()`, or set an event handler property.

```js
addEventListener("textupdate", (event) => {});

ontextupdate = (event) => {};
```

Event type
----------

A `TextUpdateEvent`. Inherits from `Event`.

Event properties
----------------

*In addition to the properties listed below, properties from the parent interface, `Event`, are available.*

`TextUpdateEvent.updateRangeStart` Read only

Returns the index of the first character in the range of text that was updated.

`TextUpdateEvent.updateRangeEnd` Read only

Returns the index of the last character in the range of text that was updated.

`TextUpdateEvent.text` Read only

Returns the text that was inserted in the updated range.

`TextUpdateEvent.selectionStart` Read only

Returns the index of the first character in the new selection range, after the update.

`TextUpdateEvent.selectionEnd` Read only

Returns the index of the last character in the new selection range, after the update.

Examples
--------

### Rendering the updated text on `textupdate`

In the following example, the `textupdate` event of the EditContext API is used to render the text a user enters in an editable `<canvas>` element.

```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} at ${e.updateRangeStart}. Re-rendering the full EditContext text`,
  );
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.fillText(editContext.text, 10, 10);
});
```

Specifications
--------------

| Specification |
| --- |
| EditContext API # dom-editcontext-ontextupdate |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


EditContext: updateControlBounds() method - Web APIs

EditContext: updateControlBounds() method
=========================================

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

The **`EditContext.updateControlBounds()`** method of the `EditContext` interface is used to inform the operating system about the position and size of the editable text region of the `EditContext` object.

Call this method to tell the operating system the bounds of the current editable region. You should call it when initializing the EditContext, and whenever the editable region's bounds change such as when the webpage is resized. These bounds are used to position platform-specific editing-related UI surfaces such as an Input Method Editor (IME) window.

Syntax
------

```js
updateControlBounds(controlBounds)
```

### Parameters

`controlBounds`

A `DOMRect` object representing the new control bounds.

### Exceptions

* If no argument is provided, a `TypeError` `DOMException` is thrown.
* If the provided argument is not a `DOMRect` a `TypeError` `DOMException` is thrown.
Examples
--------

### Updating the control bounds when the editor is initialized and on window resize

This example shows how to use the `updateControlBounds()` method to tell the platform where the editable region is at all times.

```css
#editor {
  border: 1px solid black;
  height: 50vw;
  width: 50vh;
}
```

```html
<div id="editor"></div>
```

```js
const editorEl = document.getElementById("editor");
const editContext = new EditContext();
editorEl.editContext = editContext;

function updateControlBounds() {
  const editorBounds = editorEl.getBoundingClientRect();
  editContext.updateControlBounds(editorBounds);
  console.log(
    `Updated control bounds to ${editorBounds.x}, ${editorBounds.y}, ${editorBounds.width}, ${editorBounds.height}`,
  );
}

// Update the control bounds now.
updateControlBounds();
// And when the page is resized.
window.addEventListener("resize", updateControlBounds);
```

Specifications
--------------

| Specification |
| --- |
| EditContext API # dom-editcontext-updatecontrolbounds |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* The `EditContext` interface it belongs to.


EditContext: selectionStart property - Web APIs

EditContext: selectionStart property
====================================

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

The **`selectionStart`** read-only property of the `EditContext` refers to the offset, within the editable text content, of the start of the current selection.

Value
-----

A `Number`

Examples
--------

### Using `selectionStart` 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
--------------

| Specification |
| --- |
| EditContext API # dom-editcontextinit-selectionstart |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


EditContext: text property - Web APIs

EditContext: text property
==========================

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

The **`text`** read-only property of the `EditContext` interface represents the editable content of the element.

Value
-----

A string containing the current editable content of the element that's attached to the `EditContext` object. Its initial value is the empty string.

This string may or may not be equal to the value of the `textContent` property of the DOM element that's associated to the `EditContext`. The associated element might, for example, be a `<canvas>` element, which doesn't have a `textContent` property. Or, the associated element might be a `<div>` element that contains text that's different than the `EditContext.text` value, for more advanced rendering.

The `text` property of the `EditContext` object can be used as the model for the editable text region. Other properties of the `EditContext` object, such as `selectionStart` and `selectionEnd` refer to offsets within the `text` string.

Examples
--------

### Using `text` to render the text in an editable canvas

In the following example, the EditContext API is used to render the text a user enters in a `<canvas>` element.

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

Specifications
--------------

| Specification |
| --- |
| EditContext API # dom-editcontext-text |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


EditContext: characterBoundsRangeStart property - Web APIs

EditContext: characterBoundsRangeStart property
===============================================

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

The **`characterBoundsRangeStart`** read-only property of the `EditContext` interface indicates the index of the character, within the editable text content, that corresponds to the first item in the `characterBounds` array.

For example, if the `EditContent` contains the characters `abc`, and if `characterBoundRangeStart` is `1`, the first item in the `characterBounds` array contains the bounds for the character `b`.

Value
-----

A `Number`.

Specifications
--------------

| Specification |
| --- |
| EditContext API # dom-editcontext-characterboundsrangestart |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


EditContext: compositionstart event - Web APIs

EditContext: compositionstart event
===================================

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

The `compositionstart` event of the `EditContext` interface fires when composition using a Input Method Editor (IME) window starts.

Syntax
------

Use the event name in methods like `addEventListener()`, or set an event handler property.

```js
addEventListener("compositionstart", (event) => {});

oncompositionstart = (event) => {};
```

Examples
--------

### Using `compositionstart` to change the editable region's border

In the following example, the editable region's border is set to red when the `compositionstart` event fires, and back to black when the `compositionend` event fires. Note that the event listener callbacks in this example are only called when using an IME window, or other platform-specific editing UI surfaces, to compose text.

```css
#text-editor {
  border: 1px solid black;
}
#text-editor.is-composing {
  border-color: red;
}
```

```html
<div id="text-editor"></div>
```

```js
const editorElement = document.getElementById("text-editor");
const editContext = new EditContext();
editorElement.editContext = editContext;

editContext.addEventListener("compositionstart", (event) => {
  editorElement.classList.add("is-composing");
});

editContext.addEventListener("compositionend", (event) => {
  editorElement.classList.remove("is-composing");
});
```

Specifications
--------------

| Specification |
| --- |
| EditContext API # dom-editcontext-oncompositionstart |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


EditContext: compositionend event - Web APIs

EditContext: compositionend event
=================================

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

The `compositionend` event of the `EditContext` interface fires when composition using a Input Method Editor (IME) window ends.

Syntax
------

Use the event name in methods like `addEventListener()`, or set an event handler property.

```js
addEventListener("compositionend", (event) => {});

oncompositionend = (event) => {};
```

Examples
--------

### Using `compositionend` to change the editable region's border

In the following example, the editable region's border is set to red when the `compositionstart` event fires, and back to black when the `compositionend` event fires. Note that the event listener callbacks in this example are only called when using an IME window, or other platform-specific editing UI surfaces, to compose text.

```css
#text-editor {
  border: 1px solid black;
}
#text-editor.is-composing {
  border-color: red;
}
```

```html
<div id="text-editor"></div>
```

```js
const editorElement = document.getElementById("text-editor");
const editContext = new EditContext();
editorElement.editContext = editContext;

editContext.addEventListener("compositionstart", (event) => {
  editorElement.classList.add("is-composing");
});

editContext.addEventListener("compositionend", (event) => {
  editorElement.classList.remove("is-composing");
});
```

Specifications
--------------

| Specification |
| --- |
| EditContext API # dom-editcontext-oncompositionend |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


EditContext: characterBounds() method - Web APIs

EditContext: characterBounds() method
=====================================

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

The **`characterBounds()`** method of the `EditContext` interface returns an `Array` containing the list of bounding rectangles for the characters in the `EditContext` object.

The position and size of the characters in an `EditContext` object is used by the operating system to correctly position platform-specific editing-related UI surfaces such as an Input Method Editor (IME) window when needed. This is especially important in situations where the operating system can't automatically detect the position and size of the characters, such as when rendering text in a `<canvas>` element.

Web developers will most likely be interested in using the `characterboundsupdate` event together with the `EditContext.updateCharacterBounds()` method to update the character bounds when the operating system indicates that it requires information about the position and size of the characters.

The `characterBounds()` method returns the list of character bounds that were last updated with `updateCharacterBounds()`. The list doesn't contain an item for every character in the `EditContext` object, only for the characters that were updated with `updateCharacterBounds()`. To know where the characters are located in the `EditContext` object, use the `EditContext.characterBoundsRangeStart` property.

Syntax
------

```js
characterBounds()
```

### Return value

An `Array` containing `DOMRect` objects.

Specifications
--------------

| Specification |
| --- |
| EditContext API # dom-editcontext-characterbounds |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* The `EditContext` interface it belongs to.


EditContext: updateCharacterBounds() method - Web APIs

EditContext: updateCharacterBounds() method
===========================================

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

The **`EditContext.updateCharacterBounds()`** method of the `EditContext` interface should be called as response to a `characterboundsupdate` event to inform the operating system about the position and size of the characters in the `EditContext` object.

The `characterboundsupdate` event is the only time you need to call the `updateCharacterBounds()` method.

The character bounds information is then used by the operating system to correctly position the Input Method Editor (IME) window when needed. This is especially important in situations where the operating system can't automatically detect the position and size of the characters, such as when rendering text in a `<canvas>` element.

### Avoid sudden jumps in the IME window position

Calculating the character bounds and calling `updateCharacterBounds` synchronously, within the `characterboundsupdate` event ensures that the operating system has the information it needs when it displays the IME window. If you don't call `updateCharacterBounds()` synchronously within the event handler, users may observe the IME window being displayed in the wrong position before being moved to the correct position.

### Which characters to include

The `updateCharacterBounds()` method should only be called when the operating system indicates that it requires the information, and only for the characters that are included in the current IME composition.

The event object passed to the `characterboundsupdate` event handler contains a `rangeStart` and `rangeEnd` properties that indicate the range of characters that are currently being composed. The `updateCharacterBounds()` method should only be called for the characters in this range.

Syntax
------

```js
updateCharacterBounds(rangeStart, characterBounds)
```

### Parameters

`rangeStart`

A number representing the start of the range of text for which character bounds are provided.

`characterBounds`

An `Array` containing `DOMRect` objects representing the character bounds.

### Exceptions

* If less than two arguments are provided, a `TypeError` `DOMException` is thrown.
* if `rangeStart` is not a number or `characterBounds` is not iterable, a `TypeError` `DOMException` is thrown.
Examples
--------

### Updating the character bounds when needed

This example shows how to use the `updateCharacterBounds` method to update the character bounds in the `EditContext` of a `<canvas>` element when the operating system indicates that it requires the information. Note that the `characterboundsupdate` event listener callback in this example is only called when using an IME window, or other platform-specific editing UI surfaces, to compose text.

```html
<canvas id="editor-canvas"></canvas>
```

```js
const FONT\_SIZE = 40;
const FONT = `${FONT\_SIZE}px Arial`;

const canvas = document.getElementById("editor-canvas");
const ctx = canvas.getContext("2d");
ctx.font = FONT;

const editContext = new EditContext();
canvas.editContext = editContext;

function computeCharacterBound(offset) {
  // Measure the width from the start of the text to the character.
  const widthBeforeChar = ctx.measureText(
    editContext.text.substring(0, offset),
  ).width;

  // Measure the character width.
  const charWidth = ctx.measureText(editContext.text[offset]).width;

  const charX = canvas.offsetLeft + widthBeforeChar;
  const charY = canvas.offsetTop;

  // Return a DOMRect representing the character bounds.
  return DOMRect.fromRect({
    x: charX,
    y: charY - FONT\_SIZE,
    width: charWidth,
    height: FONT\_SIZE,
  });
}

editContext.addEventListener("characterboundsupdate", (e) => {
  const charBounds = [];
  for (let offset = e.rangeStart; offset < e.rangeEnd; offset++) {
    charBounds.push(computeCharacterBound(offset));
  }

  editContext.updateCharacterBounds(e.rangeStart, charBounds);
});
```

Specifications
--------------

| Specification |
| --- |
| EditContext API # dom-editcontext-updatecharacterbounds |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* The `EditContext` interface it belongs to.


VRDisplay: submitFrame() method - Web APIs

VRDisplay: submitFrame() method
===============================

**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

The **`submitFrame()`** method of the `VRDisplay` interface captures the current state of the `VRLayerInit` currently being presented and displays it on the `VRDisplay`.

**Note:** This method was part of the old WebVR API. It has been superseded by the WebXR Device API.

The frame should subsequently be rendered using the `VRPose` and matrices provided by the last call to `getFrameData()`.

Syntax
------

```js
submitFrame()
```

### Parameters

None.

### Return value

None (`undefined`).

Examples
--------

```js
const frameData = new VRFrameData();
let vrDisplay;

navigator.getVRDisplays().then((displays) => {
  vrDisplay = displays[0];
  console.log("Display found");
  // Starting the presentation when the button is clicked: It can only be called in response to a user gesture
  btn.addEventListener("click", () => {
    vrDisplay.requestPresent([{ source: canvas }]).then(() => {
      drawVRScene();
    });
  });
});

// WebVR: Draw the scene for the WebVR display.
function drawVRScene() {
  // WebVR: Request the next frame of the animation
  vrSceneFrame = vrDisplay.requestAnimationFrame(drawVRScene);

  // Populate frameData with the data of the next frame to display
  vrDisplay.getFrameData(frameData);

  // You can get the position, orientation, etc. of the display from the current frame's pose
  const curFramePose = frameData.pose;
  const curPos = curFramePose.position;
  const curOrient = curFramePose.orientation;

  // Clear the canvas before we start drawing on it.

  gl.clear(gl.COLOR\_BUFFER\_BIT | gl.DEPTH\_BUFFER\_BIT);

  // WebVR: Create the required projection and view matrix locations needed
  // for passing into the uniformMatrix4fv methods below

  const projectionMatrixLocation = gl.getUniformLocation(
    shaderProgram,
    "projMatrix",
  );
  const viewMatrixLocation = gl.getUniformLocation(shaderProgram, "viewMatrix");

  // WebVR: Render the left eye's view to the left half of the canvas
  gl.viewport(0, 0, canvas.width \* 0.5, canvas.height);
  gl.uniformMatrix4fv(
    projectionMatrixLocation,
    false,
    frameData.leftProjectionMatrix,
  );
  gl.uniformMatrix4fv(viewMatrixLocation, false, frameData.leftViewMatrix);
  drawGeometry();

  // WebVR: Render the right eye's view to the right half of the canvas
  gl.viewport(canvas.width \* 0.5, 0, canvas.width \* 0.5, canvas.height);
  gl.uniformMatrix4fv(
    projectionMatrixLocation,
    false,
    frameData.rightProjectionMatrix,
  );
  gl.uniformMatrix4fv(viewMatrixLocation, false, frameData.rightViewMatrix);
  drawGeometry();

  function drawGeometry() {
    // draw the view for each eye
  }

  // …

  // WebVR: Indicate that we are ready to present the rendered frame to the VR display
  vrDisplay.submitFrame();
}
```

**Note:** You can see this complete code at raw-webgl-example.

Specifications
--------------

This method was part of the old WebVR API that has been superseded by the WebXR Device API. It is no longer on track to becoming a standard.

Until all browsers have implemented the new WebXR APIs, it is recommended to rely on frameworks, like A-Frame, Babylon.js, or Three.js, or a polyfill, to develop WebXR applications that will work across all browsers [1].

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* WebVR API


VRDisplay: stageParameters property - Web APIs

VRDisplay: stageParameters property
===================================

**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

The **`stageParameters`** read-only property of the `VRDisplay` interface returns a `VRStageParameters` object containing room-scale parameters, if the `VRDisplay` is capable of supporting room-scale experiences.

**Note:** This property was part of the old WebVR API. It has been superseded by the WebXR Device API.

Value
-----

`VRStageParameters` object containing the `VRDisplay`'s room-scale parameters, or `null` if the `VRDisplay` is not capable of supporting room-scale experiences.

Examples
--------

See `VRStageParameters` for example code.

Specifications
--------------

This property was part of the old WebVR API that has been superseded by the WebXR Device API. It is no longer on track to becoming a standard.

Until all browsers have implemented the new WebXR APIs, it is recommended to rely on frameworks, like A-Frame, Babylon.js, or Three.js, or a polyfill, to develop WebXR applications that will work across all browsers [1].

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* WebVR API


VRDisplay: getLayers() method - Web APIs

VRDisplay: getLayers() method
=============================

**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

The **`getLayers()`** method of the `VRDisplay` interface returns the layers currently being presented by the `VRDisplay`.

**Note:** This method was part of the old WebVR API. It has been superseded by the WebXR Device API.

Syntax
------

```js
getLayers()
```

### Parameters

None.

### Return value

If the `VRDisplay` is presenting, this method returns an array of the `VRLayerInit` objects currently being presented (this will currently be one, as `VRDisplayCapabilities.maxLayers` is currently always 1). If the `VRDisplay` is not presenting, this method returns an empty array.

Examples
--------

See `VRLayerInit` for example code.

Specifications
--------------

This method was part of the old WebVR API that has been superseded by the WebXR Device API. It is no longer on track to becoming a standard.

Until all browsers have implemented the new WebXR APIs, it is recommended to rely on frameworks, like A-Frame, Babylon.js, or Three.js, or a polyfill, to develop WebXR applications that will work across all browsers [1].

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* WebVR API


VRDisplay: isConnected property - Web APIs

VRDisplay: isConnected property
===============================

**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

The **`isConnected`** read-only property of the `VRDisplay` interface returns a boolean value indicating whether the `VRDisplay` is connected to the computer.

**Note:** This property was part of the old WebVR API. It has been superseded by the WebXR Device API.

Value
-----

A boolean value; `true` means the display is connected; `false` means it isn't.

Examples
--------

```js
navigator.getVRDisplays().then((displays) => {
  // If a display is available, use it to present the scene
  if (displays.length > 0) {
    vrDisplay = displays[0];

    // Starting the presentation when the button is clicked: It can only be called in response to a user gesture
    btn.addEventListener("click", () => {
      // Only request presentation if the display is still connected.
      if (vrDisplay.isConnected) {
        vrDisplay.requestPresent([{ source: canvas }]).then(() => {
          // start rendering the app, etc.
        });
      } else {
        console.log("Connection to display lost");
      }
    });
  }
});
```

Specifications
--------------

This property was part of the old WebVR API that has been superseded by the WebXR Device API. It is no longer on track to becoming a standard.

Until all browsers have implemented the new WebXR APIs, it is recommended to rely on frameworks, like A-Frame, Babylon.js, or Three.js, or a polyfill, to develop WebXR applications that will work across all browsers [1].

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* WebVR API


VRDisplay: depthFar property - Web APIs

VRDisplay: depthFar property
============================

**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

The **`depthFar`** property of the `VRDisplay` interface gets and sets the z-depth defining the far plane of the eye view frustum, i.e. the furthest viewable boundary of the scene.

**Note:** This property was part of the old WebVR API. It has been superseded by the WebXR Device API.

Generally you should leave the value as is, but you might want to reduce it if you are trying to improve performance on slower computers.

Value
-----

 A double, representing the z-depth in meters.
 It initial value is `10000.0`.

Examples
--------

```js
let vrDisplay;

navigator.getVRDisplays().then((displays) => {
  vrDisplay = displays[0];
  vrDisplay.depthNear = 1.0;
  vrDisplay.depthFar = 7500.0;
});
```

Specifications
--------------

This property was part of the old WebVR API that has been superseded by the WebXR Device API. It is no longer on track to becoming a standard.

Until all browsers have implemented the new WebXR APIs, it is recommended to rely on frameworks, like A-Frame, Babylon.js, or Three.js, or a polyfill, to develop WebXR applications that will work across all browsers [1].

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* WebVR API


VRDisplay: isPresenting property - Web APIs

VRDisplay: isPresenting property
================================

**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

The **`isPresenting`** read-only property of the `VRDisplay` interface returns a boolean value indicating whether the `VRDisplay` is currently having content presented through it.

**Note:** This property was part of the old WebVR API. It has been superseded by the WebXR Device API.

Value
-----

A boolean value; `true` means the display is presenting; `false` means it isn't.

Examples
--------

```js
function onVRExitPresent() {
  // No sense in exiting presentation if we're not actually presenting.
  // (This may happen if we get an event like vrdisplaydeactivate when
  // we weren't presenting.)
  if (!vrDisplay.isPresenting) return;
  vrDisplay.exitPresent().then(
    () => {
      // Nothing to do because we're handling things in onVRPresentChange.
    },
    (err) => {
      let errMsg = "exitPresent failed.";
      if (err && err.message) {
        errMsg += `<br/>${err.message}`;
      }
      VRSamplesUtil.addError(errMsg, 2000);
    },
  );
}
```

**Note:** Code snippet taken from Google's VR Presentation demo.

Specifications
--------------

This property was part of the old WebVR API that has been superseded by the WebXR Device API. It is no longer on track to becoming a standard.

Until all browsers have implemented the new WebXR APIs, it is recommended to rely on frameworks, like A-Frame, Babylon.js, or Three.js, or a polyfill, to develop WebXR applications that will work across all browsers [1].

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* WebVR API


VRDisplay: displayName property - Web APIs

VRDisplay: displayName property
===============================

**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

The **`displayName`** read-only property of the `VRDisplay` interface returns a human-readable name to identify the `VRDisplay`.

**Note:** This property was part of the old WebVR API. It has been superseded by the WebXR Device API.

This will generally be something like "Oculus VR HMD (HMD)" or "Oculus VR HMD (Sensor)".

Value
-----

A string containing the human-readable name of the specific VR display.

Examples
--------

See `VRDisplayCapabilities` for example code.

Specifications
--------------

This property was part of the old WebVR API that has been superseded by the WebXR Device API. It is no longer on track to becoming a standard.

Until all browsers have implemented the new WebXR APIs, it is recommended to rely on frameworks, like A-Frame, Babylon.js, or Three.js, or a polyfill, to develop WebXR applications that will work across all browsers [1].

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* WebVR API


VRDisplay: getEyeParameters() method - Web APIs

VRDisplay: getEyeParameters() method
====================================

**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

The **`getEyeParameters()`** method of the `VRDisplay` interface returns the `VREyeParameters` object containing the eye parameters for the specified eye.

**Note:** This method was part of the old WebVR API. It has been superseded by the WebXR Device API.

Syntax
------

```js
getEyeParameters(whichEye)
```

### Parameters

`whichEye`

A string representing the eye you want to return the eye parameters for. Available values are `left` and `right` (defined in the VREye enum).

### Return value

A `VREyeParameters` object, or null if the VR is not able to present content (e.g. `VRDisplayCapabilities.canPresent` returns `false`).

Examples
--------

See `VREyeParameters` for example code.

Specifications
--------------

This method was part of the old WebVR API that has been superseded by the WebXR Device API. It is no longer on track to becoming a standard.

Until all browsers have implemented the new WebXR APIs, it is recommended to rely on frameworks, like A-Frame, Babylon.js, or Three.js, or a polyfill, to develop WebXR applications that will work across all browsers [1].

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* WebVR API


VRDisplay: getFrameData() method - Web APIs

VRDisplay: getFrameData() method
================================

**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

The **`getFrameData()`** method of the `VRDisplay` interface accepts a `VRFrameData` object and populates it with the information required to render the current frame.

**Note:** This method was part of the old WebVR API. It has been superseded by the WebXR Device API.

This includes the `VRPose` and view and projection matrices for the current frame.

Syntax
------

```js
getFrameData(frameData)
```

### Parameters

`frameData`

The `VRFrameData` object you want to populate.

### Return value

A boolean value — a value of `true` is returned if the `VRFrameData` object was successfully populated, or `false` if it wasn't.

Examples
--------

```js
const frameData = new VRFrameData();
let vrDisplay;

navigator.getVRDisplays().then((displays) => {
  vrDisplay = displays[0];
  console.log("Display found");
  // Starting the presentation when the button is clicked: It can only be called in response to a user gesture
  btn.addEventListener("click", () => {
    vrDisplay.requestPresent([{ source: canvas }]).then(() => {
      drawVRScene();
    });
  });
});

// WebVR: Draw the scene for the WebVR display.
function drawVRScene() {
  // WebVR: Request the next frame of the animation
  vrSceneFrame = vrDisplay.requestAnimationFrame(drawVRScene);

  // Populate frameData with the data of the next frame to display
  vrDisplay.getFrameData(frameData);

  // You can get the position, orientation, etc. of the display from the current frame's pose
  // curFramePose is a VRPose object
  const curFramePose = frameData.pose;
  const curPos = curFramePose.position;
  const curOrient = curFramePose.orientation;

  // Clear the canvas before we start drawing on it.

  gl.clear(gl.COLOR\_BUFFER\_BIT | gl.DEPTH\_BUFFER\_BIT);

  // WebVR: Create the required projection and view matrix locations needed
  // for passing into the uniformMatrix4fv methods below

  const projectionMatrixLocation = gl.getUniformLocation(
    shaderProgram,
    "projMatrix",
  );
  const viewMatrixLocation = gl.getUniformLocation(shaderProgram, "viewMatrix");

  // WebVR: Render the left eye's view to the left half of the canvas
  gl.viewport(0, 0, canvas.width \* 0.5, canvas.height);
  gl.uniformMatrix4fv(
    projectionMatrixLocation,
    false,
    frameData.leftProjectionMatrix,
  );
  gl.uniformMatrix4fv(viewMatrixLocation, false, frameData.leftViewMatrix);
  drawGeometry();

  // WebVR: Render the right eye's view to the right half of the canvas
  gl.viewport(canvas.width \* 0.5, 0, canvas.width \* 0.5, canvas.height);
  gl.uniformMatrix4fv(
    projectionMatrixLocation,
    false,
    frameData.rightProjectionMatrix,
  );
  gl.uniformMatrix4fv(viewMatrixLocation, false, frameData.rightViewMatrix);
  drawGeometry();

  function drawGeometry() {
    // draw the view for each eye
  }

  // …

  // WebVR: Indicate that we are ready to present the rendered frame to the VR display
  vrDisplay.submitFrame();
}
```

**Note:** You can see this complete code at raw-webgl-example.

Specifications
--------------

This method was part of the old WebVR API that has been superseded by the WebXR Device API. It is no longer on track to becoming a standard.

Until all browsers have implemented the new WebXR APIs, it is recommended to rely on frameworks, like A-Frame, Babylon.js, or Three.js, or a polyfill, to develop WebXR applications that will work across all browsers [1].

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* WebVR API


VRDisplay: displayId property - Web APIs

VRDisplay: displayId property
=============================

**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

The **`displayId`** read-only property of the `VRDisplay` interface returns an identifier for this particular `VRDisplay`, which is also used as an association point in the Gamepad API (see `Gamepad.displayId`).

**Note:** This property was part of the old WebVR API. It has been superseded by the WebXR Device API.

Value
-----

A number representing the ID of the specific `VRDisplay`.

Examples
--------

See `VRDisplayCapabilities` for example code.

Specifications
--------------

This property was part of the old WebVR API that has been superseded by the WebXR Device API. It is no longer on track to becoming a standard.

Until all browsers have implemented the new WebXR APIs, it is recommended to rely on frameworks, like A-Frame, Babylon.js, or Three.js, or a polyfill, to develop WebXR applications that will work across all browsers [1].

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* WebVR API


VRDisplay: getPose() method - Web APIs

VRDisplay: getPose() method
===========================

**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

The **`getPose()`** method of the `VRDisplay` interface returns a `VRPose` object defining the future predicted pose of the `VRDisplay` as it will be when the current frame is actually presented.

**Note:** This method was part of the old WebVR API. It has been superseded by the WebXR Device API.

It was even deprecated there — instead, you should use `VRDisplay.getFrameData()`, which also provides a `VRPose` object.

Syntax
------

```js
getPose()
```

### Parameters

None.

### Return value

A `VRPose` object.

Examples
--------

Once we have a reference to a `VRDisplay` object, we can retrieve the `VRPose` representing the current pose of the display.

```js
if (navigator.getVRDisplays) {
  console.log("WebVR 1.1 supported");
  // Then get the displays attached to the computer
  navigator.getVRDisplays().then((displays) => {
    // If a display is available, use it to present the scene
    if (displays.length > 0) {
      vrDisplay = displays[0];
      console.log("Display found");

      // Return the current VRPose object for the display
      const pose = vrDisplay.getPose();

      // …
    }
  });
}
```

It is however recommended that you use the non-deprecated `pose` property of the `VRFrameData` object (retrieved via `VRDisplay.getFrameData()`) to retrieve the current pose for each frame before it is submitted to the display to be presented. This happens on each iteration of the rendering loop for your app, so you can be sure the pose data is current.

Specifications
--------------

This method was part of the old WebVR API that has been superseded by the WebXR Device API. It is no longer on track to becoming a standard.

Until all browsers have implemented the new WebXR APIs, it is recommended to rely on frameworks, like A-Frame, Babylon.js, or Three.js, or a polyfill, to develop WebXR applications that will work across all browsers [1].

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* WebVR API


VRDisplay: cancelAnimationFrame() method - Web APIs

VRDisplay: cancelAnimationFrame() method
========================================

**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

The **`cancelAnimationFrame()`** method of the `VRDisplay` interface is a special implementation of `Window.cancelAnimationFrame` that unregisters callbacks registered with `VRDisplay.requestAnimationFrame()`.

**Note:** This method was part of the old WebVR API. It has been superseded by the WebXR Device API.

Syntax
------

```js
cancelAnimationFrame(handle)
```

### Parameters

`handle`

The handle returned by the `VRDisplay.requestAnimationFrame()` call that you want to unregister.

### Return value

None (`undefined`).

Examples
--------

```js
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
drawScene();

// WebVR: Check to see if WebVR is supported
if (navigator.getVRDisplays) {
  console.log("WebVR 1.1 supported");
  // Then get the displays attached to the computer
  navigator.getVRDisplays().then((displays) => {
    // If a display is available, use it to present the scene
    if (displays.length > 0) {
      vrDisplay = displays[0];
      console.log("Display found");
      // Starting the presentation when the button is clicked: It can only be called in response to a user gesture
      btn.addEventListener("click", () => {
        if (btn.textContent === "Start VR display") {
          vrDisplay.requestPresent([{ source: canvas }]).then(() => {
            console.log("Presenting to WebVR display");

            // Set the canvas size to the size of the vrDisplay viewport

            const leftEye = vrDisplay.getEyeParameters("left");
            const rightEye = vrDisplay.getEyeParameters("right");

            canvas.width =
              Math.max(leftEye.renderWidth, rightEye.renderWidth) \* 2;
            canvas.height = Math.max(
              leftEye.renderHeight,
              rightEye.renderHeight,
            );

            // stop the normal presentation, and start the vr presentation
            window.cancelAnimationFrame(normalSceneFrame);
            drawVRScene();

            btn.textContent = "Exit VR display";
          });
        } else {
          vrDisplay.exitPresent();
          console.log("Stopped presenting to WebVR display");

          btn.textContent = "Start VR display";

          // Stop the VR presentation, and start the normal presentation
          vrDisplay.cancelAnimationFrame(vrSceneFrame);
          drawScene();
        }
      });
    }
  });
} else {
  info.textContent = "WebVR API not supported by this browser.";
}

function drawVRScene() {
  // WebVR: Request the next frame of the animation
  vrSceneFrame = vrDisplay.requestAnimationFrame(drawVRScene);

  // …
}
```

**Note:** You can see this complete code at raw-webgl-example.

Specifications
--------------

This method was part of the old WebVR API that has been superseded by the WebXR Device API. It is no longer on track to becoming a standard.

Until all browsers have implemented the new WebXR APIs, it is recommended to rely on frameworks, like A-Frame, Babylon.js, or Three.js, or a polyfill, to develop WebXR applications that will work across all browsers [1].

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* WebVR API


VRDisplay: resetPose() method - Web APIs

VRDisplay: resetPose() method
=============================

**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

The **`resetPose()`** method of the `VRDisplay` interface resets the pose for the `VRDisplay`, treating its current `VRPose.position` and `VRPose.orientation` as the "origin/zero" values.

**Note:** This method was part of the old WebVR API. It has been superseded by the WebXR Device API.

After `resetPost()` has been called, future poses returned from `VRDisplay.getPose()`/`VRDisplay.getImmediatePose()` will describe positions relative to the `VRDisplay`'s position when `resetPose()` was last called and will treat the display's yaw when `resetPose()` was last called as the forward orientation.

The VRDisplay's reported roll and pitch do not change when `resetPose()` is called as they are relative to gravity. Calling `resetPose()` may change the `VRStageParameters.sittingToStandingTransform` matrix.

Syntax
------

```js
resetPose()
```

### Parameters

None.

### Return value

None (`undefined`).

Examples
--------

```js
// Assuming vrDisplay already contains a VRDisplay object,
// and we have a <button> referenced inside btn
btn.addEventListener("click", () => {
  vrDisplay.resetPose();
  console.log("Current pose set as origin/center");
});
```

Specifications
--------------

This method was part of the old WebVR API that has been superseded by the WebXR Device API. It is no longer on track to becoming a standard.

Until all browsers have implemented the new WebXR APIs, it is recommended to rely on frameworks, like A-Frame, Babylon.js, or Three.js, or a polyfill, to develop WebXR applications that will work across all browsers [1].

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* WebVR API


VRDisplay: capabilities property - Web APIs

VRDisplay: capabilities property
================================

**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

The **`capabilities`** read-only property of the `VRDisplay` interface returns a `VRDisplayCapabilities` object that indicates the various capabilities of the `VRDisplay`.

**Note:** This property was part of the old WebVR API. It has been superseded by the WebXR Device API.

Value
-----

A `VRDisplayCapabilities` object.

Examples
--------

See `VRDisplayCapabilities` for example code.

Specifications
--------------

This property was part of the old WebVR API that has been superseded by the WebXR Device API. It is no longer on track to becoming a standard.

Until all browsers have implemented the new WebXR APIs, it is recommended to rely on frameworks, like A-Frame, Babylon.js, or Three.js, or a polyfill, to develop WebXR applications that will work across all browsers [1].

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* WebVR API


VRDisplay: depthNear property - Web APIs

VRDisplay: depthNear property
=============================

**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

The **`depthNear`** property of the `VRDisplay` interface gets and sets the z-depth defining the near plane of the eye view frustum, i.e. the nearest viewable boundary of the scene.

**Note:** This property was part of the old WebVR API. It has been superseded by the WebXR Device API.

Generally you should leave the value as is, but you might want to increase it if you are trying to improve performance on slower computers, and/or your UI makes sense with the near boundary made further away.

Value
-----

A double, representing the z-depth in meters; its initial value is `0.01`.

Examples
--------

```js
let vrDisplay;

navigator.getVRDisplays().then((displays) => {
  vrDisplay = displays[0];
  vrDisplay.depthNear = 1.0;
  vrDisplay.depthFar = 7500.0;
});
```

Specifications
--------------

This property was part of the old WebVR API that has been superseded by the WebXR Device API. It is no longer on track to becoming a standard.

Until all browsers have implemented the new WebXR APIs, it is recommended to rely on frameworks, like A-Frame, Babylon.js, or Three.js, or a polyfill, to develop WebXR applications that will work across all browsers [1].

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* WebVR API


VRDisplay: exitPresent() method - Web APIs

VRDisplay: exitPresent() method
===============================

**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

The **`exitPresent()`** method of the `VRDisplay` interface stops the `VRDisplay` presenting a scene.

**Note:** This method was part of the old WebVR API. It has been superseded by the WebXR Device API.

Syntax
------

```js
exitPresent()
```

### Parameters

None.

### Return value

A promise that resolves once the presentation has ended. If the `VRDisplay` is not presenting when `exitPresent()` is called, the promise will reject.

Examples
--------

```js
if (navigator.getVRDisplays) {
  console.log("WebVR 1.1 supported");
  // Then get the displays attached to the computer
  navigator.getVRDisplays().then((displays) => {
    // If a display is available, use it to present the scene
    if (displays.length > 0) {
      vrDisplay = displays[0];
      console.log("Display found");
      // Starting the presentation when the button is clicked: It can only be called in response to a user gesture
      btn.addEventListener("click", () => {
        if (btn.textContent === "Start VR display") {
          vrDisplay.requestPresent([{ source: canvas }]).then(() => {
            console.log("Presenting to WebVR display");

            // Set the canvas size to the size of the vrDisplay viewport

            const leftEye = vrDisplay.getEyeParameters("left");
            const rightEye = vrDisplay.getEyeParameters("right");

            canvas.width =
              Math.max(leftEye.renderWidth, rightEye.renderWidth) \* 2;
            canvas.height = Math.max(
              leftEye.renderHeight,
              rightEye.renderHeight,
            );

            // stop the normal presentation, and start the vr presentation
            window.cancelAnimationFrame(normalSceneFrame);
            drawVRScene();

            btn.textContent = "Exit VR display";
          });
        } else {
          vrDisplay.exitPresent();
          console.log("Stopped presenting to WebVR display");

          btn.textContent = "Start VR display";

          // Stop the VR presentation, and start the normal presentation
          vrDisplay.cancelAnimationFrame(vrSceneFrame);
          drawScene();
        }
      });
    }
  });
}
```

**Note:** You can see this complete code at raw-webgl-example.

Specifications
--------------

This method was part of the old WebVR API that has been superseded by the WebXR Device API. It is no longer on track to becoming a standard.

Until all browsers have implemented the new WebXR APIs, it is recommended to rely on frameworks, like A-Frame, Babylon.js, or Three.js, or a polyfill, to develop WebXR applications that will work across all browsers [1].

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* WebVR API


VRDisplay: requestAnimationFrame() method - Web APIs

VRDisplay: requestAnimationFrame() method
=========================================

**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

The **`requestAnimationFrame()`** method of the `VRDisplay` interface is a special implementation of `Window.requestAnimationFrame` containing a callback function that will be called every time a new frame of the `VRDisplay` presentation is rendered:

**Note:** This method was part of the old WebVR API. It has been superseded by the WebXR Device API.

* When the `VRDisplay` is not presenting a scene, this is functionally equivalent to `Window.requestAnimationFrame`.
* When the `VRDisplay` is presenting, the callback is called at its native refresh rate.
Syntax
------

```js
requestAnimationFrame(callback)
```

### Parameters

`callback`

A callback function that will be called every time a new frame of the `VRDisplay` presentation is rendered.

### Return value

A long representing the handle of the `requestAnimationFrame()` call. This can then be passed to a `VRDisplay.cancelAnimationFrame()` call to unregister the callback.

Examples
--------

```js
const frameData = new VRFrameData();
let vrDisplay;

navigator.getVRDisplays().then((displays) => {
  vrDisplay = displays[0];
  console.log("Display found");
  // Starting the presentation when the button is clicked: It can only be called in response to a user gesture
  btn.addEventListener("click", () => {
    vrDisplay.requestPresent([{ source: canvas }]).then(() => {
      drawVRScene();
    });
  });
});

// WebVR: Draw the scene for the WebVR display.
function drawVRScene() {
  // WebVR: Request the next frame of the animation
  vrSceneFrame = vrDisplay.requestAnimationFrame(drawVRScene);

  // Populate frameData with the data of the next frame to display
  vrDisplay.getFrameData(frameData);

  // You can get the position, orientation, etc. of the display from the current frame's pose
  const curFramePose = frameData.pose;
  const curPos = curFramePose.position;
  const curOrient = curFramePose.orientation;

  // Clear the canvas before we start drawing on it.

  gl.clear(gl.COLOR\_BUFFER\_BIT | gl.DEPTH\_BUFFER\_BIT);

  // WebVR: Create the required projection and view matrix locations needed
  // for passing into the uniformMatrix4fv methods below

  const projectionMatrixLocation = gl.getUniformLocation(
    shaderProgram,
    "projMatrix",
  );
  const viewMatrixLocation = gl.getUniformLocation(shaderProgram, "viewMatrix");

  // WebVR: Render the left eye's view to the left half of the canvas
  gl.viewport(0, 0, canvas.width \* 0.5, canvas.height);
  gl.uniformMatrix4fv(
    projectionMatrixLocation,
    false,
    frameData.leftProjectionMatrix,
  );
  gl.uniformMatrix4fv(viewMatrixLocation, false, frameData.leftViewMatrix);
  drawGeometry();

  // WebVR: Render the right eye's view to the right half of the canvas
  gl.viewport(canvas.width \* 0.5, 0, canvas.width \* 0.5, canvas.height);
  gl.uniformMatrix4fv(
    projectionMatrixLocation,
    false,
    frameData.rightProjectionMatrix,
  );
  gl.uniformMatrix4fv(viewMatrixLocation, false, frameData.rightViewMatrix);
  drawGeometry();

  function drawGeometry() {
    // draw the view for each eye
  }

  // …

  // WebVR: Indicate that we are ready to present the rendered frame to the VR display
  vrDisplay.submitFrame();
}
```

**Note:** You can see this complete code at raw-webgl-example.

Specifications
--------------

This method was part of the old WebVR API that has been superseded by the WebXR Device API. It is no longer on track to becoming a standard.

Until all browsers have implemented the new WebXR APIs, it is recommended to rely on frameworks, like A-Frame, Babylon.js, or Three.js, or a polyfill, to develop WebXR applications that will work across all browsers [1].

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* WebVR API


VRDisplay: requestPresent() method - Web APIs

VRDisplay: requestPresent() method
==================================

**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

The **`requestPresent()`** method of the `VRDisplay` interface starts the `VRDisplay` presenting a scene.

**Note:** This method was part of the old WebVR API. It has been superseded by the WebXR Device API.

Syntax
------

```js
requestPresent(layers)
```

### Parameters

`layers`

An array of `VRLayerInit` objects representing the scene you want to present. At the moment, this can be a minimum of 0 and a maximum of 1.

### Return value

A promise that resolves once the presentation has begun. There are a number of rules surrounding the promise's fulfillment or rejection:

* If `VRDisplayCapabilities.canPresent` is false, or if the VRLayer array contains more than `VRDisplayCapabilities.maxLayers` layers, the promise will be rejected.
* If the `VRDisplay` is already presenting when `requestPresent()` is called, the `VRDisplay` will update the `VRLayer` array being presented.
* If a call to `requestPresent()` is rejected while the `VRDisplay` is already presenting it will end its presentation.
* If `requestPresent()` is called outside of an engagement gesture the promise will be rejected unless the `VRDisplay` was already presenting. This engagement gesture is also sufficient to allow `requestPointerLock()` calls until presentation has ended.
Examples
--------

```js
if (navigator.getVRDisplays) {
  console.log("WebVR 1.1 supported");
  // Then get the displays attached to the computer
  navigator.getVRDisplays().then((displays) => {
    // If a display is available, use it to present the scene
    if (displays.length > 0) {
      vrDisplay = displays[0];
      console.log("Display found");
      // Starting the presentation when the button is clicked: It can only be called in response to a user gesture
      btn.addEventListener("click", () => {
        if (btn.textContent === "Start VR display") {
          vrDisplay.requestPresent([{ source: canvas }]).then(() => {
            console.log("Presenting to WebVR display");

            // Set the canvas size to the size of the vrDisplay viewport

            const leftEye = vrDisplay.getEyeParameters("left");
            const rightEye = vrDisplay.getEyeParameters("right");

            canvas.width =
              Math.max(leftEye.renderWidth, rightEye.renderWidth) \* 2;
            canvas.height = Math.max(
              leftEye.renderHeight,
              rightEye.renderHeight,
            );

            // stop the normal presentation, and start the vr presentation
            window.cancelAnimationFrame(normalSceneFrame);
            drawVRScene();

            btn.textContent = "Exit VR display";
          });
        } else {
          vrDisplay.exitPresent();
          console.log("Stopped presenting to WebVR display");

          btn.textContent = "Start VR display";

          // Stop the VR presentation, and start the normal presentation
          vrDisplay.cancelAnimationFrame(vrSceneFrame);
          drawScene();
        }
      });
    }
  });
}
```

**Note:** You can see this complete code at raw-webgl-example.

Specifications
--------------

This method was part of the old WebVR API that has been superseded by the WebXR Device API. It is no longer on track to becoming a standard.

Until all browsers have implemented the new WebXR APIs, it is recommended to rely on frameworks, like A-Frame, Babylon.js, or Three.js, or a polyfill, to develop WebXR applications that will work across all browsers [1].

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* WebVR API


VRDisplay: getImmediatePose() method - Web APIs

VRDisplay: getImmediatePose() method
====================================

**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

The **`getImmediatePose()`** method of the `VRDisplay` interface returns a `VRPose` object defining the current pose of the `VRDisplay`, with no prediction applied.

**Note:** This method was part of the old WebVR API. It has been superseded by the WebXR Device API.

Syntax
------

```js
getImmediatePose()
```

### Parameters

None.

### Return value

A `VRPose` object.

Specifications
--------------

This method was part of the old WebVR API that has been superseded by the WebXR Device API. It is no longer on track to becoming a standard.

Until all browsers have implemented the new WebXR APIs, it is recommended to rely on frameworks, like A-Frame, Babylon.js, or Three.js, or a polyfill, to develop WebXR applications that will work across all browsers [1].

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* WebVR API


CSSPositionValue: CSSPositionValue() constructor - Web APIs

CSSPositionValue: CSSPositionValue() constructor
================================================

**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

 The **`CSSPositionValue()`** constructor
 creates a new `CSSPositionValue` object which represents values for
 properties that take a position, for example `object-position`.

Syntax
------

```js
new CSSPositionValue(x, y)
```

### Parameters

`x`

A position along the web page's horizontal axis.

`y`

A position along the web page's vertical axis.

Examples
--------

 The following example positions a container `<div>` 5 pixels from the
 top and 10 pixels from the left of the page.

```js
let someDiv = document.getElementById("container");
let position = new CSSPositionValue(CSS.px(5), CSS.px(10));

someDiv.attributeStyleMap.set("object-position", position);
console.log(position.x.value, position.y.value); // 5 10
```

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `CSSPositionValue.x`
* `CSSPositionValue.y`
* Using the CSS Typed OM
* CSS Typed Object Model API


CSSPositionValue: y property - Web APIs

CSSPositionValue: y property
============================

**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

 The **`y`** property of the
 `CSSPositionValue` interface returns the item's position along the
 vertical axis.

Value
-----

A `CSSNumericValue`.

Examples
--------

 The following example positions a container `<div>` 5 pixels from the
 top and 10 pixels from the left of the page.

```js
let replaceEl = document.getElementById("container");
let position = new CSSPositionValue(CSS.px(5), CSS.px(10));

someDiv.attributeStyleMap.set("object-position", position);
console.log(position.x.value, position.y.value);
```

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `CSSPositionValue()`
* `CSSPositionValue.x`
* Using the CSS Typed OM
* CSS Typed Object Model API


CSSPositionValue: x property - Web APIs

CSSPositionValue: x property
============================

**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

 The **`x`** property of the
 `CSSPositionValue` interface returns the item's position along the web
 page's horizontal axis.

Value
-----

A `CSSNumericValue`.

Examples
--------

 The following example positions a container `<div>` 5 pixels from the
 top and 10 pixels from the left of the page.

```js
let someDiv = document.getElementById("container");
let position = new CSSPositionValue(CSS.px(5), CSS.px(10));

someDiv.attributeStyleMap.set("object-position", position);
console.log(position.x.value, position.y.value);
```

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `CSSPositionValue()`
* `CSSPositionValue.y`
* Using the CSS Typed OM
* CSS Typed Object Model API


CloseEvent: code property - Web APIs

CloseEvent: code property
=========================

The **`code`** read-only property of the `CloseEvent` interface returns a WebSocket connection close code indicating the reason the server gave for closing the connection.

Value
-----

An integer WebSocket connection close code in the range `1000` - `4999`, indicating the reason the server gave for closing the connection.

| Status code | Meaning | Description |
| --- | --- | --- |
| `0`–`999` |  | Not used. |
| `1000` | Normal Closure |
 The connection successfully completed the purpose for which it was
 created.
  |
| `1001` | Going Away |
 The endpoint is going away, either because of a server failure or
 because the browser is navigating away from the page that opened the
 connection.
  |
| `1002` | Protocol error | The endpoint is terminating the connection due to a protocol error. |
| `1003` | Unsupported Data |
 The connection is being terminated because the endpoint received data of
 a type it cannot accept. (For example, a text-only endpoint received
 binary data.)
  |
| `1004` | Reserved | **Reserved.** A meaning might be defined in the future. |
| `1005` | No Status Rcvd | **Reserved.** Indicates that no status code was provided even though one was expected. |
| `1006` | Abnormal Closure | **Reserved.** Indicates that a connection was closed abnormally (that is, with no
 close frame being sent) when a status code is expected.
  |
| `1007` | Invalid frame payload data |
 The endpoint is terminating the connection because a message was
 received that contained inconsistent data (e.g., non-UTF-8 data within a
 text message).
  |
| `1008` | Policy Violation |
 The endpoint is terminating the connection because it received a message
 that violates its policy. This is a generic status code, used when codes
 1003 and 1009 are not suitable.
  |
| `1009` | Message Too Big |
 The endpoint is terminating the connection because a data frame was
 received that is too large.
  |
| `1010` | Mandatory Ext. |
 The client is terminating the connection because it expected the server
 to negotiate one or more extension, but the server didn't.
  |
| `1011` | Internal Error |
 The server is terminating the connection because it encountered an
 unexpected condition that prevented it from fulfilling the request.
  |
| `1012` | Service Restart | The server is terminating the connection because it is restarting. |
| `1013` | Try Again Later |
 The server is terminating the connection due to a temporary condition,
 e.g. it is overloaded and is casting off some of its clients.
  |
| `1014` | Bad Gateway |
 The server was acting as a gateway or proxy and received an invalid
 response from the upstream server. This is similar to 502 HTTP Status
 Code.
  |
| `1015` | TLS handshake | **Reserved.** Indicates that the connection was closed due
 to a failure to perform a TLS handshake (e.g., the server certificate
 can't be verified).
  |
| `1016`–`2999` |  | For definition by future revisions of the WebSocket Protocol specification, and for definition by extension specifications. |
| `3000`–`3999` |  | For use by libraries, frameworks, and applications. These status codes are registered directly with IANA. The interpretation of these codes is undefined by the WebSocket protocol. |
| `4000`–`4999` |  | For private use, and thus can't be registered. Such codes can be used by prior agreements between WebSocket applications. The interpretation of these codes is undefined by the WebSocket protocol. |

Examples
--------

The following example prints the value of `code` to the console.

```js
WebSocket.onclose = (event) => {
  console.log(event.code);
};
```

Specifications
--------------

| Specification |
| --- |
| WebSockets Standard # ref-for-dom-closeevent-code② |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* RFC 6455 (the WebSocket Protocol specification)
* WebSocket Close Code Number Registry (IANA)


CloseEvent: wasClean property - Web APIs

CloseEvent: wasClean property
=============================

The **`wasClean`** read-only property of the `CloseEvent` interface returns `true` if the connection closed cleanly.

Value
-----

A boolean value. True if the connection closed cleanly, false otherwise.

Examples
--------

The following example prints the value of `wasClean` to the console.

```js
WebSocket.onclose = (event) => {
  console.log(event.wasClean);
};
```

Specifications
--------------

| Specification |
| --- |
| WebSockets Standard # ref-for-dom-closeevent-wasclean② |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


CloseEvent: reason property - Web APIs

CloseEvent: reason property
===========================

The **`reason`** read-only property of the `CloseEvent` interface returns the WebSocket connection close reason the server gave for closing the connection; that is, a concise human-readable prose explanation for the closure.

Value
-----

A string.

Examples
--------

The following example prints the value of `reason` to the console.

```js
WebSocket.onclose = (event) => {
  console.log(event.reason);
};
```

Specifications
--------------

| Specification |
| --- |
| WebSockets Standard # ref-for-dom-closeevent-reason② |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* RFC 6455 (the WebSocket Protocol specification)


CloseEvent: CloseEvent() constructor - Web APIs

CloseEvent: CloseEvent() constructor
====================================

The **`CloseEvent()`** constructor creates a new `CloseEvent` object.

Syntax
------

```js
new CloseEvent(type)
new CloseEvent(type, options)
```

### Parameters

`type`

 A string with the name of the event.
 It is case-sensitive and browsers always set it to `close`.

`options` Optional

An object that, *in addition of the properties defined in `Event()`*, has the following properties:

`wasClean` Optional

A boolean value indicating if the connection has been closed cleanly or not. It defaults to `false`.

`code` Optional

An integer representing the *connection close code* sent by the server. It defaults to `0`.

`reason` Optional

A string containing a human-readable reason describing why the server closed the connection. It defaults to `''`

Return value
------------

A new `CloseEvent` object.

Specifications
--------------

| Specification |
| --- |
| WebSockets Standard # dom-closeevent-closeevent |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `CloseEvent`, the interface of the objects it constructs.


SVGGeometryElement: pathLength property - Web APIs

SVGGeometryElement: pathLength property
=======================================

 The **`SVGGeometryElement.pathLength`** property reflects the
 `pathLength` attribute and returns the total length of the path, in user units.

Value
-----

A number.

Specifications
--------------

| Specification |
| --- |
| Scalable Vector Graphics (SVG) 2 # \_\_svg\_\_SVGGeometryElement\_\_pathLength |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


SVGGeometryElement: isPointInFill() method - Web APIs

SVGGeometryElement: isPointInFill() method
==========================================

 The **`SVGGeometryElement.isPointInFill()`** method determines
 whether a given point is within the fill shape of an element. Normal hit testing rules
 apply; the value of the `pointer-events` property on the element determines
 whether a point is considered to be within the fill. The `point` argument is
 interpreted as a point in the local coordinate system of the element.

Syntax
------

```js
isPointInFill(point)
```

### Parameters

`point`

 A DOMPointInit object interpreted as a point in the local coordinate system
 of the element.

### Return value

A boolean indicating whether the given point is within the fill or not.

Examples
--------

### SVG

```html
<svg
 viewBox="0 0 100 100"
 width="150"
 height="150"
 xmlns="http://www.w3.org/2000/svg">
  <circle
 id="circle"
 cx="50"
 cy="50"
 r="45"
 fill="white"
 stroke="black"
 stroke-width="10" />
</svg>
```

### JavaScript

```js
const svg = document.getElementsByTagName("svg")[0];
const circle = document.getElementById("circle");
const points = [
  ["10", "10"],
  ["40", "30"],
  ["70", "40"],
  ["15", "75"],
  ["83", "83"],
];

for (const point of points) {
  let isPointInFill;

  try {
    const pointObj = new DOMPoint(point[0], point[1]);
    isPointInFill = circle.isPointInFill(pointObj);
  } catch (e) {
    // Fallback for browsers that don't support DOMPoint as an argument
    const pointObj = svg.createSVGPoint();
    pointObj.x = point[0];
    pointObj.y = point[1];
    isPointInFill = circle.isPointInFill(pointObj);
  }

  console.log(`Point at ${point[0]},${point[1]}: ${isPointInFill}`);

  const pointEl = document.createElementNS(
    "http://www.w3.org/2000/svg",
    "circle",
  );
  pointEl.style.cx = point[0];
  pointEl.style.cy = point[1];
  pointEl.style.r = 5;
  pointEl.style.fill = isPointInFill ? "seagreen" : "rgb(255 0 0 / 50%)";
  svg.appendChild(pointEl);
}
```

### Result

Specifications
--------------

| Specification |
| --- |
| Scalable Vector Graphics (SVG) 2 # \_\_svg\_\_SVGGeometryElement\_\_isPointInFill |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


SVGGeometryElement: getPointAtLength() method - Web APIs

SVGGeometryElement: getPointAtLength() method
=============================================

 The
 **`SVGGeometryElement.getPointAtLength()`** method returns the
 point at a given distance along the path.

Syntax
------

```js
getPointAtLength(distance)
```

### Parameters

`distance`

A float referring to the distance along the path.

### Return value

A `DOMPoint` indicating the point at a given distance along the path.

Specifications
--------------

| Specification |
| --- |
| Scalable Vector Graphics (SVG) 2 # \_\_svg\_\_SVGGeometryElement\_\_getPointAtLength |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


SVGGeometryElement: isPointInStroke() method - Web APIs

SVGGeometryElement: isPointInStroke() method
============================================

 The **`SVGGeometryElement.isPointInStroke()`** method
 determines whether a given point is within the stroke shape of an element. Normal hit
 testing rules apply; the value of the `pointer-events` property on the
 element determines whether a point is considered to be within the stroke. The
 `point` argument is interpreted as a point in the local coordinate system of
 the element.

Syntax
------

```js
isPointInStroke(point)
```

### Parameters

`point`

 An object interpreted as a point in the local coordinate system
 of the element.

### Return value

A boolean indicating whether the given point is within the stroke or not.

Examples
--------

### SVG

```html
<svg
 viewBox="0 0 100 100"
 width="150"
 height="150"
 xmlns="http://www.w3.org/2000/svg">
  <circle
 id="circle"
 cx="50"
 cy="50"
 r="45"
 fill="white"
 stroke="black"
 stroke-width="10" />
</svg>
```

### JavaScript

```js
const svg = document.getElementsByTagName("svg")[0];
const circle = document.getElementById("circle");
const points = [
  ["10", "10"],
  ["40", "30"],
  ["70", "40"],
  ["15", "75"],
  ["83", "83"],
];

for (const point of points) {
  let isPointInStroke;

  try {
    const pointObj = new DOMPoint(point[0], point[1]);
    isPointInFill = circle.isPointInStroke(pointObj);
  } catch (e) {
    // Fallback for browsers that don't support DOMPoint as an argument
    const pointObj = svg.createSVGPoint();
    pointObj.x = point[0];
    pointObj.y = point[1];
    isPointInStroke = circle.isPointInStroke(pointObj);
  }

  console.log(`Point at ${point[0]},${point[1]}: ${isPointInStroke}`);

  const pointEl = document.createElementNS(
    "http://www.w3.org/2000/svg",
    "circle",
  );
  pointEl.style.cx = point[0];
  pointEl.style.cy = point[1];
  pointEl.style.r = 5;
  pointEl.style.fill = isPointInStroke ? "seagreen" : "rgb(255 0 0 / 50%)";
  svg.appendChild(pointEl);
}
```

### Result

Specifications
--------------

| Specification |
| --- |
| Scalable Vector Graphics (SVG) 2 # \_\_svg\_\_SVGGeometryElement\_\_isPointInStroke |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


SVGGeometryElement: getTotalLength() method - Web APIs

SVGGeometryElement: getTotalLength() method
===========================================

 The **`SVGGeometryElement.getTotalLength()`** method returns
 the user agent's computed value for the total length of the path in user units.

Syntax
------

```js
getTotalLength()
```

### Parameters

None.

### Return value

A float indicating the total length of the path in user units.

Specifications
--------------

| Specification |
| --- |
| Scalable Vector Graphics (SVG) 2 # \_\_svg\_\_SVGGeometryElement\_\_getTotalLength |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


GPUAdapterInfo: description property - Web APIs

GPUAdapterInfo: description property
====================================

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

 The **`description`** read-only property of the
 `GPUAdapterInfo` interface returns a human-readable string describing the adapter, or an empty string if it is not available.

Value
-----

A string.

Examples
--------

```js
async function init() {
  if (!navigator.gpu) {
    throw Error("WebGPU not supported.");
  }

  const adapter = await navigator.gpu.requestAdapter();
  if (!adapter) {
    throw Error("Couldn't request WebGPU adapter.");
  }

  const adapterInfo = await adapter.requestAdapterInfo();
  console.log(adapterInfo.description);

  // ...
}
```

Specifications
--------------

| Specification |
| --- |
| WebGPU # dom-gpuadapterinfo-description |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* The WebGPU API


GPUAdapterInfo: vendor property - Web APIs

GPUAdapterInfo: vendor property
===============================

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

 The **`vendor`** read-only property of the
 `GPUAdapterInfo` interface returns the name of the adapter vendor, or an empty string if it is not available.

Value
-----

A string.

Examples
--------

```js
async function init() {
  if (!navigator.gpu) {
    throw Error("WebGPU not supported.");
  }

  const adapter = await navigator.gpu.requestAdapter();
  if (!adapter) {
    throw Error("Couldn't request WebGPU adapter.");
  }

  const adapterInfo = await adapter.requestAdapterInfo();
  console.log(adapterInfo.vendor);

  // ...
}
```

Specifications
--------------

| Specification |
| --- |
| WebGPU # dom-gpuadapterinfo-vendor |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* The WebGPU API