AudioListener - Web APIs

AudioListener
=============

The `AudioListener` interface represents the position and orientation of the unique person listening to the audio scene, and is used in audio spatialization. All `PannerNode`s spatialize in relation to the `AudioListener` stored in the `BaseAudioContext.listener` attribute.

It is important to note that there is only one listener per context and that it isn't an `AudioNode`.

![We see the position, up and front vectors of an AudioListener, with the up and front vectors at 90° from the other.](/en-US/docs/Web/API/AudioListener/webaudiolistenerreduced.png)

Instance properties
-------------------

**Note:** The position, forward, and up value are set and retrieved using different syntaxes. Retrieval is done by accessing, for example, `AudioListener.positionX`, while setting the same property is done with `AudioListener.positionX.value`. This is why these values are not marked read only, which is how they appear in the specification's IDL.

`AudioListener.positionX`

Represents the horizontal position of the listener in a right-hand cartesian coordinate system. The default is 0.

`AudioListener.positionY`

Represents the vertical position of the listener in a right-hand cartesian coordinate system. The default is 0.

`AudioListener.positionZ`

Represents the longitudinal (back and forth) position of the listener in a right-hand cartesian coordinate system. The default is 0.

`AudioListener.forwardX`

Represents the horizontal position of the listener's forward direction in the same cartesian coordinate system as the position (`positionX`, `positionY`, and `positionZ`) values. The forward and up values are linearly independent of each other. The default is 0.

`AudioListener.forwardY`

Represents the vertical position of the listener's forward direction in the same cartesian coordinate system as the position (`positionX`, `positionY`, and `positionZ`) values. The forward and up values are linearly independent of each other. The default is 0.

`AudioListener.forwardZ`

Represents the longitudinal (back and forth) position of the listener's forward direction in the same cartesian coordinate system as the position (`positionX`, `positionY`, and `positionZ`) values. The forward and up values are linearly independent of each other. The default is -1.

`AudioListener.upX`

Represents the horizontal position of the top of the listener's head in the same cartesian coordinate system as the position (`positionX`, `positionY`, and `positionZ`) values. The forward and up values are linearly independent of each other. The default is 0.

`AudioListener.upY`

Represents the vertical position of the top of the listener's head in the same cartesian coordinate system as the position (`positionX`, `positionY`, and `positionZ`) values. The forward and up values are linearly independent of each other. The default is 1.

`AudioListener.upZ`

Represents the longitudinal (back and forth) position of the top of the listener's head in the same cartesian coordinate system as the position (`positionX`, `positionY`, and `positionZ`) values. The forward and up values are linearly independent of each other. The default is 0.

Instance methods
----------------

`AudioListener.setOrientation()`
Deprecated

Sets the orientation of the listener.

`AudioListener.setPosition()`
Deprecated

Sets the position of the listener.

**Note:** Although these methods are deprecated they are currently the only way to set the orientation and position in Firefox.

Deprecated features
-------------------

The `setOrientation()` and `setPosition()` methods have been replaced by setting their property value equivalents. For example `setPosition(x, y, z)` can be achieved by setting `positionX.value`, `positionY.value`, and `positionZ.value` respectively.

Example
-------

See `BaseAudioContext.createPanner()` for example code.

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

| Specification |
| --- |
| Web Audio API # AudioListener |

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

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

See also
--------

* Using the Web Audio API


BluetoothCharacteristicProperties - Web APIs

BluetoothCharacteristicProperties
=================================

**Secure context:** This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.

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

The **`BluetoothCharacteristicProperties`** interface of the Web Bluetooth API provides the operations that are valid on the given `BluetoothRemoteGATTCharacteristic`.

This interface is returned by calling `BluetoothRemoteGATTCharacteristic.properties`.

Instance properties
-------------------

`authenticatedSignedWrites` Read only
Experimental

Returns a `boolean` that is `true` if signed writing to the characteristic value is permitted.

`broadcast` Read only
Experimental

Returns a `boolean` that is `true` if the broadcast of the characteristic value is permitted using the Server Characteristic Configuration Descriptor.

`indicate` Read only
Experimental

Returns a `boolean` that is `true` if indications of the characteristic value with acknowledgement is permitted.

`notify` Read only
Experimental

Returns a `boolean` that is `true` if notifications of the characteristic value without acknowledgement is permitted.

`read` Read only
Experimental

Returns a `boolean` that is `true` if the reading of the characteristic value is permitted.

`reliableWrite` Read only
Experimental

Returns a `boolean` that is `true` if reliable writes to the characteristic is permitted.

`writableAuxiliaries` Read only
Experimental

Returns a `boolean` that is `true` if reliable writes to the characteristic descriptor is permitted.

`write` Read only
Experimental

Returns a `boolean` that is `true` if the writing to the characteristic with response is permitted.

`writeWithoutResponse` Read only
Experimental

Returns a `boolean` that is `true` if the writing to the characteristic without response is permitted.

Examples
--------

The following example shows how tell if a GATT characteristic supports value change notifications.

```js
let device = await navigator.bluetooth.requestDevice({
  filters: [{ services: ["heart\_rate"] }],
});
let gatt = await device.gatt.connect();
let service = await gatt.getPrimaryService("heart\_rate");
let characteristic = await service.getCharacteristic("heart\_rate\_measurement");
if (characteristic.properties.notify) {
  characteristic.addEventListener(
    "characteristicvaluechanged",
    async (event) => {
      console.log(`Received heart rate measurement: ${event.target.value}`);
    },
  );
  await characteristic.startNotifications();
}
```

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

| Specification |
| --- |
| Web Bluetooth # characteristicproperties-interface |

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

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


MathMLElement - Web APIs

MathMLElement
=============

The **`MathMLElement`** interface represents any MathML element.

EventTarget

Node

Element

MathMLElementInstance properties
-------------------

*Also inherits properties from its parent, `Element`*.

`MathMLElement.attributeStyleMap` Read only

A `StylePropertyMap` representing the declarations of the element's `style` attribute.

`MathMLElement.style`

A `CSSStyleDeclaration` representing the declarations of the element's `style` attribute.

Instance methods
----------------

*This interface has no methods, but inherits methods from its parent, `Element`*.

Examples
--------

### MathML

```html
<math xmlns="http://www.w3.org/1998/Math/MathML">
  <msqrt>
    <mi>x</mi>
  </msqrt>
</math>
```

### JavaScript

```js
document.querySelector("msqrt").constructor.name; // MathMLElement
```

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

| Specification |
| --- |
| MathML Core # dom-mathmlelement |

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

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

See also
--------

* `Element`
* `HTMLElement`
* `SVGElement`


XRProjectionLayer - Web APIs

XRProjectionLayer
=================

**Secure context:** This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.

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

The **`XRProjectionLayer`** interface of the WebXR Device API is a layer that fills the entire view of the observer and is refreshed close to the device's native frame rate.

`XRProjectionLayer` is supported by all `XRSession` objects (no `layers` feature descriptor is needed).

 To create a new `XRProjectionLayer`, call `XRWebGLBinding.createProjectionLayer()`.
 To present layers to the XR device, add them to the `layers` render state using `XRSession.updateRenderState()`.

`XRProjectionLayer` objects don't have an associated `XRSpace`, because they render to the full frame.

EventTarget

XRLayer

XRCompositionLayer

XRProjectionLayerInstance properties
-------------------

*Inherits properties from its parent, `XRCompositionLayer` and `EventTarget`.*

`XRProjectionLayer.fixedFoveation`
Experimental

A number indicating the amount of foveation used by the XR compositor for the layer. Fixed Foveated Rendering (FFR) renders the edges of the eye textures at a lower resolution than the center and reduces the GPU load.

`XRProjectionLayer.ignoreDepthValues` Read only
Experimental

A boolean indicating that the XR compositor is not making use of depth buffer values when rendering the layer.

`XRProjectionLayer.textureArrayLength` Read only
Experimental

The layer's layer count for array textures when using `texture-array` as the `textureType`.

`XRProjectionLayer.textureHeight` Read only
Experimental

The height in pixels of the color textures of this layer.

`XRProjectionLayer.textureWidth` Read only
Experimental

The width in pixels of the color textures of this layer.

Instance methods
----------------

*Inherits methods from its parents, `XRCompositionLayer` and `EventTarget`*.

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

| Specification |
| --- |
| WebXR Layers API Level 1 # xrprojectionlayertype |

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

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

See also
--------

* `XRLayer`
* `EventTarget`
* `XRCompositionLayer`
* `XREquirectLayer`
* `XRCubeLayer`
* `XRCylinderLayer`
* `XRQuadLayer`


VRDisplayCapabilities - Web APIs

VRDisplayCapabilities
=====================

**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 **`VRDisplayCapabilities`** interface of the WebVR API describes the capabilities of a `VRDisplay` — its features can be used to perform VR device capability tests, for example can it return position information.

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

This interface is accessible through the `VRDisplay.capabilities` property.

Instance properties
-------------------

`VRDisplayCapabilities.canPresent`
Deprecated
 Read only
Non-standard

Returns a boolean value stating whether the VR display is capable of presenting content (e.g. through an HMD).

`VRDisplayCapabilities.hasExternalDisplay`
Deprecated
 Read only
Non-standard

Returns a boolean value stating whether the VR display is separate from the device's primary display.

`VRDisplayCapabilities.hasOrientation`
Deprecated
 Read only
Non-standard

Returns a boolean value stating whether the VR display can track and return orientation information.

`VRDisplayCapabilities.hasPosition`
Deprecated
 Read only
Non-standard

Returns a boolean value stating whether the VR display can track and return position information.

`VRDisplayCapabilities.maxLayers`
Deprecated
 Read only
Non-standard

Returns a number indicating the maximum number of `VRLayerInit`s that the VR display can present at once (e.g. the maximum length of the array that `VRDisplay.requestPresent()` can accept.)

Examples
--------

```js
function reportDisplays() {
  navigator.getVRDisplays().then((displays) => {
    displays.forEach((display, i) => {
      const cap = display.capabilities;
      // cap is a VRDisplayCapabilities object
      const listItem = document.createElement("li");
      listItem.innerHTML =
        `<strong>Display ${i + 1}</strong><br>` +
        `VR Display ID: ${display.displayId}<br>` +
        `VR Display Name: ${display.displayName}<br>` +
        `Display can present content: ${cap.canPresent}<br>` +
        `Display is separate from the computer's main display: ${cap.hasExternalDisplay}<br>` +
        `Display can return position info: ${cap.hasPosition}<br>` +
        `Display can return orientation info: ${cap.hasOrientation}<br>` +
        `Display max layers: ${cap.maxLayers}`;
      list.appendChild(listItem);
    });
  });
}
```

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

This interface 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


DocumentFragment - Web APIs

DocumentFragment
================

The **`DocumentFragment`** interface represents a minimal document object that has no parent.

It is used as a lightweight version of `Document` that stores a segment of a document structure comprised of nodes just like a standard document. The key difference is due to the fact that the document fragment isn't part of the active document tree structure. Changes made to the fragment don't affect the document.

EventTarget

Node

DocumentFragmentConstructor
-----------

`DocumentFragment()`

Creates and returns a new `DocumentFragment` object.

Instance properties
-------------------

*This interface has no specific properties, but inherits those of its parent, `Node`.*

`DocumentFragment.childElementCount` Read only

Returns the amount of child `elements` the `DocumentFragment` has.

`DocumentFragment.children` Read only

Returns a live `HTMLCollection` containing all objects of type `Element` that are children of the `DocumentFragment` object.

`DocumentFragment.firstElementChild` Read only

Returns the `Element` that is the first child of the `DocumentFragment` object, or `null` if there is none.

`DocumentFragment.lastElementChild` Read only

Returns the `Element` that is the last child of the `DocumentFragment` object, or `null` if there is none.

Instance methods
----------------

*This interface inherits the methods of its parent, `Node`.*

`DocumentFragment.append()`

Inserts a set of `Node` objects or string objects after the last child of the document fragment.

`DocumentFragment.prepend()`

Inserts a set of `Node` objects or string objects before the first child of the document fragment.

`DocumentFragment.querySelector()`

Returns the first `Element` node within the `DocumentFragment`, in document order, that matches the specified selectors.

`DocumentFragment.querySelectorAll()`

Returns a `NodeList` of all the `Element` nodes within the `DocumentFragment` that match the specified selectors.

`DocumentFragment.replaceChildren()`

Replaces the existing children of a `DocumentFragment` with a specified new set of children.

`DocumentFragment.getElementById()`

Returns the first `Element` node within the `DocumentFragment`, in document order, that matches the specified ID. Functionally equivalent to `Document.getElementById()`.

Usage notes
-----------

A common use for `DocumentFragment` is to create one, assemble a DOM subtree within it, then append or insert the fragment into the DOM using `Node` interface methods such as `appendChild()`, `append()`, or `insertBefore()`. Doing this moves the fragment's nodes into the DOM, leaving behind an empty `DocumentFragment`.

This interface is also of great use with Web components: `<template>` elements contain a `DocumentFragment` in their `HTMLTemplateElement.content` property.

An empty `DocumentFragment` can be created using the `document.createDocumentFragment()` method or the constructor.

Performance
-----------

The performance benefit of `DocumentFragment` is often overstated. In fact, in some engines, using a `DocumentFragment` is slower than appending to the document in a loop as demonstrated in this benchmark. However, the difference between these examples is so marginal that it's better to optimize for readability than performance.

Example
-------

### HTML

```html
<ul></ul>
```

### JavaScript

```js
const ul = document.querySelector("ul");
const fruits = ["Apple", "Orange", "Banana", "Melon"];

const fragment = new DocumentFragment();

for (const fruit of fruits) {
  const li = document.createElement("li");
  li.textContent = fruit;
  fragment.append(li);
}

ul.append(fragment);
```

### Result

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

| Specification |
| --- |
| DOM Standard # interface-documentfragment |

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

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


FileSystemDirectoryEntry - Web APIs

FileSystemDirectoryEntry
========================

The **`FileSystemDirectoryEntry`** interface of the File and Directory Entries API represents a directory in a file system. It provides methods which make it possible to access and manipulate the files in a directory, as well as to access the entries within the directory.

FileSystemEntry

FileSystemDirectoryEntryBasic concepts
--------------

You can create a new directory by calling `getDirectory()`. If you want to create subdirectories, create each child directory in sequence. If you try creating a directory using a full path that includes parent directories that do not exist yet, an error is returned. So create the hierarchy by recursively adding a new path after creating the parent directory.

### Example

In the following code snippet, we create a directory called "Documents."

```js
// Taking care of the browser-specific prefixes.
window.requestFileSystem =
  window.requestFileSystem || window.webkitRequestFileSystem;
window.directoryEntry = window.directoryEntry || window.webkitDirectoryEntry;

// …

function onFs(fs) {
  fs.root.getDirectory(
    "Documents",
    { create: true },
    (directoryEntry) => {
      //directoryEntry.isFile === false
      //directoryEntry.isDirectory === true
      //directoryEntry.name === 'Documents'
      //directoryEntry.fullPath === '/Documents'
    },
    onError,
  );
}

// Opening a file system with temporary storage
window.requestFileSystem(TEMPORARY, 1024 \* 1024 /\*1MB\*/, onFs, onError);
```

Instance properties
-------------------

*This interface has no properties of its own, but inherits properties from its parent interface, `FileSystemEntry`.*

Instance methods
----------------

*This interface inherits methods from its parent interface, `FileSystemEntry`.*

`createReader()`

Creates a `FileSystemDirectoryReader` object which can be used to read the entries in this directory.

`getDirectory()`

Returns a `FileSystemDirectoryEntry` object representing a directory located at a given path, relative to the directory on which the method is called.

`getFile()`

Returns a `FileSystemFileEntry` object representing a file located within the directory's hierarchy, given a path relative to the directory on which the method is called.

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

| Specification |
| --- |
| File and Directory Entries API # api-directoryentry |

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

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

See also
--------

* File and Directory Entries API
* Introduction to the File and Directory Entries API
* `FileSystemDirectoryReader`
* `FileSystemEntry`
* `FileSystemFileEntry`


IDBVersionChangeEvent - Web APIs

IDBVersionChangeEvent
=====================

The **`IDBVersionChangeEvent`** interface of the IndexedDB API indicates that the version of the database has changed, as the result of an `onupgradeneeded` event handler function.

**Note:** This feature is available in Web Workers

Event

IDBVersionChangeEventConstructor
-----------

`IDBVersionChangeEvent()`

Creates and returns a new `IDBVersionChangeEvent` object which is used to represent when a version of the database has changed.

Instance properties
-------------------

*Also inherits properties from its parent, `Event` interface.*

`IDBVersionChangeEvent.oldVersion` Read only

Returns the old version of the database.

`IDBVersionChangeEvent.newVersion` Read only

Returns the new version of the database.

Instance methods
----------------

*No specific method, but inherits methods from its parent, `Event` interface.*

Example
-------

In the following code snippet, we make a request to open a database, and include handlers for the success and error cases. Upon a version change (after an `upgradeneeded` event), the `success` event will implement the `IDBVersionChangeEvent` interface. For a full working example, see our To-do Notifications app (view example live).

```js
const note = document.querySelector("ul");

// Let us open version 4 of our database
const DBOpenRequest = window.indexedDB.open("toDoList", 4);

// these two event handlers act on the database being opened successfully, or not
DBOpenRequest.onerror = (event) => {
  note.innerHTML += "<li>Error loading database.</li>";
};

DBOpenRequest.onsuccess = (event) => {
  note.innerHTML += "<li>Database initialized.</li>";

  // store the result of opening the database in the db variable. This is used a lot later on, for opening transactions and suchlike.
  const db = DBOpenRequest.result;
};
```

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

| Specification |
| --- |
| Indexed Database API 3.0 # events |

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

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

See also
--------

* Using IndexedDB
* Starting transactions: `IDBDatabase`
* Using transactions: `IDBTransaction`
* Setting a range of keys: `IDBKeyRange`
* Retrieving and making changes to your data: `IDBObjectStore`
* Using cursors: `IDBCursor`
* Reference example: To-do Notifications (View the example live).


SpeechRecognitionResultList - Web APIs

SpeechRecognitionResultList
===========================

The **`SpeechRecognitionResultList`** interface of the Web Speech API represents a list of `SpeechRecognitionResult` objects, or a single one if results are being captured in `non-continuous` mode.

Instance properties
-------------------

`SpeechRecognitionResultList.length` Read only

Returns the length of the "array" — the number of `SpeechRecognitionResult` objects in the list.

Instance methods
----------------

`SpeechRecognitionResultList.item`

A standard getter that allows `SpeechRecognitionResult` objects in the list to be accessed via array syntax.

Examples
--------

This code is excerpted from our Speech color changer example.

```js
recognition.onresult = (event) => {
  // The SpeechRecognitionEvent results property returns a SpeechRecognitionResultList object
  // The SpeechRecognitionResultList object contains SpeechRecognitionResult objects.
  // It has a getter so it can be accessed like an array
  // The first [0] returns the SpeechRecognitionResult at position 0.
  // Each SpeechRecognitionResult object contains SpeechRecognitionAlternative objects
  // that contain individual results.
  // These also have getters so they can be accessed like arrays.
  // The second [0] returns the SpeechRecognitionAlternative at position 0.
  // We then return the transcript property of the SpeechRecognitionAlternative object
  const color = event.results[0][0].transcript;
  diagnostic.textContent = `Result received: ${color}.`;
  bg.style.backgroundColor = color;
};
```

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

| Specification |
| --- |
| Web Speech API # speechreco-resultlist |

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

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

See also
--------

* Web Speech API


EventTarget - Web APIs

EventTarget
===========

 The **`EventTarget`** interface is implemented by objects that can receive events and may have listeners for them.
 In other words, any target of events implements the three methods associated with this interface.

`Element`, and its children, as well as `Document` and `Window`, are the most common event targets,
 but other objects can be event targets, too.
 For example `IDBRequest`, `AudioNode`, and `AudioContext` are also event targets.

Many event targets (including elements, documents, and windows) also support setting event handlers via `onevent` properties and attributes.

Constructor
-----------

`EventTarget()`

Creates a new `EventTarget` object instance.

Instance methods
----------------

`EventTarget.addEventListener()`

Registers an event handler of a specific event type on the `EventTarget`.

`EventTarget.removeEventListener()`

Removes an event listener from the `EventTarget`.

`EventTarget.dispatchEvent()`

Dispatches an event to this `EventTarget`.

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

| Specification |
| --- |
| DOM Standard # interface-eventtarget |

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

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

See also
--------

* Event reference – the events available in the platform.
* Introduction to events
* `Event` interface


PerformancePaintTiming - Web APIs

PerformancePaintTiming
======================

The **`PerformancePaintTiming`** interface provides timing information about "paint" (also called "render") operations during web page construction. "Paint" refers to conversion of the render tree to on-screen pixels.

There are two key paint moments this API provides:

* First paint (FP): Time when anything is rendered. Note that the marking of the first paint is optional, not all user agents report it.
* First contentful paint (FCP): Time when the first bit of DOM text or image content is rendered.

A third key paint moment is provided by the `LargestContentfulPaint` API:

* Largest contentful paint (LCP): Render time of the largest image or text block visible within the viewport, recorded from when the page first begins to load.

The data this API provides helps you minimize the time that users have to wait before they can see the site's content start to appear. Decreasing the time until these key paint moments make sites feel more responsive, performant, and engaging for your users.

Like other Performance APIs, this API extends `PerformanceEntry`.

PerformanceEntry

PerformancePaintTimingInstance properties
-------------------

This interface has no properties but it extends the following `PerformanceEntry` properties by qualifying and constraining the properties as follows:

`PerformanceEntry.entryType`

Returns "`paint`".

`PerformanceEntry.name`

Returns either `"first-paint"` or `"first-contentful-paint"`.

`PerformanceEntry.startTime`

Returns the `timestamp` when the paint occurred.

`PerformanceEntry.duration`

Returns 0.

Instance methods
----------------

This interface has no methods.

Examples
--------

### Getting paint timings

Example using a `PerformanceObserver`, which notifies of new `paint` performance entries as they are recorded in the browser's performance timeline. Use the `buffered` option to access entries from before the observer creation.

```js
const observer = new PerformanceObserver((list) => {
  list.getEntries().forEach((entry) => {
    console.log(
      `The time to ${entry.name} was ${entry.startTime} milliseconds.`,
    );
    // Logs "The time to first-paint was 386.7999999523163 milliseconds."
    // Logs "The time to first-contentful-paint was 400.6999999284744 milliseconds."
  });
});

observer.observe({ type: "paint", buffered: true });
```

Example using `Performance.getEntriesByType()`, which only shows `paint` performance entries present in the browser's performance timeline at the time you call this method:

```js
const entries = performance.getEntriesByType("paint");
entries.forEach((entry) => {
  console.log(`The time to ${entry.name} was ${entry.startTime} milliseconds.`);
  // Logs "The time to first-paint was 386.7999999523163 milliseconds."
  // Logs "The time to first-contentful-paint was 400.6999999284744 milliseconds."
});
```

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

| Specification |
| --- |
| Paint Timing # sec-PerformancePaintTiming |

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

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

### See also

* `LargestContentfulPaint`


SVGPoint - Web APIs

SVGPoint
========

**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.

**Warning:** `SVGPoint` is deprecated.
 Use `DOMPoint` or `DOMPointReadOnly` instead.

An `SVGPoint` represents a 2D or 3D point in the SVG coordinate system.

Syntax
------

```js
createSVGPoint()
```

### Value

The returned value is an `SVGPoint` object.

Example
-------

```js
// Create an SVGPoint in the user coordinate system
let s = document.getElementById("SVG-ElementID").createSVGPoint();

// Then, set the x and y values of the returned SVGPoint object
// (which is the variable `s`)
s.y = 10;
s.x = 10;
```

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

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


EXT_texture_norm16 extension - Web APIs

EXT\_texture\_norm16 extension
==============================

The **`EXT_texture_norm16`** extension is part of the WebGL API and provides a set of new 16-bit signed normalized and unsigned normalized formats (fixed-point texture, renderbuffer and texture buffer).

When this extension is enabled:

* The `WebGLRenderingContext.texImage2D()` and `WebGLRenderingContext.texSubImage2D()` methods accept new formats provided by this extension.
* The 16-bit normalized fixed-point types `ext.R16_EXT`, `ext.RG16_EXT` and `ext.RGBA16_EXT` become available as color-renderable formats and renderbuffers and be created in these formats.

WebGL extensions are available using the `WebGLRenderingContext.getExtension()` method. For more information, see also Using Extensions in the WebGL tutorial.

**Note:** This extension is only available to WebGL 2 contexts.

Constants
---------

`ext.R16_EXT`

Red 16-bit unsigned format. Color-renderable.

`ext.RG16_EXT`

RG 16-bit unsigned format. Color-renderable.

`ext.RGB16_EXT`

RGB 16-bit unsigned format.

`ext.RGBA16_EXT`

RGBA 16-bit unsigned format. Color-renderable.

`ext.R16_SNORM_EXT`

Red 16-bit signed normalized format.

`ext.RG16_SNORM__EXT`

RG 16-bit signed normalized format.

`ext.RGB16_SNORM__EXT`

RGB 16-bit signed normalized format.

`ext.RGBA16_SNORM__EXT`

RGBA 16-bit signed normalized format.

Examples
--------

### Enabling the extension

```js
let ext = gl.getExtension("EXT\_texture\_norm16");
```

### Texture formats

The `WebGLRenderingContext.texImage2D()` method accepts new formats when `EXT_texture_norm16` is enabled. Example calls:

```js
// imageData = Uint16Array
gl.texImage2D(gl.TEXTURE\_2D, 0, ext.R16\_EXT, 1, 1, 0, gl.RED, gl.UNSIGNED\_SHORT, imageData);
gl.texImage2D(gl.TEXTURE\_2D, 0, ext.RG16\_EXT, 1, 1, 0, gl.RG, gl.UNSIGNED\_SHORT, imageData);
gl.texImage2D(gl.TEXTURE\_2D, 0, ext.RGB16\_EXT, 1, 1, 0, gl.RGB, gl.UNSIGNED\_SHORT, imageData);
gl.texImage2D(gl.TEXTURE\_2D, 0, ext.RGBA16\_EXT, 1, 1, 0, gl.RGBA, gl.UNSIGNED\_SHORT, imageData);

// imageData = Int16Array
gl.texImage2D(gl.TEXTURE\_2D, 0, ext.R16\_SNORM\_EXT, 1, 1, 0, gl.RED, gl.SHORT, imageData);
gl.texImage2D(gl.TEXTURE\_2D, 0, ext.RG16\_SNORM\_EXT, 1, 1, 0, gl.RG, gl.SHORT, imageData);
gl.texImage2D(gl.TEXTURE\_2D, 0, ext.RGB16\_SNORM\_EXT, 1, 1, 0, gl.RGB, gl.SHORT, imageData);
gl.texImage2D(gl.TEXTURE\_2D, 0, ext.RGBA16\_SNORM\_EXT, 1, 1, 0, gl.RGBA, gl.SHORT, imageData);
```

### Renderbuffer formats

 The `WebGLRenderingContext.renderbufferStorage()` method accepts `ext.R16_EXT`,
 `ext.RG16_EXT` and `ext.RGBA16_EXT` as internal formats to create renderbuffers in these formats. Example calls:

```js
gl.renderbufferStorage(gl.RENDERBUFFER, ext.R16\_EXT, 1, 1);
gl.renderbufferStorage(gl.RENDERBUFFER, ext.RG16\_EXT, 1, 1);
gl.renderbufferStorage(gl.RENDERBUFFER, ext.RGBA16\_EXT, 1, 1);
```

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

| Specification |
| --- |
| WebGL EXT\_texture\_norm16 Extension Specification  |

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

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

See also
--------

* `WebGLRenderingContext.getExtension()`
* `WebGLRenderingContext.texImage2D()`
* `WebGLRenderingContext.renderbufferStorage()`


Web MIDI API - Web APIs

Web MIDI API
============

**Secure context:** This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.

The Web MIDI API connects to and interacts with Musical Instrument Digital Interface (MIDI) Devices.

 The interfaces deal with the practical aspects of sending and receiving MIDI messages.
 Therefore, the API can be used for musical and non-musical uses, with any MIDI device connected to your computer.

Interfaces
----------

`MIDIInputMap`

Represents all of the available MIDI input ports.

`MIDIOutputMap`

Represents all of the available MIDI output ports.

`MIDIAccess`

Provides the methods to list input and output devices, and to access an individual device.

`MIDIPort`

Represents an individual MIDI port.

`MIDIInput`

Provides a method for dealing with MIDI messages from an input port.

`MIDIOutput`

Queues messages to the linked MIDI port. Messages can be sent immediately or after a specified delay.

`MIDIMessageEvent`

The event passed to `MIDIInput.midimessage_event`.

`MIDIConnectionEvent`

The event passed to the `MIDIAccess.statechange_event` and `MIDIPort.statechange_event` events, when a port becomes available or unavailable.

Security requirements
---------------------

Access to the API is requested using the `navigator.requestMIDIAccess()` method.

* The method must be called in a secure context.
* Access may be gated by the `midi` HTTP Permission Policy.
* The user must explicitly grant permission to use the API through a user-agent specific mechanism, or have previously granted permission.
 Note that if access is denied by a permission policy it cannot be granted by a user permission.

The permission status can be queried using the Permissions API method `navigator.permissions.query()`, passing a permission descriptor with the `midi` permission and (optional) `sysex` property:

```js
navigator.permissions.query({ name: "midi", sysex: true }).then((result) => {
  if (result.state === "granted") {
    // Access granted.
  } else if (result.state === "prompt") {
    // Using API will prompt for permission
  }
  // Permission was denied by user prompt or permission policy
});
```

Examples
--------

### Gaining access to the MIDI port

 The `navigator.requestMIDIAccess()` method returns a promise that resolves to a `MIDIAccess` object, which can then be used to access a MIDI device.
 The method must be called in a secure context.

```js
let midi = null; // global MIDIAccess object
function onMIDISuccess(midiAccess) {
  console.log("MIDI ready!");
  midi = midiAccess; // store in the global (in real usage, would probably keep in an object instance)
}

function onMIDIFailure(msg) {
  console.error(`Failed to get MIDI access - ${msg}`);
}

navigator.requestMIDIAccess().then(onMIDISuccess, onMIDIFailure);
```

### Listing inputs and outputs

In this example the list of input and output ports are retrieved and printed to the console.

```js
function listInputsAndOutputs(midiAccess) {
  for (const entry of midiAccess.inputs) {
    const input = entry[1];
    console.log(
      `Input port [type:'${input.type}']` +
        ` id:'${input.id}'` +
        ` manufacturer:'${input.manufacturer}'` +
        ` name:'${input.name}'` +
        ` version:'${input.version}'`,
    );
  }

  for (const entry of midiAccess.outputs) {
    const output = entry[1];
    console.log(
      `Output port [type:'${output.type}'] id:'${output.id}' manufacturer:'${output.manufacturer}' name:'${output.name}' version:'${output.version}'`,
    );
  }
}
```

### Handling MIDI Input

This example prints all MIDI input messages to the console.

```js
function onMIDIMessage(event) {
  let str = `MIDI message received at timestamp ${event.timeStamp}[${event.data.length} bytes]: `;
  for (const character of event.data) {
    str += `0x${character.toString(16)} `;
  }
  console.log(str);
}

function startLoggingMIDIInput(midiAccess) {
  midiAccess.inputs.forEach((entry) => {
    entry.onmidimessage = onMIDIMessage;
  });
}
```

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

| Specification |
| --- |
| Web MIDI API  |

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

### api.Navigator.requestMIDIAccess

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

### http.headers.Permissions-Policy.midi

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

### api.Permissions.permission\_midi

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

See also
--------

* Introduction to Web MIDI
* Making Music in the Browser


atob() global function - Web APIs

atob() global function
======================

**Note:** This feature is available in Web Workers

 The **`atob()`** function decodes a
 string of data which has been encoded using Base64 encoding. You can use
 the `btoa()` method to encode and transmit
 data which may otherwise cause communication problems, then transmit it and use the
 `atob()` method to decode the data again. For example, you can encode,
 transmit, and decode control characters such as ASCII values 0 through 31.

For use with arbitrary Unicode strings, see The "Unicode Problem" section of the Base64 glossary entry.

Syntax
------

```js
atob(encodedData)
```

### Parameters

`encodedData`

A binary string (i.e., a string in which each character in the string is treated as a byte of binary data) containing base64-encoded data.

### Return value

An ASCII string containing decoded data from `encodedData`.

### Exceptions

`InvalidCharacterError` `DOMException`

Thrown if `encodedData` is not valid base64.

Examples
--------

```js
const encodedData = btoa("Hello, world"); // encode a string
const decodedData = atob(encodedData); // decode the string
```

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

| Specification |
| --- |
| HTML Standard # dom-atob-dev |

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

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

See also
--------

* A polyfill of `atob` is available in `core-js`
* `data` URLs
* `btoa()`


EventSource - Web APIs

EventSource
===========

The **`EventSource`** interface is web content's interface to server-sent events.

An `EventSource` instance opens a persistent connection to an HTTP server, which sends events in `text/event-stream` format. The connection remains open until closed by calling `EventSource.close()`.

EventTarget

EventSource
Once the connection is opened, incoming messages from the server are delivered to your code in the form of events. If there is an event field in the incoming message, the triggered event is the same as the event field value. If no event field is present, then a generic `message` event is fired.

Unlike WebSockets, server-sent events are unidirectional; that is, data messages are delivered in one direction, from the server to the client (such as a user's web browser). That makes them an excellent choice when there's no need to send data from the client to the server in message form. For example, `EventSource` is a useful approach for handling things like social media status updates, news feeds, or delivering data into a client-side storage mechanism like IndexedDB or web storage.

**Warning:** When **not used over HTTP/2**, SSE suffers from a limitation to the maximum number of open connections, which can be specially painful when opening various tabs as the limit is *per browser* and set to a very low number (6). The issue has been marked as "Won't fix" in Chrome and Firefox. This limit is per browser + domain, so that means that you can open 6 SSE connections across all of the tabs to `www.example1.com` and another 6 SSE connections to `www.example2.com`. (from Stackoverflow). When using HTTP/2, the maximum number of simultaneous *HTTP streams* is negotiated between the server and the client (defaults to 100).

Constructor
-----------

`EventSource()`

Creates a new `EventSource` to handle receiving server-sent events from a specified URL, optionally in credentials mode.

Instance properties
-------------------

*This interface also inherits properties from its parent, `EventTarget`.*

`EventSource.readyState` Read only

A number representing the state of the connection. Possible values are `CONNECTING` (`0`), `OPEN` (`1`), or `CLOSED` (`2`).

`EventSource.url` Read only

A string representing the URL of the source.

`EventSource.withCredentials` Read only

A boolean value indicating whether the `EventSource` object was instantiated with cross-origin (CORS) credentials set (`true`), or not (`false`, the default).

Instance methods
----------------

*This interface also inherits methods from its parent, `EventTarget`.*

`EventSource.close()`

Closes the connection, if any, and sets the `readyState` attribute to `CLOSED`. If the connection is already closed, the method does nothing.

Events
------

`error`

Fired when a connection to an event source failed to open.

`message`

Fired when data is received from an event source.

`open`

Fired when a connection to an event source has opened.

Additionally, the event source itself may send messages with an event field, which will create ad hoc events keyed to that value.

Examples
--------

In this basic example, an `EventSource` is created to receive unnamed events from the server; a page with the name `sse.php` is responsible for generating the events.

```js
const evtSource = new EventSource("sse.php");
const eventList = document.querySelector("ul");

evtSource.onmessage = (e) => {
  const newElement = document.createElement("li");

  newElement.textContent = `message: ${e.data}`;
  eventList.appendChild(newElement);
};
```

Each received event causes our `EventSource` object's `onmessage` event handler to be run. It, in turn, creates a new `<li>` element and writes the message's data into it, then appends the new element to the list element already in the document.

**Note:** You can find a full example on GitHub — see Simple SSE demo using PHP.

To listen to named events, you'll require a listener for each type of event sent.

```js
const sse = new EventSource("/api/v1/sse");

/\*
 \* This will listen only for events
 \* similar to the following:
 \*
 \* event: notice
 \* data: useful data
 \* id: someid
 \*/
sse.addEventListener("notice", (e) => {
  console.log(e.data);
});

/\*
 \* Similarly, this will listen for events
 \* with the field `event: update`
 \*/
sse.addEventListener("update", (e) => {
  console.log(e.data);
});

/\*
 \* The event "message" is a special case, as it
 \* will capture events without an event field
 \* as well as events that have the specific type
 \* `event: message` It will not trigger on any
 \* other event type.
 \*/
sse.addEventListener("message", (e) => {
  console.log(e.data);
});
```

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

| Specification |
| --- |
| HTML Standard # the-eventsource-interface |

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

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

See also
--------

* Server-sent events
* Using server-sent events


XRHitTestResult - Web APIs

XRHitTestResult
===============

**Secure context:** This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.

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

The **`XRHitTestResult`** interface of the WebXR Device API contains a single result of a hit test. You can get an array of `XRHitTestResult` objects for a frame by calling `XRFrame.getHitTestResults()`.

Instance properties
-------------------

None.

Instance methods
----------------

`XRHitTestResult.createAnchor()`
Experimental

Returns a `Promise` that resolves with an `XRAnchor` created from the hit test result.

`XRHitTestResult.getPose()`
Experimental

Returns the `XRPose` of the hit test result relative to the given base space.

Examples
--------

### Getting `XRHitTestResult` objects within the frame loop

In addition to showing `XRHitTestResult` within a frame loop, this example demonstrates a few things you must do before requesting this object. While setting up the session, specify `"hit-test"` as one of the `requiredFeatures`. Next, call `XRSession.requestHitTestSource()` with the desired references. (Obtain this by calling `XRSession.requestReferenceSpace()`.) This returns a `XRHitTestSource`. That you will use in the frame loop to get `XRHitTestResult` objects.

```js
const xrSession = navigator.xr.requestSession("immersive-ar", {
  requiredFeatures: ["local", "hit-test"],
});

let hitTestSource = null;

xrSession
  .requestHitTestSource({
    space: viewerSpace, // obtained from xrSession.requestReferenceSpace("viewer");
    offsetRay: new XRRay({ y: 0.5 }),
  })
  .then((viewerHitTestSource) => {
    hitTestSource = viewerHitTestSource;
  });

// frame loop
function onXRFrame(time, xrFrame) {
  let hitTestResults = xrFrame.getHitTestResults(hitTestSource);

  // do things with the hit test results
}
```

### Getting the hit test result's pose

Use `getPose()` to query the result's pose.

```js
let hitTestResults = xrFrame.getHitTestResults(hitTestSource);

if (hitTestResults.length > 0) {
  let pose = hitTestResults[0].getPose(referenceSpace);
}
```

### Creating an anchor from a hit test result

Once you find intersections on real-world surfaces using hit testing, you can create an `XRAnchor` to attach a virtual object to that location.

```js
hitTestResult.createAnchor().then(
  (anchor) => {
    // add anchored objects to the scene
  },
  (error) => {
    console.error(`Could not create anchor: ${error}`);
  },
);
```

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

| Specification |
| --- |
| WebXR Hit Test Module # xr-hit-test-result-interface |

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

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

See also
--------

* `XRTransientInputHitTestResult`
* `XRPose`
* `XRAnchor`


GPUBindGroupLayout - Web APIs

GPUBindGroupLayout
==================

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

The **`GPUBindGroupLayout`** interface of the WebGPU API defines the structure and purpose of related GPU resources such as buffers that will be used in a pipeline, and is used as a template when creating `GPUBindGroup`s.

A `GPUBindGroupLayout` object instance is created using the `GPUDevice.createBindGroupLayout()` method.

Instance properties
-------------------

`label`
Experimental

A string providing a label that can be used to identify the object, for example in `GPUError` messages or console warnings.

Examples
--------

**Note:** The WebGPU samples feature many more examples.

### Basic example

Our basic compute demo shows an example of creating a bind group layout and then using that as a template when creating a bind group.

```js
// ...

const bindGroupLayout = device.createBindGroupLayout({
  entries: [
    {
      binding: 0,
      visibility: GPUShaderStage.COMPUTE,
      buffer: {
        type: "storage",
      },
    },
  ],
});

const bindGroup = device.createBindGroup({
  layout: bindGroupLayout,
  entries: [
    {
      binding: 0,
      resource: {
        buffer: output,
      },
    },
  ],
});

// ...
```

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

| Specification |
| --- |
| WebGPU # gpubindgrouplayout |

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

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

See also
--------

* The WebGPU API


Pbkdf2Params - Web APIs

Pbkdf2Params
============

The **`Pbkdf2Params`** dictionary of the Web Crypto API represents the object that should be passed as the `algorithm` parameter into `SubtleCrypto.deriveKey()`, when using the PBKDF2 algorithm.

Instance properties
-------------------

`name`

A string. This should be set to `PBKDF2`.

`hash`

A string representing the digest algorithm to use. This may be one of:

* `SHA-1`
* `SHA-256`
* `SHA-384`
* `SHA-512`

**Warning:** `SHA-1` is considered vulnerable in most cryptographic applications, but is still considered safe in PBKDF2. However, it's advisable to transition away from it everywhere, so unless you need to use `SHA-1`, don't. Use a different digest algorithm instead.

`salt`

An `ArrayBuffer`, a `TypedArray`, or a `DataView`. This should be a random or pseudo-random value of at least 16 bytes. Unlike the input key material passed into `deriveKey()`, `salt` does not need to be kept secret.

`iterations`

A `Number` representing the number of times the hash function will be executed in `deriveKey()`. This determines how computationally expensive (that is, slow) the `deriveKey()` operation will be. In this context, slow is good, since it makes it more expensive for an attacker to run a dictionary attack against the keys. The general guidance here is to use as many iterations as possible, subject to keeping an acceptable level of performance for your application.

Examples
--------

See the examples for `SubtleCrypto.deriveKey()`.

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

| Specification |
| --- |
| Web Cryptography API # dfn-Pbkdf2Params |

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

Browsers that support the "PBKDF2" algorithm for the `SubtleCrypto.deriveKey()` method will support this type.

See also
--------

* `SubtleCrypto.deriveKey()`.


TrustedScriptURL - Web APIs

TrustedScriptURL
================

The **`TrustedScriptURL`** interface of the `Trusted Types API` represents a string that a developer can insert into an injection sink that will parse it as a URL of an external script. These objects are created via `TrustedTypePolicy.createScriptURL()` and therefore have no constructor.

The value of a **TrustedScriptURL** object is set when the object is created and cannot be changed by JavaScript as there is no setter exposed.

Instance methods
----------------

`TrustedScriptURL.toJSON()`

Returns a JSON representation of the stored data.

`TrustedScriptURL.toString()`

A string containing the sanitized URL.

Examples
--------

The constant `sanitized` is an object created via a Trusted Types policy.

```js
const sanitized = scriptPolicy.createScriptURL(
  "https://example.com/my-script.js",
);
console.log(sanitized); /\* a TrustedScriptURL object \*/
```

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

| Specification |
| --- |
| Trusted Types # trused-script-url |

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

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

See also
--------

* Prevent DOM-based cross-site scripting vulnerabilities with Trusted Types


WebTransportBidirectionalStream - Web APIs

WebTransportBidirectionalStream
===============================

Limited availability
--------------------

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

* Learn more
* See full compatibility
* Report feedback
**Secure context:** This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.

The **`WebTransportBidirectionalStream`** interface of the WebTransport API represents a bidirectional stream created by a server or a client that can be used for reliable transport. Provides access to a `WebTransportReceiveStream` for reading incoming data, and a `WebTransportSendStream` for writing outgoing data.

**Note:** This feature is available in Web Workers

Instance properties
-------------------

`readable` Read only

Returns a `WebTransportReceiveStream` instance that can be used to read incoming data.

`writable` Read only

Returns a `WebTransportSendStream` instance that can be used to write outgoing data.

Examples
--------

### Bidirectional transmission initiated by the user agent

 To open a bidirectional stream from a user agent, you use the `WebTransport.createBidirectionalStream()` method to get a reference to a `WebTransportBidirectionalStream`. The `readable` and `writable` properties return references to `WebTransportReceiveStream` and `WebTransportSendStream` instances.
 These inherit from `ReadableStream` and `WebTransportReceiveStream` respectively, and can be used to read from and write to the server.

```js
async function setUpBidirectional() {
  const stream = await transport.createBidirectionalStream();
  // stream is a WebTransportBidirectionalStream
  // stream.readable is a WebTransportReceiveStream
  const readable = stream.readable;
  // stream.writable is a WebTransportSendStream
  const writable = stream.writable;

  ...
}
```

Reading from the `WebTransportReceiveStream` can be done in the same way as you would read a `ReadableStream`:

```js
async function readData(readable) {
  const reader = readable.getReader();
  while (true) {
    const { value, done } = await reader.read();
    if (done) {
      break;
    }
    // value is a Uint8Array.
    console.log(value);
  }
}
```

And writing to the `WebTransportSendStream` can be done like this:

```js
async function writeData(writable) {
  const writer = writable.getWriter();
  const data1 = new Uint8Array([65, 66, 67]);
  const data2 = new Uint8Array([68, 69, 70]);
  writer.write(data1);
  writer.write(data2);
}
```

### Bidirectional transmission initiated by the server

If the server opens a bidirectional stream to transmit data to and receive it from the client, this can be accessed via the `WebTransport.incomingBidirectionalStreams` property, which returns a `ReadableStream` of `WebTransportBidirectionalStream` objects. Each one can be used to read and write `Uint8Array` instances as shown above. However, you need an initial function to read the bidirectional stream in the first place:

```js
async function receiveBidirectional() {
  const bds = transport.incomingBidirectionalStreams;
  const reader = bds.getReader();
  while (true) {
    const { done, value } = await reader.read();
    if (done) {
      break;
    }
    // value is an instance of WebTransportBidirectionalStream
    await readData(value.readable);
    await writeData(value.writable);
  }
}
```

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

| Specification |
| --- |
| WebTransport # webtransportbidirectionalstream |

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

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

See also
--------

* Using WebTransport
* WebSockets API
* Streams API
* WebTransport over HTTP/3


SVGMarkerElement - Web APIs

SVGMarkerElement
================

The **`SVGMarkerElement`** interface provides access to the properties of `<marker>` elements, as well as methods to manipulate them. The `<marker>` element defines the graphics used for drawing marks on a shape.

EventTarget

Node

Element

SVGElement

SVGMarkerElement
The following properties and methods all return, or act on the attributes of the `<marker>` element represented by `SVGMarkerElement`.

Instance properties
-------------------

*This interface also inherits properties from its parent, `SVGElement`.*

`SVGMarkerElement.markerUnits` Read only

Returns an `SVGAnimatedEnumeration` object, with one of the following values:

0

`SVG_MARKERUNITS_UNKNOWN` which means that the `markerUnits` attribute has a value other than the two predefined keywords.

1

`SVG_MARKERUNITS_USERSPACEONUSE` which means that the `markerUnits` attribute has the keyword value `userSpaceOnUse`.

2

`SVG_MARKERUNITS_STROKEWIDTH` which means that the `markerUnits` attribute has the keyword value `strokeWidth`.

`SVGMarkerElement.markerWidth` Read only

Returns an `SVGAnimatedLength` object containing the width of the `<marker>` viewport.

`SVGMarkerElement.markerHeight` Read only

Returns an `SVGAnimatedLength` object containing the height of the `<marker>` viewport.

`SVGMarkerElement.orientType` Read only

Returns an `SVGAnimatedEnumeration` object, with one of the following values:

0

`SVG_MARKER_ORIENT_UNKNOWN` which means that the `orient` attribute has a value other than the two predefined keywords.

1

`SVG_MARKERUNITS_ORIENT_AUTO` which means that the `orient` attribute has the keyword value `auto`.

2

`SVG_MARKERUNITS_ORIENT_ANGLE` which means that the `orient` attribute has an `<angle>` or `<number>` value indicating the angle.

`SVGMarkerElement.orientAngle` Read only

Returns an `SVGAnimatedAngle` object containing the angle of the `orient` attribute.

`SVGMarkerElement.refX` Read only

Returns an `SVGAnimatedLength` object containing the value of the `refX` attribute of the `<marker>`.

`SVGMarkerElement.refY` Read only

Returns an `SVGAnimatedLength` object containing the value of the `refY` attribute of the `<marker>`.

`SVGMarkerElement.viewBox` Read only

Returns an `SVGAnimatedRect` object containing an `SVGRect` which contains the values set by the `viewBox` attribute on the `<marker>`.

`SVGMarkerElement.preserveAspectRatio` Read only

Returns an `SVGPreserveAspectRatio` object which contains the values set by the `preserveAspectRatio` attribute on the `<marker>` viewport.

Instance methods
----------------

*This interface also inherits methods from its parent, `SVGElement`.*

`SVGMarkerElement.setOrientToAuto()`

Sets the value of the `orient` attribute to `auto`.

`SVGMarkerElement.setOrientToAngle()`

Sets the value of the `orient` attribute to a specific angle value.

Examples
--------

The following SVG will be referenced in the examples.

```html
<svg id="svg" viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">
  <defs>
    <marker
 id="arrow"
 viewBox="0 0 10 10"
 refX="5"
 refY="5"
 markerWidth="6"
 markerHeight="6"
 orient="90">
      <path d="M 0 0 L 10 5 L 0 10 z" />
    </marker>
  </defs>
</svg>
```

### Finding the Width of the Marker

The `markerWidth` property returns an `SVGAnimatedLength` which contains an `SVGLength` with the value of the `markerWidth` attribute.

```js
let marker = document.getElementById("arrow");
console.log(marker.markerWidth.baseVal.value); // 6
```

### Updating the Orientation Angle

In the following example the value of the `orient` attribute is updated using `setOrientToAngle()` using an `SVGAngle` created using `SVGElement.createSVGAngle()`.

```js
let svg = document.getElementById("svg");
let marker = document.getElementById("arrow");
console.log(marker.orientAngle.baseVal.value); // value in SVG above - 90
let angle = svg.createSVGAngle();
angle.value = "110";
marker.setOrientToAngle(angle);
console.log(marker.orientAngle.baseVal.value); // new value - 110
```

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

| Specification |
| --- |
| Scalable Vector Graphics (SVG) 2 # InterfaceSVGMarkerElement |

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

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


WebGPU API - Web APIs

WebGPU API
==========

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

**Secure context:** This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.

The **WebGPU API** enables web developers to use the underlying system's GPU (Graphics Processing Unit) to carry out high-performance computations and draw complex images that can be rendered in the browser.

WebGPU is the successor to WebGL, providing better compatibility with modern GPUs, support for general-purpose GPU computations, faster operations, and access to more advanced GPU features.

Concepts and usage
------------------

It is fair to say that WebGL revolutionized the web in terms of graphical capabilities after it first appeared around 2011. WebGL is a JavaScript port of the OpenGL ES 2.0 graphics library, allowing web pages to pass rendering computations directly to the device's GPU to be processed at very high speeds, and render the result inside a `<canvas>` element.

WebGL and the GLSL language used to write WebGL shader code are complex, so several WebGL libraries have been created to make WebGL apps easier to write: Popular examples include Three.js, Babylon.js, and PlayCanvas. Developers have used these tools to build immersive web-based 3D games, music videos, training and modeling tools, VR and AR experiences, and more.

However, WebGL has some fundamental issues that needed addressing:

* Since WebGL's release, a new generation of native GPU APIs have appeared — the most popular being Microsoft's Direct3D 12, Apple's Metal, and The Khronos Group's Vulkan — which provide a multitude of new features. There are no more updates planned to OpenGL (and therefore WebGL), so it won't get any of these new features. WebGPU on the other hand will have new features added to it going forwards.
* WebGL is based wholly around the use case of drawing graphics and rendering them to a canvas. It does not handle general-purpose GPU (GPGPU) computations very well. GPGPU computations are becoming more and more important for many different use cases, for example those based on machine learning models.
* 3D graphics apps are becoming increasingly demanding, both in terms of the number of objects to be rendered simultaneously, and usage of new rendering features.

WebGPU addresses these issues, providing an updated general-purpose architecture compatible with modern GPU APIs, which feels more "webby". It supports graphic rendering, but also has first-class support for GPGPU computations. Rendering of individual objects is significantly cheaper on the CPU side, and it supports modern GPU rendering features such as compute-based particles and post-processing filters like color effects, sharpening, and depth-of-field simulation. In addition, it can handle expensive computations such as culling and skinned model transformation directly on the GPU.

General model
-------------

There are several layers of abstraction between a device GPU and a web browser running the WebGPU API. It is useful to understand these as you begin to learn WebGPU:

![A basic stack diagram showing the position of the different elements of a WebGPU architecture on a device](/en-US/docs/Web/API/WebGPU_API/basic-webgpu-stack.png)

* Physical devices have GPUs. Most devices only have one GPU, but some have more than one. Different GPU types are available:
    + Integrated GPUs, which live on the same board as the CPU and share its memory.
    + Discrete GPUs, which live on their own board, separate from the CPU.
    + Software "GPUs", implemented on the CPU.
**Note:** The above diagram assumes a device with only one GPU.
* A native GPU API, which is part of the OS (e.g. Metal on macOS), is a programming interface allowing native applications to use the capabilities of the GPU. API instructions are sent to the GPU (and responses received) via a driver. It is possible for a system to have multiple native OS APIs and drivers available to communicate with the GPU, although the above diagram assumes a device with only one native API/driver.
* A browser's WebGPU implementation handles communicating with the GPU via a native GPU API driver. A WebGPU adapter effectively represents a physical GPU and driver available on the underlying system, in your code.
* A logical device is an abstraction via which a single web app can access GPU capabilities in a compartmentalized way. Logical devices are required to provide multiplexing capabilities. A physical device's GPU is used by many applications and processes concurrently, including potentially many web apps. Each web app needs to be able to access WebGPU in isolation for security and logic reasons.
Accessing a device
------------------

A logical device — represented by a `GPUDevice` object instance — is the basis from which a web app accesses all WebGPU functionality. Accessing a device is done as follows:

1. The `Navigator.gpu` property (or `WorkerNavigator.gpu` if you are using WebGPU functionality from inside a worker) returns the `GPU` object for the current context.
2. You access an adapter via the `GPU.requestAdapter()` method. This method accepts an optional settings object allowing you to request for example a high-performance or low-energy adapter. If this is not included, the device will provide access to the default adapter, which is good enough for most purposes.
3. A device can be requested via `GPUAdapter.requestDevice()`. This method also accepts an options object (referred to as a descriptor), which can be used to specify the exact features and limits you want the logical device to have. If this is not included, the supplied device will have a reasonable general-purpose spec that is good enough for most purposes.

Putting this together with some feature detection checks, the above process could be achieved as follows:

```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 device = await adapter.requestDevice();

  //...
}
```

Pipelines and shaders: WebGPU app structure
-------------------------------------------

A pipeline is a logical structure containing programmable stages that are completed to get your program's work done. WebGPU is currently able to handle two types of pipeline:

* A render pipeline renders graphics, typically into a `<canvas>` element, but it could also render graphics offscreen. It has two main stages:
    + A vertex stage, in which a vertex shader takes positioning data fed into the GPU and uses it to position a series of vertices in 3D space by applying specified effects like rotation, translation, or perspective. The vertices are then assembled into primitives such as triangles (the basic building block of rendered graphics) and rasterized by the GPU to figure out what pixels each one should cover on the drawing canvas.
    + A fragment stage, in which a fragment shader computes the color for each pixel covered by the primitives produced by the vertex shader. These computations frequently use inputs such as images (in the form of textures) that provide surface details and the position and color of virtual lights.
* A compute pipeline is for general computation. A compute pipeline contains a single compute stage in which a compute shader takes general data, processes it in parallel across a specified number of workgroups, then returns the result in one or more buffers. The buffers can contain any kind of data.

The shaders mentioned above are sets of instructions processed by the GPU. WebGPU shaders are written in a low-level Rust-like language called WebGPU Shader Language (WGSL).

There are several different ways in which you could architect a WebGPU app, but the process will likely contain the following steps:

1. Create shader modules: Write your shader code in WGSL and package it into one or more shader modules.
2. Get and configure the canvas context: Get the `webgpu` context of a `<canvas>` element and configure it to receive information on what graphics to render from your GPU logical device. This step is not necessary if your app has no graphical output, such as one that only uses compute pipelines.
3. Create resources containing your data: The data that you want processed by your pipelines needs to be stored in GPU buffers or textures to be accessed by your app.
4. Create pipelines: Define pipeline descriptors that describe the desired pipelines in detail, including the required data structure, bindings, shaders, and resource layouts, then create pipelines from them. Our basic demos only contain a single pipeline, but non-trivial apps will usually contain multiple pipelines for different purposes.
5. Run a compute/rendering pass: This involves a number of substeps:
    1. Create a command encoder that can encode a set of commands to be passed to the GPU to execute.
    2. Create a pass encoder object on which compute/render commands are issued.
    3. Run commands to specify which pipelines to use, what buffer(s) to get the required data from, how many drawing operations to run (in the case of render pipelines), etc.
    4. Finalize the command list and encapsulate it in a command buffer.
    5. Submit the command buffer to the GPU via the logical device's command queue.

In the sections below, we will examine a basic render pipeline demo, to allow you to explore what it requires. Later on, we'll also examine a basic compute pipeline example, looking at how it differs from the render pipeline.

Basic render pipeline
---------------------

In our basic render demo we give a `<canvas>` element a solid blue background and draw a triangle onto it.

### Create shader modules

We are using the following shader code. The vertex shader stage (`@vertex` block) accepts a chunk of data containing a position and a color, positions the vertex according to the given position, interpolates the color, then passes the data along to the fragment shader stage. The fragment shader stage (`@fragment` block) accepts the data from the vertex shader stage and colors the vertex according to the given color.

```js
const shaders = `
struct VertexOut {
 @builtin(position) position : vec4f,
 @location(0) color : vec4f
}

@vertex
fn vertex\_main(@location(0) position: vec4f,
 @location(1) color: vec4f) -> VertexOut
{
 var output : VertexOut;
 output.position = position;
 output.color = color;
 return output;
}

@fragment
fn fragment\_main(fragData: VertexOut) -> @location(0) vec4f
{
 return fragData.color;
}
`;
```

**Note:** In our demos we are storing our shader code inside a template literal, but you can store it anywhere from which it can easily be retrieved as text to be fed into your WebGPU program. For example, another common practice is to store shaders inside a `<script>` element and retrieve the contents using `Node.textContent`. The correct mime type to use for WGSL is `text/wgsl`.

To make your shader code available to WebGPU, you have to put it inside a `GPUShaderModule` via a `GPUDevice.createShaderModule()` call, passing your shader code as a property inside a descriptor object. For example:

```js
const shaderModule = device.createShaderModule({
  code: shaders,
});
```

### Get and configure the canvas context

In a render pipeline, we need to specify somewhere to render the graphics to. In this case we are getting a reference to an onscreen `<canvas>` element then calling `HTMLCanvasElement.getContext()` with a parameter of `webgpu` to return its GPU context (a `GPUCanvasContext` instance).

From there, we configure the context with a call to `GPUCanvasContext.configure()`, passing it an options object containing the `GPUDevice` that the rendering information will come from, the format the textures will have, and the alpha mode to use when rendering semi-transparent textures.

```js
const canvas = document.querySelector("#gpuCanvas");
const context = canvas.getContext("webgpu");

context.configure({
  device: device,
  format: navigator.gpu.getPreferredCanvasFormat(),
  alphaMode: "premultiplied",
});
```

**Note:** The best practice for determining the texture format is to use the `GPU.getPreferredCanvasFormat()` method; this selects the most efficient format (either `bgra8unorm` or `rgba8unorm`) for the user's device.

### Create a buffer and write our triangle data into it

Next we will provide our WebGPU program with our data, in a form it can use. Our data is initially provided in a `Float32Array`, which contains 8 data points for each triangle vertex — X, Y, Z, W for position, and R, G, B, A for color.

```js
const vertices = new Float32Array([
  0.0, 0.6, 0, 1, 1, 0, 0, 1, -0.5, -0.6, 0, 1, 0, 1, 0, 1, 0.5, -0.6, 0, 1, 0,
  0, 1, 1,
]);
```

However, we've got an issue here. We need to get our data into a `GPUBuffer`. Behind the scenes, this type of buffer is stored in memory very tightly integrated with the GPU's cores to allow for the desired high performance processing. As a side effect, this memory can't be accessed by processes running on the host system, like the browser.

The `GPUBuffer` is created via a call to `GPUDevice.createBuffer()`. We give it a size equal to the length of the `vertices` array so it can contain all the data, and `VERTEX` and `COPY_DST` usage flags to indicate that the buffer will be used as a vertex buffer and the destination of copy operations.

```js
const vertexBuffer = device.createBuffer({
  size: vertices.byteLength, // make it big enough to store vertices in
  usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY\_DST,
});
```

We could handle getting our data into the `GPUBuffer` using a mapping operation, like we use in the compute pipeline example to read data from the GPU back to JavaScript. However, in this case we are going to use the handy `GPUQueue.writeBuffer()` convenience method, which takes as its parameters the buffer to write to, the data source to write from, an offset value for each, and the size of data to write (we've specified the whole length of the array). The browser then works out the most efficient way to handle writing the data.

```js
device.queue.writeBuffer(vertexBuffer, 0, vertices, 0, vertices.length);
```

### Define and create the render pipeline

Now we've got our data into a buffer, the next part of the setup is to actually create our pipeline, ready to be used for rendering.

First of all, we create an object that describes the required layout of our vertex data. This perfectly describes what we saw earlier on in our `vertices` array and vertex shader stage — each vertex has position and color data. Both are formatted in `float32x4` format (which maps to the WGSL `vec4<f32>` type), and the color data starts at an offset of 16 bytes into each vertex. `arrayStride` specifies the stride, meaning the number of bytes making up each vertex, and `stepMode` specifies that the data should be fetched per-vertex.

```js
const vertexBuffers = [
  {
    attributes: [
      {
        shaderLocation: 0, // position
        offset: 0,
        format: "float32x4",
      },
      {
        shaderLocation: 1, // color
        offset: 16,
        format: "float32x4",
      },
    ],
    arrayStride: 32,
    stepMode: "vertex",
  },
];
```

Next, we create a descriptor object that specifies the configuration of our render pipeline stages. For both the shader stages, we specify the `GPUShaderModule` that the relevant code can be found in (`shaderModule`), and the name of the function that acts as the entry point for each stage.

In addition, in the case of the vertex shader stage we provide our `vertexBuffers` object to provide the expected state of our vertex data. And in the case of our fragment shader stage, we provide an array of color target states that indicate the specified rendering format (this matches the format specified in our canvas context config earlier).

We also specify a `primitive` state, which in this case just states the type of primitive we will be drawing, and a `layout` of `auto`. The `layout` property defines the layout (structure, purpose, and type) of all the GPU resources (buffers, textures, etc.) used during the execution of the pipeline. In more complex apps, this would take the form of a `GPUPipelineLayout` object, created using `GPUDevice.createPipelineLayout()` (you can see an example in our Basic compute pipeline), which allows the GPU to figure out how to run the pipeline most efficiently ahead of time. Here however we are specifying the `auto` value, which will cause the pipeline to generate an implicit bind group layout based on any bindings defined in the shader code.

```js
const pipelineDescriptor = {
  vertex: {
    module: shaderModule,
    entryPoint: "vertex\_main",
    buffers: vertexBuffers,
  },
  fragment: {
    module: shaderModule,
    entryPoint: "fragment\_main",
    targets: [
      {
        format: navigator.gpu.getPreferredCanvasFormat(),
      },
    ],
  },
  primitive: {
    topology: "triangle-list",
  },
  layout: "auto",
};
```

Finally, we can create a `GPURenderPipeline` based on our `pipelineDescriptor` object, by passing it in as a parameter to a `GPUDevice.createRenderPipeline()` method call.

```js
const renderPipeline = device.createRenderPipeline(pipelineDescriptor);
```

### Running a rendering pass

Now that all the setup is done, we can actually run a rendering pass and draw something onto our `<canvas>`. To encode any commands to be later issued to the GPU, you need to create a `GPUCommandEncoder` instance, which is done using a `GPUDevice.createCommandEncoder()` call.

```js
const commandEncoder = device.createCommandEncoder();
```

Next up we start the rendering pass running by creating a `GPURenderPassEncoder` instance with a `GPUCommandEncoder.beginRenderPass()` call. This method takes a descriptor object as a parameter, the only mandatory property of which is a `colorAttachments` array. In this case, we specify:

1. A texture view to render into; we create a new view from the `<canvas>` via `context.getCurrentTexture().createView()`.
2. That the view should be "cleared" to a specified color once loaded and before any drawing takes place. This is what causes the blue background behind the triangle.
3. That the value of the current rendering pass should be stored for this color attachment.

```js
const clearColor = { r: 0.0, g: 0.5, b: 1.0, a: 1.0 };

const renderPassDescriptor = {
  colorAttachments: [
    {
      clearValue: clearColor,
      loadOp: "clear",
      storeOp: "store",
      view: context.getCurrentTexture().createView(),
    },
  ],
};

const passEncoder = commandEncoder.beginRenderPass(renderPassDescriptor);
```

Now we can invoke methods of the rendering pass encoder to draw our triangle:

1. `GPURenderPassEncoder.setPipeline()` is called with our `renderPipeline` object as a parameter to specify the pipeline to use for the rendering pass.
2. `GPURenderPassEncoder.setVertexBuffer()` is called with our `vertexBuffer` object as a parameter to act as the data source to pass to the pipeline to render. The first parameter is the slot to set the vertex buffer for, and is a reference to the index of the element in the `vertexBuffers` array which describes this buffer's layout.
3. `GPURenderPassEncoder.draw()` sets the drawing in motion. There is data for three vertices inside our `vertexBuffer`, so we set a vertex count value of `3` to draw them all.

```js
passEncoder.setPipeline(renderPipeline);
passEncoder.setVertexBuffer(0, vertexBuffer);
passEncoder.draw(3);
```

To finish encoding the sequence of commands and issue them to the GPU, three more steps are needed.

1. We invoke the `GPURenderPassEncoder.end()` method to signal the end of the render pass command list.
2. We invoke the `GPUCommandEncoder.finish()` method to complete recording of the issued command sequence and encapsulate it into a `GPUCommandBuffer` object instance.
3. We submit the `GPUCommandBuffer` to the device's command queue (represented by a `GPUQueue` instance) to be sent to the GPU. The device's queue is available via the `GPUDevice.queue` property, and an array of `GPUCommandBuffer` instances can be added to the queue via a `GPUQueue.submit()` call.

These three steps can be achieved via the following two lines:

```js
passEncoder.end();

device.queue.submit([commandEncoder.finish()]);
```

Basic compute pipeline
----------------------

In our basic compute demo, we get the GPU to calculate some values, store them in an output buffer, copy the data across to a staging buffer, then map that staging buffer so that the data can be read out to JavaScript and logged to the console.

The app follows a similar structure to the basic rendering demo. We create a `GPUDevice` reference in the same way as before, and encapsulate our shader code into a `GPUShaderModule` via a `GPUDevice.createShaderModule()` call. The difference here is that our shader code only has one shader stage, a `@compute` stage:

```js
// Define global buffer size
const BUFFER\_SIZE = 1000;

const shader = `
@group(0) @binding(0)
var<storage, read\_write> output: array<f32>;

@compute @workgroup\_size(64)
fn main(
 @builtin(global\_invocation\_id)
 global\_id : vec3u,

 @builtin(local\_invocation\_id)
 local\_id : vec3u,
) {
 // Avoid accessing the buffer out of bounds
 if (global\_id.x >= ${BUFFER\_SIZE}) {
 return;
 }

 output[global\_id.x] =
 f32(global\_id.x) \* 1000. + f32(local\_id.x);
}
`;
```

### Create buffers to handle our data

In this example we create two `GPUBuffer` instances to handle our data, an `output` buffer to write the GPU calculation results to at high speed, and a `stagingBuffer` that we'll copy the `output` contents to, which can be mapped to allow JavaScript to access the values.

* `output` is specified as a storage buffer that will be the source of a copy operation.
* `stagingBuffer` is specified as a buffer that can be mapped for reading by JavaScript, and will be the destination of a copy operation.

```js
const output = device.createBuffer({
  size: BUFFER\_SIZE,
  usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY\_SRC,
});

const stagingBuffer = device.createBuffer({
  size: BUFFER\_SIZE,
  usage: GPUBufferUsage.MAP\_READ | GPUBufferUsage.COPY\_DST,
});
```

### Create a bind group layout

When the pipeline is created, we specify a bind group to use for the pipeline. This involves first creating a `GPUBindGroupLayout` (via a call to `GPUDevice.createBindGroupLayout()`) that defines the structure and purpose of GPU resources such as buffers that will be used in this pipeline. This layout is used as a template for bind groups to adhere to. In this case we give the pipeline access to a single memory buffer, tied to binding slot 0 (this matches the relevant binding number in our shader code — `@binding(0)`), usable in the compute stage of the pipeline, and with the buffer's purpose defined as `storage`.

```js
const bindGroupLayout = device.createBindGroupLayout({
  entries: [
    {
      binding: 0,
      visibility: GPUShaderStage.COMPUTE,
      buffer: {
        type: "storage",
      },
    },
  ],
});
```

Next we create a `GPUBindGroup` by calling `GPUDevice.createBindGroup()`. We pass this method call a descriptor object that specifies the bind group layout to base this bind group on, and the details of the variable to bind to the slot defined in the layout. In this case, we are declaring binding 0, and specifying that the `output` buffer we defined earlier should be bound to it.

```js
const bindGroup = device.createBindGroup({
  layout: bindGroupLayout,
  entries: [
    {
      binding: 0,
      resource: {
        buffer: output,
      },
    },
  ],
});
```

**Note:** You could retrieve an implicit layout to use when creating a bind group by calling the `GPUComputePipeline.getBindGroupLayout()` method. There is also a version available for render pipelines: see `GPURenderPipeline.getBindGroupLayout()`.

### Create a compute pipeline

With the above all in place, we can now create a compute pipeline by calling `GPUDevice.createComputePipeline()`, passing it a pipeline descriptor object. This works in a similar way to creating a render pipeline. We describe the compute shader, specifying what module to find the code in and what the entry point is. We also specify a `layout` for the pipeline, in this case creating a layout based on the `bindGroupLayout` we defined earlier via a `GPUDevice.createPipelineLayout()` call.

```js
const computePipeline = device.createComputePipeline({
  layout: device.createPipelineLayout({
    bindGroupLayouts: [bindGroupLayout],
  }),
  compute: {
    module: shaderModule,
    entryPoint: "main",
  },
});
```

One difference here from the render pipeline layout is that we are not specifying a primitive type, as we are not drawing anything.

### Running a compute pass

Running a compute pass is similar in structure to running a rendering pass, with some different commands. For a start, the pass encoder is created using `GPUCommandEncoder.beginComputePass()`.

When issuing the commands, we specify the pipeline to use in the same way as before, using `GPUComputePassEncoder.setPipeline()`. We then however use `GPUComputePassEncoder.setBindGroup()` to specify that we want to use our `bindGroup` to specify the data to use in the calculation, and `GPUComputePassEncoder.dispatchWorkgroups()` to specify the number of GPU workgroups to use to run the calculations.

We then signal the end of the render pass command list using `GPURenderPassEncoder.end()`.

```js
passEncoder.setPipeline(computePipeline);
passEncoder.setBindGroup(0, bindGroup);
passEncoder.dispatchWorkgroups(Math.ceil(BUFFER\_SIZE / 64));

passEncoder.end();
```

### Reading the results back to JavaScript

Before submitting the encoded commands to the GPU for execution using `GPUQueue.submit()`, we copy the contents of the `output` buffer to the `stagingBuffer` buffer using `GPUCommandEncoder.copyBufferToBuffer()`.

```js
// Copy output buffer to staging buffer
commandEncoder.copyBufferToBuffer(
  output,
  0, // Source offset
  stagingBuffer,
  0, // Destination offset
  BUFFER\_SIZE,
);

// End frame by passing array of command buffers to command queue for execution
device.queue.submit([commandEncoder.finish()]);
```

Once the output data is available in the `stagingBuffer`, we use the `GPUBuffer.mapAsync()` method to map the data to intermediate memory, grab a reference to the mapped range using `GPUBuffer.getMappedRange()`, copy the data into JavaScript, and then log it to the console. We also unmap the `stagingBuffer` once we are finished with it.

```js
// map staging buffer to read results back to JS
await stagingBuffer.mapAsync(
  GPUMapMode.READ,
  0, // Offset
  BUFFER\_SIZE, // Length
);

const copyArrayBuffer = stagingBuffer.getMappedRange(0, BUFFER\_SIZE);
const data = copyArrayBuffer.slice();
stagingBuffer.unmap();
console.log(new Float32Array(data));
```

GPU error handling
------------------

WebGPU calls are validated asynchronously in the GPU process. If errors are found, the problem call is marked as invalid on the GPU side. If another call is made that relies on the return value of an invalidated call, that object will also be marked as invalid, and so on. For this reason, errors in WebGPU are referred to as "contagious".

Each `GPUDevice` instance maintains its own error scope stack. This stack is initially empty, but you can start pushing an error scope to the stack by invoking `GPUDevice.pushErrorScope()` to capture errors of a particular type.

Once you are done capturing errors, you can end capture by invoking `GPUDevice.popErrorScope()`. This pops the scope from the stack and returns a `Promise` that resolves to an object (`GPUInternalError`, `GPUOutOfMemoryError`, or `GPUValidationError`) describing the first error captured in the scope, or `null` if no errors were captured.

We have attempted to provide useful information to help you understand why errors are occurring in your WebGPU code in "Validation" sections where appropriate, which list criteria to meet to avoid errors. See for example the `GPUDevice.createBindGroup()` Validation section. Some of this information is complex; rather than repeat the spec, we have decided to just list error criteria that are:

* Non-obvious, for example combinations of descriptor properties that produce validation errors. There is no point telling you to make sure you use the correct descriptor object structure. That is both obvious and vague.
* Developer-controlled. Some of the error criteria are purely based on internals and not really relevant to web developers.

You can find more information about WebGPU error handling in the explainer — see Object validity and destroyed-ness and Errors. WebGPU Error Handling best practices provides useful real-world examples and advice.

**Note:** The historic way of handling errors in WebGL is to provide a `getError()` method to return error information. This is problematic in that it returns errors synchronously, which is bad for performance — each call requires a round-trip to the GPU and requires all previously issued operations to be finished. Its state model is also flat, meaning that errors can leak between unrelated code. The creators of WebGPU were determined to improve on this.

Interfaces
----------

### Entry point for the API

`Navigator.gpu` / `WorkerNavigator.gpu`

The entry point for the API — returns the `GPU` object for the current context.

`GPU`

The starting point for using WebGPU. It can be used to return a `GPUAdapter`.

`GPUAdapter`

Represents a GPU adapter. From this you can request a `GPUDevice`, adapter info, features, and limits.

`GPUAdapterInfo`

Contains identifying information about an adapter.

### Configuring GPUDevices

`GPUDevice`

Represents a logical GPU device. This is the main interface through which the majority of WebGPU functionality is accessed.

`GPUSupportedFeatures`

A setlike object that describes additional functionality supported by a `GPUAdapter` or `GPUDevice`.

`GPUSupportedLimits`

Describes the limits supported by a `GPUAdapter` or `GPUDevice`.

### Configuring a rendering `<canvas>`

`HTMLCanvasElement.getContext()` — the `"webgpu"` `contextType`

Invoking `getContext()` with the `"webgpu"` `contextType` returns a `GPUCanvasContext` object instance, which can then be configured with `GPUCanvasContext.configure()`.

`GPUCanvasContext`

Represents the WebGPU rendering context of an `<canvas>` element.

### Representing pipeline resources

`GPUBuffer`

Represents a block of memory that can be used to store raw data to use in GPU operations.

`GPUExternalTexture`

A wrapper object containing an `HTMLVideoElement` snapshot that can be used as a texture in GPU rendering operations.

`GPUSampler`

Controls how shaders transform and filter texture resource data.

`GPUShaderModule`

A reference to an internal shader module object, a container for WGSL shader code that can be submitted to the GPU to execution by a pipeline.

`GPUTexture`

A container used to store 1D, 2D, or 3D arrays of data, such as images, to use in GPU rendering operations.

`GPUTextureView`

A view onto some subset of the texture subresources defined by a particular `GPUTexture`.

### Representing pipelines

`GPUBindGroup`

Based on a `GPUBindGroupLayout`, a `GPUBindGroup` defines a set of resources to be bound together in a group and how those resources are used in shader stages.

`GPUBindGroupLayout`

Defines the structure and purpose of related GPU resources such as buffers that will be used in a pipeline, and is used as a template when creating `GPUBindGroup`s.

`GPUComputePipeline`

Controls the compute shader stage and can be used in a `GPUComputePassEncoder`.

`GPUPipelineLayout`

Defines the `GPUBindGroupLayout`s used by a pipeline. `GPUBindGroup`s used with the pipeline during command encoding must have compatible `GPUBindGroupLayout`s.

`GPURenderPipeline`

Controls the vertex and fragment shader stages and can be used in a `GPURenderPassEncoder` or `GPURenderBundleEncoder`.

### Encoding and submitting commands to the GPU

`GPUCommandBuffer`

Represents a recorded list of GPU commands that can be submitted to a `GPUQueue` for execution.

`GPUCommandEncoder`

Represents a command encoder, used to encode commands to be issued to the GPU.

`GPUComputePassEncoder`

Encodes commands related to controlling the compute shader stage, as issued by a `GPUComputePipeline`. Part of the overall encoding activity of a `GPUCommandEncoder`.

`GPUQueue`

controls execution of encoded commands on the GPU.

`GPURenderBundle`

A container for pre-recorded bundles of commands (see `GPURenderBundleEncoder`).

`GPURenderBundleEncoder`

Used to pre-record bundles of commands. These can be reused in `GPURenderPassEncoder`s via the `executeBundles()` method, as many times as required.

`GPURenderPassEncoder`

Encodes commands related to controlling the vertex and fragment shader stages, as issued by a `GPURenderPipeline`. Part of the overall encoding activity of a `GPUCommandEncoder`.

### Running queries on rendering passes

`GPUQuerySet`

Used to record the results of queries on passes, such as occlusion or timestamp queries.

### Debugging errors

`GPUCompilationInfo`

An array of `GPUCompilationMessage` objects, generated by the GPU shader module compiler to help diagnose problems with shader code.

`GPUCompilationMessage`

Represents a single informational, warning, or error message generated by the GPU shader module compiler.

`GPUDeviceLostInfo`

Returned when the `GPUDevice.lost` `Promise` resolves, providing information as to why the device was lost.

`GPUError`

The base interface for errors surfaced by `GPUDevice.popErrorScope` and the `uncapturederror` event.

`GPUInternalError`

One of the types of errors surfaced by `GPUDevice.popErrorScope` and the `GPUDevice` `uncapturederror` event. Indicates that an operation failed for a system or implementation-specific reason, even when all validation requirements were satisfied.

`GPUOutOfMemoryError`

One of the types of errors surfaced by `GPUDevice.popErrorScope` and the `GPUDevice` `uncapturederror` event. Indicates that there was not enough free memory to complete the requested operation.

`GPUPipelineError`

Describes a pipeline failure. The value received when a `Promise` returned by a `GPUDevice.createComputePipelineAsync()` or `GPUDevice.createRenderPipelineAsync()` call rejects.

`GPUUncapturedErrorEvent`

The event object type for the `GPUDevice` `uncapturederror` event.

`GPUValidationError`

One of the types of errors surfaced by `GPUDevice.popErrorScope` and the `GPUDevice` `uncapturederror` event. Describes an application error indicating that an operation did not pass the WebGPU API's validation constraints.

Security requirements
---------------------

The whole API is available only in a secure context.

Examples
--------

* Basic compute demo
* Basic render demo
* WebGPU samples
Specifications
--------------

| Specification |
| --- |
| WebGPU # gpu-interface |

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

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

See also
--------

* WebGPU best practices
* WebGPU explainer
* WebGPU — All of the cores, none of the canvas


OES_standard_derivatives extension - Web APIs

OES\_standard\_derivatives extension
====================================

The **`OES_standard_derivatives`** extension is part of the WebGL API and adds the GLSL derivative functions `dFdx`, `dFdy`, and `fwidth`.

WebGL extensions are available using the `WebGLRenderingContext.getExtension()` method. For more information, see also Using Extensions in the WebGL tutorial.

**Note:** This extension is only available to WebGL1 contexts. In WebGL2, the functionality of this extension is available on the WebGL2 context by default. In WebGL 2, the constant is available as `gl.FRAGMENT_SHADER_DERIVATIVE_HINT` and it requires GLSL `#version 300 es`.

Constants
---------

This extension exposes one new constant, which can be used in the `hint()` and `getParameter()` methods.

`ext.FRAGMENT_SHADER_DERIVATIVE_HINT_OES`

A `WebGL_API.Types` indicating the accuracy of the derivative calculation for the GLSL built-in functions: `dFdx`, `dFdy`, and `fwidth`.

GLSL built-in functions
-----------------------

The following new functions can be used in GLSL shader code, if this extension is enabled:

```cpp
genType dFdx(genType)
genType dFdy(genType)
genType fwidth(genType)
```

Examples
--------

Enabling the extensions:

```js
gl.getExtension("OES\_standard\_derivatives");
gl.getExtension("EXT\_shader\_texture\_lod");
```

Shader code that avoids artifacts when wrapping texture coordinates:

```html
<script type="x-shader/x-fragment">
 #extension GL\_EXT\_shader\_texture\_lod : enable
 #extension GL\_OES\_standard\_derivatives : enable

 uniform sampler2D myTexture;
 varying vec2 texcoord;

 void main(){
 gl\_FragColor = texture2DGradEXT(myTexture, mod(texcoord, vec2(0.1, 0.5)),
 dFdx(texcoord), dFdy(texcoord));
 }
</script>
```

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

| Specification |
| --- |
| WebGL OES\_standard\_derivatives Khronos Ratified Extension Specification  |

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

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

See also
--------

* `WebGLRenderingContext.getExtension()`
* `EXT_shader_texture_lod`


CSSScale - Web APIs

CSSScale
========

The **`CSSScale`** interface of the CSS\_Object\_Model#css\_typed\_object\_model represents the scale() and scale3d() values of the individual `transform` property in CSS. It inherits properties and methods from its parent `CSSTransformValue`.

CSSTransformComponent

CSSScaleConstructor
-----------

`CSSScale()`

Creates a new `CSSScale` object.

Instance properties
-------------------

`x`

Returns or sets the x-axis value.

`y`

Returns or sets the y-axis value.

`z`

Returns or sets the z-axis value.

Examples
--------

To do.

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

| Specification |
| --- |
| CSS Typed OM Level 1 # cssscale |

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

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