GPUDevice: createBindGroup() method - Web APIs

GPUDevice: createBindGroup() method
===================================

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

 The **`createBindGroup()`** method of the
 `GPUDevice` interface creates a `GPUBindGroup` based on a `GPUBindGroupLayout` that defines a set of resources to be bound together in a group and how those resources are used in shader stages.

Syntax
------

```js
createBindGroup(descriptor)
```

### Parameters

`descriptor`

An object containing the following properties:

`entries`

An array of entry objects describing the resources to expose to the shader. There will be one for each corresponding entry described by the `GPUBindGroupLayout` referenced in `layout`. Each entry object has the following properties:

`binding`

A number representing a unique identifier for this resource binding, which matches the `binding` value of a corresponding `GPUBindGroupLayout` entry. In addition, it matches the `n` index value of the corresponding `@binding(n)` attribute in the shader (`GPUShaderModule`) used in the related pipeline.

`resource`

The resource to bind. This can be one of the following:

* `GPUBufferBinding` (which wraps a `GPUBuffer`; see GPUBufferBinding objects for a definition)
* `GPUExternalTexture`
* `GPUSampler`
* `GPUTextureView`

`label` Optional

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

`layout`

The `GPUBindGroupLayout` that the `entries` of this bind group will conform to.

### GPUBufferBinding objects

A `GPUBufferBinding` object can contain the following properties:

`buffer`

The `GPUBuffer` object you want to bind.

`offset` Optional

The offset, in bytes, from the beginning of the `buffer` to the beginning of the range exposed to the shader by the buffer binding. If omitted, `offset` defaults to 0.

`size` Optional

The size, in bytes, of the buffer binding. If omitted, `size` will be the range starting at `offset` and ending at the end of the `buffer`. If both `offset` and `size` are omitted, the entire buffer is exposed to the shader.

### Return value

A `GPUBindGroup` object instance.

### Validation

The following criteria must be met when calling **`createBindGroup()`**, otherwise a `GPUValidationError` is generated and an invalid `GPUBindGroup` object is returned:

* The number of entries in the `layout` `GPUBindGroupLayout` equals the number of entry objects in `entries`.
* For each entry in the `layout` `GPUBindGroupLayout`, the corresponding entry object in `entries` binds the correct resource type. For example, a `buffer` resource layout object has a `GPUBufferBinding` object specified in the corresponding binding.
* If the resource layout object is a `buffer`:
    + The corresponding bound `GPUBuffer`:
        - Has its bound part (as specified by `offset` and `size`) contained inside it completely, with a non-zero size.
        - Has a size bigger than the `buffer` resource layout's `minBindingSize`.
    + If the resource layout object `type` is `"uniform"`:
        - The bound `GPUBuffer` has a `usage` that includes `GPUBufferUsage.UNIFORM`.
        - The effective size of the bound buffer segment is less than or equal to the `GPUDevice`'s `maxUniformBufferBindingSize` limit.
        - The specified `GPUBufferBinding` `offset` is a multiple of the `GPUDevice`'s `minUniformBufferOffsetAlignment` limit.
    + If the resource layout object `type` is `"storage"` or `"read-only-storage"`:
        - The bound `GPUBuffer` has a `usage` that includes `GPUBufferUsage.STORAGE`.
        - The effective size of the bound buffer segment is less than or equal to the `GPUDevice`'s `maxStorageBufferBindingSize` limit.
        - The effective size of the bound buffer segment is a multiple of 4.
        - The specified `GPUBufferBinding` `offset` is a multiple of the `GPUDevice`'s `minStorageBufferOffsetAlignment` limit.
* If the resource layout object is a `storageTexture`, the corresponding bound `GPUTextureView`:
    + Has a `dimension` equal to the resource layout object's `viewDimension` (see `GPUTexture.createView()` for more details of a texture view's settings).
    + Has a `format` equal to the resource layout object's `sampleType`.
    + Has a `mipLevelCount` equal to 1.
    + Is a view of a `GPUTexture` with a `usage` that includes `GPUTextureUsage.STORAGE_BINDING`.
* If the resource layout object is a `texture`, the corresponding bound `GPUTextureView`:
    + Has a `dimension` equal to the resource layout object's `viewDimension` (see `GPUTexture.createView()` for more details of a texture view's settings).
    + Has a `format` compatible with the resource layout object's `sampleType`.
    + Is a view of a `GPUTexture` with a `usage` that includes `GPUTextureUsage.TEXTURE_BINDING`.
    + is a view of a `GPUTexture` with a `sampleCount` greater than 1 if the resource layout object's `multisampled` property is `true`, or equal to 1 if it is `false`.
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 # dom-gpudevice-createbindgroup |

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

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

See also
--------

* The WebGPU API


GPUDevice: destroy() method - Web APIs

GPUDevice: destroy() method
===========================

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

 The **`destroy()`** method of the
 `GPUDevice` interface destroys the device, preventing further operations on it.

Note that:

* Any commands currently enqueued on the device's `GPUQueue` will be executed before the device is destroyed.
* Any WebGPU resources created using the device (buffers, textures, etc.) are also destroyed.
* Any mapped buffers created using the device will be unmapped.
Syntax
------

```js
destroy()
```

### Parameters

None.

### Return value

None (`undefined`).

Examples
--------

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

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

  let device = await adapter.requestDevice();

  // Some time later

  device.destroy();
}
```

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

| Specification |
| --- |
| WebGPU # dom-gpudevice-destroy |

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

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

See also
--------

* The WebGPU API


GPUDevice: createCommandEncoder() method - Web APIs

GPUDevice: createCommandEncoder() method
========================================

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

 The **`createCommandEncoder()`** method of the
 `GPUDevice` interface creates a `GPUCommandEncoder`, used to encode commands to be issued to the GPU.

Syntax
------

```js
createCommandEncoder()
createCommandEncoder(descriptor)
```

### Parameters

`descriptor` Optional

An object containing the following properties:

`label` Optional

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

### Return value

A `GPUCommandEncoder` object instance.

Examples
--------

In our basic render demo, several commands are recorded via a `GPUCommandEncoder` created via `createCommandEncoder()`:

```js
// ...

// Create GPUCommandEncoder
const commandEncoder = device.createCommandEncoder();

// Create GPURenderPassDescriptor to tell WebGPU which texture to draw into, then initiate render pass
const renderPassDescriptor = {
  colorAttachments: [
    {
      clearValue: clearColor,
      loadOp: "clear",
      storeOp: "store",
      view: context.getCurrentTexture().createView(),
    },
  ],
};

const passEncoder = commandEncoder.beginRenderPass(renderPassDescriptor);

// Draw a triangle
passEncoder.setPipeline(renderPipeline);
passEncoder.setVertexBuffer(0, vertexBuffer);
passEncoder.draw(3);

// End the render pass
passEncoder.end();

// ...
```

The commands encoded by the `GPUCommandEncoder` are recoded into a `GPUCommandBuffer` using the `GPUCommandEncoder.finish()` method. The command buffer is then passed into the queue via a `submit()` call, ready to be processed by the GPU.

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

**Note:** Study the WebGPU samples to find more command encoding examples.

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

| Specification |
| --- |
| WebGPU # dom-gpudevice-createcommandencoder |

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

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

See also
--------

* The WebGPU API


GPUDevice: label property - Web APIs

GPUDevice: label property
=========================

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

 The **`label`** read-only property of the
 `GPUDevice` interface is a string providing a label that can be used to identify the object, for example in `GPUError` messages or console warnings.

Value
-----

A string. If no label value has previously been set, getting the label returns an empty string.

Examples
--------

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

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

  // Create a GPUDevice
  const device = await adapter.requestDevice();

  // Set a label
  device.label = "mylabel";

  // Get a label
  console.log(device.label);

  // ...
}
```

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

| Specification |
| --- |
| WebGPU # dom-gpuobjectbase-label |

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

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

See also
--------

* The WebGPU API


GPUDevice: createRenderPipeline() method - Web APIs

GPUDevice: createRenderPipeline() method
========================================

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

 The **`createRenderPipeline()`** method of the
 `GPUDevice` interface creates a `GPURenderPipeline` that can control the vertex and fragment shader stages and be used in a `GPURenderPassEncoder` or `GPURenderBundleEncoder`.

Syntax
------

```js
createRenderPipeline(descriptor)
```

### Parameters

`descriptor`

An object containing the following properties:

`depthStencil` Optional

An object (see `depthStencil` object structure) describing depth-stencil properties including testing, operations, and bias.

`fragment` Optional

An object (see `fragment` object structure) describing the fragment shader entry point of the pipeline and its output colors. If no fragment shader entry point is defined, the pipeline will not produce any color attachment outputs, but it still performs rasterization and produces depth values based on the vertex position output. Depth testing and stencil operations can still be used.

`label` Optional

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

`layout`

Defines the layout (structure, purpose, and type) of all the GPU resources (buffers, textures, etc.) used during the execution of the pipeline. Possible values are:

* A `GPUPipelineLayout` object, created using `GPUDevice.createPipelineLayout()`, which allows the GPU to figure out how to run the pipeline most efficiently ahead of time.
* A string of `"auto"`, which causes the pipeline to generate an implicit bind group layout based on any bindings defined in the shader code. If `"auto"` is used, the generated bind group layouts may only be used with the current pipeline.

`multisample` Optional

An object (see `multisample` object structure) describing how the pipeline interacts with a render pass's multisampled attachments.

`primitive` Optional

An object (see `primitive` object structure) describing how a pipeline constructs and rasterizes primitives from its vertex inputs.

`vertex`

An object (see `vertex` object structure) describing the vertex shader entry point of the pipeline and its input buffer layouts.

### `depthStencil` object structure

The `depthStencil` object can contain the following properties:

`depthBias` Optional

A number representing a constant depth bias that is added to each fragment. If omitted, `depthBias` defaults to 0.

`depthBiasClamp` Optional

A number representing the maximum depth bias of a fragment. If omitted, `depthBiasClamp` defaults to 0.

`depthBiasSlopeScale` Optional

A number representing a depth bias that scales with the fragment's slope. If omitted, `depthBiasSlopeScale` defaults to 0.

`depthCompare`

An enumerated value specifying the comparison operation used to test fragment depths against `depthStencilAttachment` depth values. Possible values are:

* `"never"`: Comparison tests never pass.
* `"less"`: A provided value passes the comparison test if it is less than the sampled value.
* `"equal"`: A provided value passes the comparison test if it is equal to the sampled value.
* `"less-equal"`: A provided value passes the comparison test if it is less than or equal to the sampled value.
* `"greater"`: A provided value passes the comparison test if it is greater than the sampled value.
* `"not-equal"`: A provided value passes the comparison test if it is not equal to the sampled value.
* `"greater-equal"`: A provided value passes the comparison test if it is greater than or equal to the sampled value.
* `"always"`: Comparison tests always pass.

`depthWriteEnabled`

A boolean. A value of `true` specifies that the `GPURenderPipeline` can modify `depthStencilAttachment` depth values after creation. Setting it to `false` means it cannot.

`format`

An enumerated value specifying the `depthStencilAttachment` format that the `GPURenderPipeline` will be compatible with. See the specification's Texture Formats section for all the available `format` values.

`stencilBack` Optional

An object that defines how stencil comparisons and operations are performed for back-facing primitives. Its properties can include:

`compare` Optional

An enumerated value specifying the comparison operation used when testing fragments against `depthStencilAttachment` stencil values. Possible values are the same as for the `depthCompare` property; see above. If omitted, `compare` defaults to `"always"`.

`depthFailOp` Optional

An enumerated value specifying the stencil operation performed if the fragment depth comparison described by `depthCompare` fails. Possible values are:

* `"decrement-clamp"`: Decrement the current render state stencil value, clamping it to 0.
* `"decrement-wrap"`: Decrement the current render state stencil value, wrapping it to the maximum representable value of the `depthStencilAttachment`'s stencil aspect if the value goes below 0.
* `"invert"`: Bitwise-invert the current render state stencil value.
* `"increment-clamp"`: Increments the current render state stencil value, clamping it to the maximum representable value of the `depthStencilAttachment`'s stencil aspect.
* `"increment-wrap"`: Increments the current render state stencil value, wrapping it to zero if the value exceeds the maximum representable value of the `depthStencilAttachment`'s stencil aspect.
* `"keep"`: Keep the current stencil value.
* `"replace"`: Set the stencil value to the current render state stencil value.
* `"zero"`: Set the stencil value to 0.

If omitted, `depthFailOp` defaults to `"keep"`.

**Note:**: The render state stencil value is initialized to 0 at the start of a render pass.

`failOp` Optional

An enumerated value specifying the stencil operation performed if the fragment stencil comparison test described by `compare` fails. Possible and default values are the same as for `depthFailOp`.

`passOp` Optional

An enumerated value specifying the stencil operation performed if the fragment stencil comparison test described by `compare` passes. Possible and default values are the same as for `depthFailOp`.

`stencilFront` Optional

An object that defines how stencil comparisons and operations are performed for front-facing primitives. Its properties are the same as for `stencilBack`.

`stencilReadMask` Optional

A bitmask controlling which `depthStencilAttachment` stencil value bits are read when performing stencil comparison tests. If omitted, `stencilReadMask` defaults to `0xFFFFFFFF`.

`stencilWriteMask` Optional

A bitmask controlling which `depthStencilAttachment` stencil value bits are written to when performing stencil operations. If omitted, `stencilWriteMask` defaults to `0xFFFFFFFF`.

**Note:** `depthStencilAttachment` values are specified during `GPUCommandEncoder.beginRenderPass()` calls, when the `GPURenderPipeline` is actually used to perform a render pass.

### `fragment` object structure

The `fragment` object contains an array of objects, each of which can contain the following properties:

`constants` Optional

A sequence of record types, with the structure `(id, value)`, representing override values for WGSL constants that can be overridden in the pipeline. These behave like ordered maps. In each case, the `id` is a key used to identify or select the record, and the `constant` is an enumerated value representing a WGSL.

Depending on which constant you want to override, the `id` may take the form of the numeric ID of the constant, if one is specified, or otherwise the constant's identifier name.

A code snippet providing override values for several overridable constants might look like this:

```js
{
  // ...
  constants: {
    0: false,
    1200: 3.0,
    1300: 2.0,
    width: 20,
    depth: -1,
    height: 15,
  }
}
```

`entryPoint`

The name of the function in the `module` that this stage will use to perform its work. The corresponding shader function must have the `@fragment` attribute to be identified as this entry point. See Entry Point Declaration for more information.

`module`

A `GPUShaderModule` object containing the WGSL code that this programmable stage will execute.

`targets`

an array of objects representing color states that represent configuration details for the colors output by the fragment shader stage. These objects can include the following properties:

`blend` Optional

A object that describes a blend mode to be applied to the output color. `blend` has two properties:

`alpha`

Describes the alpha channel value.

`color`

Describes the color value.

`alpha` and `color` both take an object as a value that can include the following properties:

`dstFactor` Optional

An enumerated value that defines the blend factor operation to be performed on values from the target attachment. Possible values are:

* `"constant"`
* `"dst"`
* `"dst-alpha"`
* `"one"`
* `"one-minus-dst"`
* `"one-minus-src"`
* `"one-minus-src-alpha"`
* `"one-minus-dst-alpha"`
* `"one-minus-constant"`
* `"src"`
* `"src-alpha"`
* `"src-alpha-saturated"`
* `"zero"`

If omitted, `dstFactor` defaults to `"zero"`.

`operation` Optional

An enumerated value that defines the algorithm used to combine source and destination blend factors, to calculate the final values written to the target attachment components. Possible values are:

* `"add"`
* `"max"`
* `"min"`
* `"reverse-subtract"`
* `"subtract"`

If omitted, `operation` defaults to `"add"`.

`srcFactor` Optional

An enumerated value that defines the blend factor operation to be performed on values from the fragment shader. Possible values are the same as for `dstFactor`. If omitted, `srcFactor` defaults to `"one"`.

**Note:** For a detailed explanation of the algorithms defined by each `dstFactor`/`srcFactor` and `operation` enumerated value, see the Blend State section of the specification.

`format`

An enumerated value specifying the required format for output colors. See the specification's Texture Formats section for all the available `format` values.

`writeMask` Optional

One or more bitwise flags defining the write mask to apply to the color target state. Possible flag values are:

* `GPUFlagsConstant.RED`
* `GPUFlagsConstant.GREEN`
* `GPUFlagsConstant.BLUE`
* `GPUFlagsConstant.ALPHA`
* `GPUFlagsConstant.ALL`

If omitted, `writeMask` defaults to `GPUFlagsConstant.ALL`.

Note that multiple flags can be specified by separating values with pipe symbols, for example:

```js
writeMask: GPUFlagsConstant.RED | GPUFlagsConstant.ALPHA;
```

### `multisample` object structure

The `multisample` object can contain the following properties:

`alphaToCoverageEnabled` Optional

A boolean. A value of `true` indicates that a fragment's alpha channel should be used to generate a sample coverage mask. If omitted, `alphaToCoverageEnabled` defaults to `false`.

`count` Optional

A number that defines the number of samples per pixel. The pipeline will be compatible only with attachment textures (`colorAttachment`s and `depthStencilAttachment`s) with matching `sampleCounts` (see `GPUTexture`).

If omitted, `count` defaults to 1.

`mask` Optional

A bitmask that determines which samples are written to. If omitted, `mask` defaults to `0xFFFFFFFF`.

**Note:** `colorAttachment` and `depthStencilAttachment` values are specified during `GPUCommandEncoder.beginRenderPass()` calls, when the `GPURenderPipeline` is actually used to perform a render pass.

### `primitive` object structure

The `primitive` object can contain the following properties:

`cullMode` Optional

An enumerated value that defines which polygon orientation will be culled, if any. Possible values are:

* `"back"`: Back-facing polygons are culled.
* `"front"`: Front-facing polygons are culled.
* `"none"`: No polygons are culled.

If omitted, `cullMode` defaults to `"none"`.

`frontFace` Optional

An enumerated value that defines which polygons are considered front-facing. Possible values are:

* `"ccw"`: Polygons with vertices whose framebuffer coordinates are given in counter-clockwise order.
* `"cw"`: Polygons with vertices whose framebuffer coordinates are given in clockwise order.

If omitted, `frontFace` defaults to `"ccw"`.

`stripIndexFormat` Optional

An enumerated value that determines the index buffer format and primitive restart value in the case of pipelines with strip topologies (`"line-strip"` or `"triangle-strip"`). The primitive restart value specifies which index value indicates that a new primitive should be started rather than continuing to construct the strip with the prior indexed vertices. Possible values are:

* `"uint16"`: Indicates a byte size of 2 and a primitive restart value of `0xFFFF`.
* `"uint32"`: Indicates a byte size of 4 and a primitive restart value of `0xFFFFFFFF`.

GPU primitive states that specify a strip primitive topology must specify a strip index format if they are used for indexed draws (for example, via `GPURenderPassEncoder.drawIndexed()`) so that the primitive restart value that will be used is known at pipeline creation time. Pipelines with list primitive topologies (`"line-list"`, `"point-list"`, or `"triangle-list"`) should not specify a `stripIndexFormat` value. They will instead use the index format passed to, for example, `GPURenderPassEncoder.setIndexBuffer()` when doing indexed rendering.

`topology` Optional

An enumerated value that defines the type of primitive to be constructed from the specified `vertex` inputs. Possible values are:

* `"line-list"`: Each consecutive pair of two vertices defines a line primitive.
* `"line-strip"`: Each vertex after the first defines a line primitive between it and the previous vertex.
* `"point-list"`: Each vertex defines a point primitive.
* `"triangle-list"`: Each consecutive triplet of three vertices defines a triangle primitive.
* `"triangle-strip"`: Each vertex after the first two defines a triangle primitive between it and the previous two vertices.

If omitted, `topology` defaults to `"triangle-list"`.

`unclippedDepth` Optional

A boolean. A value of `true` indicates that depth clipping is disabled. If omitted, `unclippedDepth` defaults to `false`. Note that to control depth clipping, the `depth-clip-control` feature must be enabled in the `GPUDevice`.

**Note:** `frontFace` and `cullMode` have no effect on `"point-list"`, `"line-list"`, or `"line-strip"` topologies.

### `vertex` object structure

The `vertex` object can contain the following properties:

`constants` Optional

A sequence of record types, with the structure `(id, value)`, representing override values for WGSL constants that can be overridden in the pipeline. These behave like ordered maps. In each case, the `id` is a key used to identify or select the record, and the `constant` is an enumerated value representing a WGSL.

Depending on which constant you want to override, the `id` may take the form of the numeric ID of the constant, if one is specified, or otherwise the constant's identifier name.

A code snippet providing override values for several overridable constants might look like this:

```js
{
  // ...
  constants: {
    0: false,
    1200: 3.0,
    1300: 2.0,
    width: 20,
    depth: -1,
    height: 15,
  }
}
```

`entryPoint`

The name of the function in the `module` that this stage will use to perform its work. The corresponding shader function must have the `@vertex` attribute to be identified as this entry point. See Entry Point Declaration for more information.

`module`

A `GPUShaderModule` object containing the WGSL code that this programmable stage will execute.

`buffers` Optional

An array of objects, each representing the expected layout of a vertex buffer used in the pipeline. Each object can contain the following properties:

`arrayStride`

A number representing the stride, in bytes, between the different structures (e.g. vertices) inside the buffer.

`attributes`

An array of objects defining the layout of the vertex attributes within each structure. Each object has the following properties:

`format`

An enumerated value that specifies the format of the vertex. For all the available values, see the `GPUVertexFormat` definition in the specification.

`offset`

A number specifying the offset, in bytes, from the beginning of the structure to the data for the attribute.

`shaderLocation`

The numeric location associated with this attribute, which will correspond with a `@location` attribute declared in the WGSL code of the associated `GPUShaderModule` referenced in the `vertex` object's `module` property.

`stepMode` Optional

An enumerated value that defines whether the separate structures inside the buffer represent vertices or instances. Possible values are:

* `"instance"`: Each structure is an instance — the address is advanced by `arrayStride` for each instance.
* `"vertex"`: Each structure is a vertex — the address is advanced by `arrayStride` for each vertex, and reset between instances.

If omitted, `stepMode` defaults to `"vertex"`.

### Return value

A `GPURenderPipeline` object instance.

### Validation

The following criteria must be met when calling **`createRenderPipeline()`**, otherwise a `GPUValidationError` is generated and an invalid `GPURenderPipeline` object is returned:

* For `depthStencil` objects:
    + `format` is a `depth-or-stencil` format.
    + If `depthWriteEnabled` is `true` or `depthCompare` is not `"always"`, `format` has a depth component.
    + If `stencilFront` or `stencilBack`'s properties are not at their default values, `format` has a stencil component.
* For `fragment` objects:
    + `targets.length` is less than or equal to the `GPUDevice`'s `maxColorAttachments` limit.
    + For each `target`, `writeMask`'s numeric equivalent is less than 16.
    + If any of the used blend factor operations use the source alpha channel (for example `"src-alpha-saturated"`), the output has an alpha channel (that is, it must be a `vec4`).
Examples
--------

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

### Basic example

Our basic render demo provides a simple example of the construction of a valid render pipeline descriptor object, which is then used to create a `GPURenderPipeline` via a `createRenderPipeline()` call.

```js
// ...

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

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",
};

const renderPipeline = device.createRenderPipeline(pipelineDescriptor);

// ...
```

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

| Specification |
| --- |
| WebGPU # dom-gpudevice-createrenderpipeline |

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

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

See also
--------

* The WebGPU API


GPUDevice: createSampler() method - Web APIs

GPUDevice: createSampler() method
=================================

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

 The **`createSampler()`** method of the
 `GPUDevice` interface creates a `GPUSampler`, which controls how shaders transform and filter texture resource data.

Syntax
------

```js
createSampler()
createSampler(descriptor)
```

### Parameters

`descriptor` Optional

An object containing the following properties:

`addressModeU` Optional

An enumerated value specifying the behavior of the sampler when the sample footprint width extends beyond the width of the texture. Possible values are:

* `"clamp-to-edge"`: The texture coordinates are clamped between 0.0 and 1.0, inclusive.
* `"repeat"`: The texture coordinates wrap to the other side of the texture.
* `"mirror-repeat"`: The texture coordinates wrap to the other side of the texture, but the texture is flipped when the integer part of the coordinate is odd.

If omitted, `addressModeU` defaults to `"clamp-to-edge"`.

`addressModeV` Optional

An enumerated value specifying the behavior of the sampler when the sample footprint height extends beyond the height of the texture. Possible and default values are the same as for `addressModeU`.

`addressModeW` Optional

An enumerated value specifying the behavior of the sampler when the sample footprint depth extends beyond the depth of the texture. Possible and default values are the same as for `addressModeU`.

`compare` Optional

If specified, the sampler will be a comparison sampler of the specified type. Possible (enumerated) values are:

* `"never"`: Comparison tests never pass.
* `"less"`: A provided value passes the comparison test if it is less than the sampled value.
* `"equal"`: A provided value passes the comparison test if it is equal to the sampled value.
* `"less-equal"`: A provided value passes the comparison test if it is less than or equal to the sampled value.
* `"greater"`: A provided value passes the comparison test if it is greater than the sampled value.
* `"not-equal"`: A provided value passes the comparison test if it is not equal to the sampled value.
* `"greater-equal"`: A provided value passes the comparison test if it is greater than or equal to the sampled value.
* `"always"`: Comparison tests always pass.

Comparison samplers may use filtering, but the sampling results will be implementation-dependent and may differ from the normal filtering rules.

`label` Optional

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

`lodMinClamp` Optional

A number specifying the minimum level of detail used internally when sampling a texture. If omitted, `lodMinClamp` defaults to 0.

`lodMaxClamp` Optional

A number specifying the maximum level of detail used internally when sampling a texture. If omitted, `lodMaxClamp` defaults to 32.

`maxAnisotropy` Optional

Specifies the maximum anisotropy value clamp used by the sampler. If omitted, `maxAnisotropy` defaults to 1.

Most implementations support `maxAnisotropy` values in a range between 1 and 16, inclusive. The value used will be clamped to the maximum value that the underlying platform supports.

`magFilter` Optional

An enumerated value specifying the sampling behavior when the sample footprint is smaller than or equal to one texel. Possible values are:

* `"nearest"`: Return the value of the texel nearest to the texture coordinates.
* `"linear"`: Select two texels in each dimension and return a linear interpolation between their values.

If omitted, `magFilter` defaults to `"nearest"`.

`minFilter` Optional

An enumerated value specifying the sampling behavior when the sample footprint is larger than one texel. Possible and default values are the same as for `magFilter`.

`mipmapFilter` Optional

An enumerated value specifying the behavior when sampling between mipmap levels. Possible and default values are the same as for `magFilter`.

### Return value

A `GPUSampler` object instance.

### Validation

The following criteria must be met when calling **`createSampler()`**, otherwise a `GPUValidationError` is generated and an invalid `GPUSampler` object is returned:

* `lodMinClamp` is equal to or more than 0.
* `lodMaxClamp` is equal to or more than `lodMinClamp`.
* `maxAnisotropy` is equal to or more than 1.
* If `maxAnisotropy` is more than 1, `magFilter`, `minFilter`, and `mipmapFilter` are `"linear"`.
Examples
--------

The following snippet creates a `GPUSampler` that does trilinear filtering and repeats texture coordinates:

```js
// ...

const sampler = device.createSampler({
  addressModeU: "repeat",
  addressModeV: "repeat",
  magFilter: "linear",
  minFilter: "linear",
  mipmapFilter: "linear",
});
```

The WebGPU samples Shadow Mapping sample uses comparison samplers to sample from a depth texture to render shadows.

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

| Specification |
| --- |
| WebGPU # dom-gpudevice-createsampler |

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

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

See also
--------

* The WebGPU API


XRInputSourcesChangeEvent: session property - Web APIs

XRInputSourcesChangeEvent: session property
===========================================

 The `XRInputSourcesChangeEvent` property
 `session` specifies the
 `XRSession` to which the input source list change event applies.

Value
-----

 An `XRSession` indicating the WebXR session to which the input source list
 change applies.

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

| Specification |
| --- |
| WebXR Device API # dom-xrinputsourceschangeevent-session |

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

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


XRInputSourcesChangeEvent: added property - Web APIs

XRInputSourcesChangeEvent: added property
=========================================

 The read-only `XRInputSourcesChangeEvent`
 property `added` is a list of zero or
 more input sources, each identified using an `XRInputSource` object,
 which have been newly made available for use.

Value
-----

 An `Array` of zero or more `XRInputSource` objects, each
 representing one input device added to the XR system.

Examples
--------

 The example below creates a handler for the
 `inputsourceschange` event that
 processes the lists of added and removed from the WebXR system. It looks for new and
 removed devices whose `targetRayMode` is
 `tracked-pointer`.

```js
xrSession.oninputsourcescchange = (event) => {
  for (const input of event.added) {
    if (input.targetRayMode === "tracked-pointer") {
      addedPointerDevice(input);
    }
  }
  for (const input of event.removed) {
    if (input.targetRayMode === "tracked-pointer") {
      removedPointerDevice(input);
    }
  }
};
```

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

| Specification |
| --- |
| WebXR Device API # dom-xrinputsourceschangeevent-added |

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

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


XRInputSourcesChangeEvent: removed property - Web APIs

XRInputSourcesChangeEvent: removed property
===========================================

 The read-only `XRInputSourcesChangeEvent` property `removed` is an array of
 zero or more `XRInputSource` objects representing the input sources that have been removed from the `XRSession`.

Value
-----

An `Array` of zero or more `XRInputSource` objects, each representing one input device removed from the XR system.

Examples
--------

See `XRInputSourcesChangeEvent.added` for example code.

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

| Specification |
| --- |
| WebXR Device API # dom-xrinputsourceschangeevent-removed |

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

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


XRInputSourcesChangeEvent: XRInputSourcesChangeEvent() constructor - Web APIs

XRInputSourcesChangeEvent: XRInputSourcesChangeEvent() constructor
==================================================================

 The **`XRInputSourcesChangeEvent()`**
 constructor creates and returns a new `XRInputSourcesChangeEvent` object,
 representing an update to the list of available WebXR input devices. You
 won't typically call this constructor yourself, as these events are created and sent to
 you by the WebXR system.

Syntax
------

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

### Parameters

`type`

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

`options`

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

`added`

An array of zero or more `XRInputSource` objects, each representing one input device which is newly available to use.

`removed`

An array of zero or more `XRInputSource` objects representing the input devices which are no longer available.

`session`

The `XRSession` to which the event applies.

### Return value

 A new `XRInputSourcesChangeEvent` object configured based upon
 the input parameters provided.

Examples
--------

 The following snippet of code creates a new `XRInputSourcesChangeEvent`
 object indicating that a single new input source, described by an
 `XRInputSource` object named `newInputSource`, has been added to
 the system.

```js
let iscEvent = new XRInputSourcesChangeEvent("inputsourceschange", {
  session: xrSession,
  added: [newInputSource],
  removed: [],
});
```

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

| Specification |
| --- |
| WebXR Device API # dom-xrinputsourceschangeevent-xrinputsourceschangeevent |

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

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


RTCIceCandidateStats: candidateType property - Web APIs

RTCIceCandidateStats: candidateType property
============================================

 The `RTCIceCandidateStats` interface's
 **`candidateType`** property is a string that indicates the
 type of ICE candidate the object represents.

Syntax
------

```js
rtcIceCandidateStats.candidateType
```

### Value

A string whose value is one of the strings found in `RTCIceCandidate.type`.

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

| Specification |
| --- |
| Identifiers for WebRTC's Statistics API # dom-rtcicecandidatestats-candidatetype |

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

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


RTCIceCandidateStats: address property - Web APIs

RTCIceCandidateStats: address property
======================================

 The **`address`** property of the
 `RTCIceCandidateStats` dictionary indicates the address of the
 ICE candidate. While it's preferred that the address be specified as
 an IPv4 or IPv6 numeric address, a fully-qualified domain name can be used as
 well.

 When a domain name is specified, the first IP address selected for that
 address is used, even if the domain name maps to multiple IP addresses.

Value
-----

 Either an IPv4 or IPv6 address or a fully-qualified domain name, which corresponds to
 the candidate.

* If the value of `address` is comprised entirely of digits from 0-9 with
 periods as separators, the value is interpreted as an IPv4 address.
* If the value is entirely comprised of hexadecimal digits and colon (":")
 characters, it is interpreted as an IPv6 address.
* Otherwise, the `address` is presumed to be a fully-qualified domain name,
 which is resolved first using an AAAA record (assuming IPv6 is available), then using
 an A record (if no result is found or the device only supports IPv4). If multiple IP
 addresses are returned in response to the query, the user agent
 selects one, which is then used for the duration of ICE processing.
Usage notes
-----------

 The `address` property was previously known as `ip`, and only
 permitted IPv4 and IPv6 addresses to be used. The addition of support for
 fully-qualified domain names to be used for the address brought about the renaming of
 the property.

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

| Specification |
| --- |
| Identifiers for WebRTC's Statistics API # dom-rtcicecandidatestats-address |

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

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


RTCIceCandidateStats: deleted property - Web APIs

RTCIceCandidateStats: deleted property
======================================

 The `RTCIceCandidateStats` dictionary's
 **`deleted`** property indicates whether or not the candidate
 has been deleted or released.

Value
-----

 A Boolean value indicating whether or not the candidate has been deleted or released.
 If this value is `true`, the candidate described by the
 `RTCIceCandidateStats` object is no longer under consideration. The exact
 meaning varies depending on the type of candidate:

`Local candidate`

 A value of `true` means the candidate has been deleted as described by
 RFC 5245, section 8.3.

`Host candidate`

 A value of `true` indicates that the candidate's network resources have
 been released. This generally mean that any associated socket(s) have been closed and
 released.

`Remote (TURN) candidate`

 A value of `true` means the candidate's TURN allocation
 is no longer active.

 The net result is the same; the candidate is no longer under consideration if this
 value is `true`.

Examples
--------

 In this example, `setInterval()`
 is used to set up a function that runs periodically to display the latest statistics for
 candidates. Only candidates which have not been deleted are included in the output.

```js
setInterval(() => {
  myPeerConnection.getStats(null).then((stats) => {
    let statsOutput = "";

    stats.forEach((report) => {
      if (
        (stats.type === "local-candidate" ||
          stats.type === "remote.candidate") &&
        !stats.deleted
      ) {
        statsOutput +=
          `<h2>Report: ${report.type}</h3>\n<strong>ID:</strong> ${report.id}<br>\n` +
          `<strong>Timestamp:</strong> ${report.timestamp}<br>\n`;

        // Now the statistics for this report; we intentionally drop the ones we
        // sorted to the top above
        Object.keys(report).forEach((statName) => {
          if (
            statName !== "id" &&
            statName !== "timestamp" &&
            statName !== "type"
          ) {
            statsOutput += `<strong>${statName}:</strong> ${report[statName]}<br>\n`;
          }
        });
      }
    });

    document.querySelector(".stats-box").innerHTML = statsOutput;
  });
}, 1000);
```

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

#### No specification found

No specification data found for `api.RTCIceCandidateStats.deleted`.
Check for problems with this page or contribute a missing `spec_url` to mdn/browser-compat-data. Also make sure the specification is included in w3c/browser-specs.

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

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


RTCIceCandidateStats: type property - Web APIs

RTCIceCandidateStats: type property
===================================

The **`type`** property of the `RTCIceCandidateStats` dictionary is a string with the value `"local-candidate"`.

 Different statistics are obtained by iterating the `RTCStatsReport` object returned by a call to `RTCPeerConnection.getStats()`.
 The type indicates the set of statistics available through the object in a particular iteration step.
 A value of `"local-candidate"` indicates that the statistics available in the current step are those defined in `RTCIceCandidateStats`.

Value
-----

A string with the value `"local-candidate"`.

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

| Specification |
| --- |
| Identifiers for WebRTC's Statistics API # dom-rtcstats-type |

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

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


RTCIceCandidateStats: url property - Web APIs

RTCIceCandidateStats: url property
==================================

 The `RTCIceCandidateStats` dictionary's
 **`url`** property specifies the URL of the
 ICE server from which the described candidate was obtained. This
 property is *only* available for local candidates.

Value
-----

 A string specifying the URL of the ICE server from which the
 candidate described by the `RTCIceCandidateStats` was obtained. This is the
 same URL that would be received in the `icecandidate` event's
 `url` property.

**Note:** This property does not exist for remote candidates.

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

#### No specification found

No specification data found for `api.RTCIceCandidateStats.url`.
Check for problems with this page or contribute a missing `spec_url` to mdn/browser-compat-data. Also make sure the specification is included in w3c/browser-specs.

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

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


RTCIceCandidateStats: id property - Web APIs

RTCIceCandidateStats: id property
=================================

The **`id`** property of the `RTCIceCandidateStats` dictionary is a string that uniquely identifies the object for which this object provides statistics.

Using the `id`, you can correlate this statistics object with others, in order to monitor statistics over time for a given WebRTC object, such as an `RTCPeerConnection`, or an `RTCDataChannel`.

Value
-----

A string that uniquely identifies the object for which this `RTCIceCandidateStats` object provides statistics.

The format of the ID string is not defined by the specification, so you cannot reliably make any assumptions about the contents of the string, or assume that the format of the string will remain unchanged for a given object type.

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

| Specification |
| --- |
| Identifiers for WebRTC's Statistics API # dom-rtcstats-id |

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

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


RTCIceCandidateStats: protocol property - Web APIs

RTCIceCandidateStats: protocol property
=======================================

 The `RTCIceCandidateStats` dictionary's
 **`protocol`** property specifies the protocol the specified
 candidate would use for communication with the remote peer.

Value
-----

The value is one of the following string:

`tcp`

The candidate, if selected, would use TCP as the transport protocol for its data. The `tcpType` property provides additional information about the kind of TCP candidate represented by the object.

`udp`

The candidate will use the UDP transport protocol for its data. This is the preferred protocol for media interactions because of its better performance profile.

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

#### No specification found

No specification data found for `api.RTCIceCandidateStats.protocol`.
Check for problems with this page or contribute a missing `spec_url` to mdn/browser-compat-data. Also make sure the specification is included in w3c/browser-specs.

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

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


RTCIceCandidateStats: priority property - Web APIs

RTCIceCandidateStats: priority property
=======================================

 The `RTCIceCandidateStats` dictionary's
 **`priority`** property is a positive integer value
 indicating the priority (or desirability) of the described candidate.

 During ICE negotiation while setting up a WebRTC peer connection, the
 priority values reported to the remote peer by a user agent are used
 to determine which candidates are considered "more desirable". The higher the value,
 the more desirable the candidate is.

Syntax
------

```js
priority = rtcIceCandidateStats.priority
```

### Value

 A positive integer indicating the priority of the `RTCIceCandidate`
 described by the `RTCIceCandidateStats` object. The value may be anywhere
 from 1 to 2,147,483,647.

Determining priority
--------------------

 The ICE specification describes how user agents and other software using WebRTC should
 calculate the priority. The priority of a candidate is calculated using the following
 variables as inputs:

* The preferability of the candidate type (local, server reflexive, peer reflexive,
 or relayed)
* The preferability of the candidate's specific IP address (for multihomed agents)
* The candidate's component ID (1 for RTP, 2 for RTCP)

 The candidate's priority is computed using the formula (*ptype* is
 the priority of the candidate's type and *plocal* is the priority of
 the IP address):

priority
=

2
24

×

p

type

+

2
8

×

p

local

+
(
256
-
componentID
)

priority\quad =\quad { 2 }^{ 24 }\times { p }

*{
type }\quad +\quad { 2 }^{ 8 }\times { p }*{ local }\quad +\quad (256\quad
 -\quad componentID)

 This is equivalent to mapping the priorities of the candidate type, the local IP, and
 the component ID into various bit ranges within the 32-bit `priority`
 value.

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

| Specification |
| --- |
| Identifiers for WebRTC's Statistics API # dom-rtcicecandidatestats-priority |

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

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

See also
--------

* RFC 5245, section 4.1.2.1: Recommended Formula section in the ICE specification


RTCIceCandidateStats: relayProtocol property - Web APIs

RTCIceCandidateStats: relayProtocol property
============================================

 The `RTCIceCandidateStats` dictionary's
 **`relayProtocol`** property specifies the protocol being used
 by a local ICE candidate to communicate with the TURN
 server.

 The ICE protocol being used by the candidate otherwise can be obtained from the
 `protocol` property.

Value
-----

 A string identifying the protocol being used by the endpoint to
 communicate with the TURN server. The possible values are:

`tcp`

TCP (Transport Control Protocol) is being used to communicate with the TURN server.

`tls`

TLS (Transport Layer Security) is being used to communicate with the TURN server.

`udp`

UDP (User Datagram Protocol) is being used to communicate with the TURN server.

**Note:** This property is only present on
 `RTCIceCandidateStats` objects that represent local candidates.

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

#### No specification found

No specification data found for `api.RTCIceCandidateStats.relayProtocol`.
Check for problems with this page or contribute a missing `spec_url` to mdn/browser-compat-data. Also make sure the specification is included in w3c/browser-specs.

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

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


RTCIceCandidateStats: transportId property - Web APIs

RTCIceCandidateStats: transportId property
==========================================

 The `RTCIceCandidateStats` dictionary's
 **`transportId`** property is a string that uniquely
 identifies the transport that produced the `RTCTransportStats` from which
 information about this candidate was taken.

Value
-----

 A string whose value uniquely identifies the transport from which any
 transport-related information accumulated in the `RTCIceCandidateStats` was
 taken. This can be used to compare candidates that would use the same transport, for
 example.

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

| Specification |
| --- |
| Identifiers for WebRTC's Statistics API # dom-rtcicecandidatestats-transportid |

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

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


RTCIceCandidateStats: port property - Web APIs

RTCIceCandidateStats: port property
===================================

 The `RTCIceCandidateStats` dictionary's **`port`**
 property specifies the network port used by the candidate.

Value
-----

 An integer value indicating the network port used by the `RTCIceCandidate`
 described by the `RTCIceCandidateStats` object.

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

| Specification |
| --- |
| Identifiers for WebRTC's Statistics API # dom-rtcicecandidatestats-port |

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

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


RTCIceCandidateStats: timestamp property - Web APIs

RTCIceCandidateStats: timestamp property
========================================

The **`timestamp`** property of the `RTCIceCandidateStats` dictionary is a `DOMHighResTimeStamp` object specifying the time at which the data in the object was sampled.

Value
-----

A `DOMHighResTimeStamp` value indicating the time at which the activity described by the statistics in this object was recorded, in milliseconds elapsed since the beginning of January 1, 1970, UTC.

The value should be accurate to within a few milliseconds but may not be entirely precise, either because of hardware or operating system limitations or because of fingerprinting protection in the form of reduced clock precision or accuracy.

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

| Specification |
| --- |
| Identifiers for WebRTC's Statistics API # dom-rtcstats-timestamp |

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

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


SyncManager: getTags() method - Web APIs

SyncManager: getTags() method
=============================

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

 The **`getTags()`** method of the
 `SyncManager` interface returns a list of developer-defined identifiers for
 `SyncManager` registrations.

Syntax
------

```js
getTags()
```

### Parameters

None.

### Return value

 A `Promise` that resolves to an array of strings
 containing developer-defined identifiers for `SyncManager` registrations.

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

| Specification |
| --- |
| Web Background Synchronization # dom-syncmanager-gettags |

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

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


SyncManager: register() method - Web APIs

SyncManager: register() method
==============================

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

The **`register()`** method of the `SyncManager` interface registers a synchronization event, triggering a `sync` event inside the associated service worker as soon as network connectivity is available.

Syntax
------

```js
register(tag)
```

### Parameters

`tag`

An identifier for this synchronization event. This will be the value of the `tag` property of the `SyncEvent` that gets passed into the service worker's `sync` event handler.

### Return value

A `Promise` that resolves to `undefined`.

### Exceptions

`InvalidStateError` `DOMException`

Thrown if current service worker is not active.

`NotAllowedError` `DOMException`

Thrown if background sync has been disabled by the user.

Examples
--------

The following asynchronous function registers a background sync from a browsing context:

```js
async function syncMessagesLater() {
  const registration = await navigator.serviceWorker.ready;
  try {
    await registration.sync.register("sync-messages");
  } catch {
    console.log("Background Sync could not be registered!");
  }
}
```

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

| Specification |
| --- |
| Web Background Synchronization # dom-syncmanager-register |

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

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


ResizeObserverEntry: devicePixelContentBoxSize property - Web APIs

ResizeObserverEntry: devicePixelContentBoxSize property
=======================================================

 The **`devicePixelContentBoxSize`** read-only property of
 the `ResizeObserverEntry` interface returns an array containing the size in device pixels of the observed element when the callback is run.

Value
-----

 An array containing objects with the new size of the observed element in device pixels. The
 array is necessary to support elements that have multiple fragments, which occur in
 multi-column scenarios. Each object in the array contains two properties:

`blockSize`

 The size of the content-box, in device pixels, of the block dimension of the observed element. For boxes
 with a horizontal `writing-mode`, this is the vertical dimension, or
 height; if the writing-mode is vertical, this is the horizontal dimension, or width.

`inlineSize`

 The size of the content box, in device pixels, of the inline direction of the observed element. For boxes
 with a horizontal `writing-mode`, this is the horizontal dimension, or
 width; if the writing-mode is vertical, this is the vertical dimension, or height.

**Note:** For more information about writing modes and block and inline
 dimensions, read Handling different text directions.

Examples
--------

 The following example is taken from the article Pixel-perfect rendering with devicePixelContentBox. As the callback function of a `ResizeObserver`
 is called after layout but before paint.
 This provides an opportunity to log the exact size in physical pixels to
 ensure a one-to-one mapping of canvas pixels to physical pixels.

```js
const observer = new ResizeObserver((entries) => {
  const entry = entries.find((entry) => entry.target === canvas);
  canvas.width = entry.devicePixelContentBoxSize[0].inlineSize;
  canvas.height = entry.devicePixelContentBoxSize[0].blockSize;

  /\* … render to canvas … \*/
});
observer.observe(canvas, { box: "device-pixel-content-box" });
```

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

| Specification |
| --- |
| Resize Observer # dom-resizeobserverentry-devicepixelcontentboxsize |

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

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


ResizeObserverEntry: contentBoxSize property - Web APIs

ResizeObserverEntry: contentBoxSize property
============================================

 The **`contentBoxSize`** read-only property of
 the `ResizeObserverEntry` interface returns an array containing the new
 content box size of the observed element when the callback is run.

Value
-----

 An array containing objects with the new content box size of the observed element.
 The array is necessary to support elements that have multiple fragments, which occur in multi-column scenarios. Each object in the array contains two properties:

`blockSize`

 The length of the observed element's content box in the block dimension. For boxes
 with a horizontal `writing-mode`, this is the vertical dimension, or
 height; if the writing-mode is vertical, this is the horizontal dimension, or width.

`inlineSize`

 The length of the observed element's content box in the inline dimension. For boxes
 with a horizontal `writing-mode`, this is the horizontal dimension, or
 width; if the writing-mode is vertical, this is the vertical dimension, or height.

**Note:** For more explanation of writing modes and block and inline
 dimensions, read Handling different text directions.

Examples
--------

 The following snippet is taken from the resize-observer-border-radius.html
 (see source) example. This example includes a green box, sized as a percentage of the
 viewport size. When the viewport size is changed, the box's rounded corners change in
 proportion to the size of the box. We could just implement this using
 `border-radius` with a percentage, but that quickly leads to ugly-looking
 elliptical corners; this solution gives you nice square corners that scale with the box
 size.

```js
const resizeObserver = new ResizeObserver((entries) => {
  for (let entry of entries) {
    if (entry.contentBoxSize) {
      // The standard makes contentBoxSize an array...
      if (entry.contentBoxSize[0]) {
        entry.target.style.borderRadius =
          Math.min(
            100,
            entry.contentBoxSize[0].inlineSize / 10 +
              entry.contentBoxSize[0].blockSize / 10,
          ) + "px";
      } else {
        // ...but old versions of Firefox treat it as a single item
        entry.target.style.borderRadius =
          Math.min(
            100,
            entry.contentBoxSize.inlineSize / 10 +
              entry.contentBoxSize.blockSize / 10,
          ) + "px";
      }
    } else {
      entry.target.style.borderRadius =
        Math.min(
          100,
          entry.contentRect.width / 10 + entry.contentRect.height / 10,
        ) + "px";
    }
  }
});

resizeObserver.observe(document.querySelector("div"));
```

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

| Specification |
| --- |
| Resize Observer # dom-resizeobserverentry-contentboxsize |

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

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


ResizeObserverEntry: borderBoxSize property - Web APIs

ResizeObserverEntry: borderBoxSize property
===========================================

 The **`borderBoxSize`** read-only property of
 the `ResizeObserverEntry` interface returns an array containing the new
 border box size of the observed element when the callback is run.

Value
-----

 An array containing objects with the new border box size of the observed element. The
 array is necessary to support elements that have multiple fragments, which occur in
 multi-column scenarios. Each object in the array contains two properties:

`blockSize`

 The length of the observed element's border box in the block dimension. For boxes
 with a horizontal `writing-mode`, this is the vertical dimension, or
 height; if the writing-mode is vertical, this is the horizontal dimension, or width.

`inlineSize`

 The length of the observed element's border box in the inline dimension. For boxes
 with a horizontal `writing-mode`, this is the horizontal dimension, or
 width; if the writing-mode is vertical, this is the vertical dimension, or height.

**Note:** For more explanation of writing modes and block and inline
 dimensions, read Handling different text directions.

Examples
--------

```js
const resizeObserver = new ResizeObserver((entries) => {
  const calcBorderRadius = (size1, size2) =>
    `${Math.min(100, size1 / 10 + size2 / 10)}px`;

  for (const entry of entries) {
    if (entry.borderBoxSize?.length > 0) {
      entry.target.style.borderRadius = calcBorderRadius(
        entry.borderBoxSize[0].inlineSize,
        entry.borderBoxSize[0].blockSize,
      );
    } else {
      entry.target.style.borderRadius = calcBorderRadius(
        entry.contentRect.width,
        entry.contentRect.height,
      );
    }
  }
});

resizeObserver.observe(document.querySelector("div"));
```

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

| Specification |
| --- |
| Resize Observer # dom-resizeobserverentry-borderboxsize |

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

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


ResizeObserverEntry: target property - Web APIs

ResizeObserverEntry: target property
====================================

 The **`target`** read-only property of the
 `ResizeObserverEntry` interface returns a reference to the
 `Element` or `SVGElement` that is being observed.

Value
-----

 An `Element` or `SVGElement` representing the element being
 observed.

Examples
--------

 The following snippet is taken from the resize-observer-border-radius.html
 (see source) example. This example includes a green box, sized as a percentage of the
 viewport size. When the viewport size is changed, the box's rounded corners change in
 proportion to the size of the box. We could just implement this using
 `border-radius` with a percentage, but that quickly leads to ugly-looking
 elliptical corners; this solution gives you nice square corners that scale with the box
 size.

 To grab a reference to the observed element so we can update its
 `border-radius` value after each change, we make use of the
 `target` property of each entry —
 `entry.target.style.borderRadius`.

```js
const resizeObserver = new ResizeObserver((entries) => {
  for (const entry of entries) {
    if (entry.contentBoxSize) {
      entry.target.style.borderRadius = `${Math.min(
 100,
 entry.contentBoxSize.inlineSize / 10 +
 entry.contentBoxSize.blockSize / 10,
 )}px`;
    } else {
      entry.target.style.borderRadius = `${Math.min(
 100,
 entry.contentRect.width / 10 + entry.contentRect.height / 10,
 )}px`;
    }
  }
});

resizeObserver.observe(document.querySelector("div"));
```

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

| Specification |
| --- |
| Resize Observer # dom-resizeobserverentry-target |

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

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


ResizeObserverEntry: contentRect property - Web APIs

ResizeObserverEntry: contentRect property
=========================================

 The `contentRect` read-only property of the
 `ResizeObserverEntry` interface returns a `DOMRectReadOnly`
 object containing the new size of the observed element when the callback is run. Note
 that this is better supported than `ResizeObserverEntry.borderBoxSize` or
 `ResizeObserverEntry.contentBoxSize`, but it is left over from an earlier
 implementation of the Resize Observer API, is still included in the spec for web compat
 reasons, and may be deprecated in future versions.

Value
-----

 A `DOMRectReadOnly` object containing the new size of the element
 indicated by the `target` property.

 If the `target` is an HTML `Element`, the returned
 `contentRect` is the element's content box. If the `target` is an
 `SVGElement`, the returned `contentRect` is the SVG's bounding
 box.

Examples
--------

 The following snippet is taken from the resize-observer-text.html
 (see source) example. This uses a simple feature detection test to see if the browser
 supports the newer `ResizeObserverEntry.contentBoxSize` property — if so,
 it uses that to get the sizing data it needs. If not, it uses `contentRect`.

```js
const resizeObserver = new ResizeObserver((entries) => {
  for (const entry of entries) {
    if (entry.contentBoxSize) {
      h1Elem.style.fontSize = `${Math.max(
 1.5,
 entry.contentBoxSize.inlineSize / 200,
 )}rem`;
      pElem.style.fontSize = `${Math.max(
 1,
 entry.contentBoxSize.inlineSize / 600,
 )}rem`;
    } else {
      h1Elem.style.fontSize = `${Math.max(
 1.5,
 entry.contentRect.width / 200,
 )}rem`;
      pElem.style.fontSize = `${Math.max(1, entry.contentRect.width / 600)}rem`;
    }
  }
});

resizeObserver.observe(divElem);
```

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

| Specification |
| --- |
| Resize Observer # dom-resizeobserverentry-contentrect |

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

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


AudioScheduledSourceNode: start() method - Web APIs

AudioScheduledSourceNode: start() method
========================================

 The `start()` method on
 `AudioScheduledSourceNode` schedules a sound to begin playback at the
 specified time. If no time is specified, then the sound begins playing
 immediately.

Syntax
------

```js
start()
start(when)
```

### Parameters

`when` Optional

 The time, in seconds, at which the sound should begin to play. This value is
 specified in the same time coordinate system as the `AudioContext` is
 using for its `currentTime` attribute. A
 value of 0 (or omitting the `when` parameter entirely) causes the sound to
 start playback immediately.

### Return value

None (`undefined`).

### Exceptions

`InvalidStateNode` `DOMException`

 Thrown if the node has already been started. This error occurs even if the node is no longer
 running because of a prior call to `stop()`.

`RangeError`

Thrown if the value specified for `when` is negative.

Examples
--------

 This example demonstrates how to create an `OscillatorNode` which is
 scheduled to start playing in 2 seconds and stop playing 1 second after that. The times
 are calculated by adding the desired number of seconds to the context's current time
 stamp returned by `AudioContext.currentTime`.

```js
context = new AudioContext();
osc = context.createOscillator();
osc.connect(context.destination);

/\* Schedule the start and stop times for the oscillator \*/

osc.start(context.currentTime + 2);
osc.stop(context.currentTime + 3);
```

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

| Specification |
| --- |
| Web Audio API # dom-audioscheduledsourcenode-start |

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

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

See also
--------

* Using the Web Audio API
* `stop()`
* `AudioScheduledSourceNode`
* `AudioBufferSourceNode`
* `ConstantSourceNode`
* `OscillatorNode`


AudioScheduledSourceNode: stop() method - Web APIs

AudioScheduledSourceNode: stop() method
=======================================

 The `stop()` method on `AudioScheduledSourceNode` schedules a
 sound to cease playback at the specified time. If no time is specified, then the sound
 stops playing immediately.

 Each time you call `stop()` on the same node, the specified time replaces
 any previously-scheduled stop time that hasn't occurred yet. If the node has already
 stopped, this method has no effect.

**Note:** If a scheduled stop time occurs before the node's scheduled
 start time, the node never starts to play.

Syntax
------

```js
stop()
stop(when)
```

### Parameters

`when` Optional

 The time, in seconds, at which the sound should stop playing. This value is
 specified in the same time coordinate system as the `AudioContext` is
 using for its `currentTime` attribute.
 Omitting this parameter, specifying a value of 0, or passing a negative value causes
 the sound to stop playback immediately.

### Return value

None (`undefined`).

### Exceptions

`InvalidStateNode` `DOMException`

Thrown if the node has not been started by calling `start()`.

`RangeError`

Thrown if the value specified for `when` is negative.

Examples
--------

 This example demonstrates starting an oscillator node, scheduled to begin playing at
 once and to stop playing in one second. The stop time is determined by taking the audio
 context's current time from `AudioContext.currentTime` and adding 1 second.

```js
context = new AudioContext();
osc = context.createOscillator();
osc.connect(context.destination);

/\* Let's play a sine wave for one second. \*/

osc.start();
osc.stop(context.currentTime + 1);
```

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

| Specification |
| --- |
| Web Audio API # dom-audioscheduledsourcenode-stop |

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

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

See also
--------

* Using the Web Audio API
* `start()`
* `AudioScheduledSourceNode`
* `AudioBufferSourceNode`
* `ConstantSourceNode`
* `OscillatorNode`


AudioScheduledSourceNode: ended event - Web APIs

AudioScheduledSourceNode: ended event
=====================================

The `ended` event of the `AudioScheduledSourceNode` interface is fired when the source node has stopped playing.

This event occurs when a `AudioScheduledSourceNode` has stopped playing, either because it's reached a predetermined stop time, the full duration of the audio has been performed, or because the entire buffer has been played.

This event is not cancelable and does not bubble.

Syntax
------

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

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

onended = (event) => { }
```

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

A generic `Event`.

Examples
--------

In this simple example, an event listener for the `ended` event is set up to enable a "Start" button in the user interface when the node stops playing:

```js
node.addEventListener("ended", () => {
  document.getElementById("startButton").disabled = false;
});
```

You can also set up the event handler using the `onended` property:

```js
node.onended = () => {
  document.getElementById("startButton").disabled = false;
};
```

For an example of the ended event in use, see our audio-buffer example on GitHub.

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

| Specification |
| --- |
| Web Audio API # dom-audioscheduledsourcenode-onended |

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

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

Related events
--------------

* audioprocess
* complete
See also
--------

* `HTMLAudioElement`
* `HTMLVideoElement`
* `<audio>`
* `<video>`
* The HTMLMediaElement `ended` event
* The MediaStreamTrack `ended` event


CSSFontFeatureValuesRule: fontFamily property - Web APIs

CSSFontFeatureValuesRule: fontFamily property
=============================================

The **`fontFamily`** property of the `CSSConditionRule` interface represents the name of the font family it applies to.

Value
-----

A string.

Examples
--------

### Read font family

In this example, we declare two `@font-feature-values` one for the *Font One* font family, and the other for *Font Two*. We then use the CSSOM to read these font families, displaying them into the log.

```html
<pre id="log"></pre>
```

#### CSS

```css
/\* At-rule for "nice-style" in Font One \*/
@font-feature-values Font One {
  @styleset {
    nice-style: 12;
  }
}

/\* At-rule for "nice-style" in Font Two \*/
@font-feature-values Font Two {
  @styleset {
    nice-style: 4;
  }
}

/\* Apply the at-rules with a single declaration \*/
.nice-look {
  font-variant-alternates: styleset(nice-style);
}
```

#### JavaScript

```js
const log = document.getElementById("log");
const rules = document.styleSheets[document.styleSheets.length - 1].cssRules;

const fontOne = rules[0]; // A CSSFontFeatureValuesRule
log.textContent = `The 1st '@font-feature-values' family: "${fontOne.fontFamily}".\n`;

const fontTwo = rules[1]; // Another CSSFontFeatureValuesRule
log.textContent += `The 2nd '@font-feature-values' family: "${fontTwo.fontFamily}".`;
```

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

| Specification |
| --- |
| CSS Fonts Module Level 4 # dom-cssfontfeaturevaluesrule-fontfamily |

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

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

See also
--------

*


BarcodeDetector: getSupportedFormats() static method - Web APIs

BarcodeDetector: getSupportedFormats() static method
====================================================

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

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

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

 The **`getSupportedFormats()`** static method
 of the `BarcodeDetector` interface returns a `Promise` which
 fulfills with an `Array` of supported barcode format types.

Syntax
------

```js
BarcodeDetector.getSupportedFormats()
```

### Parameters

This method receives no parameters.

### Return value

 A `Promise` which fulfills with an `Array` of
 supported barcode format types.

### Exceptions

No exceptions are thrown.

Examples
--------

 The following example calls the `getSupportFormat()` static method and logs
 the results to the console.

```js
// check supported types
BarcodeDetector.getSupportedFormats().then((supportedFormats) => {
  supportedFormats.forEach((format) => console.log(format));
});
```

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

| Specification |
| --- |
| Accelerated Shape Detection in Images # dom-barcodedetector-getsupportedformats |

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

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


BarcodeDetector: BarcodeDetector() constructor - Web APIs

BarcodeDetector: BarcodeDetector() constructor
==============================================

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

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

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

 The **`BarcodeDetector()`** constructor creates
 a new `BarcodeDetector` object which detects linear and two-dimensional
 barcodes in images.

Syntax
------

```js
new BarcodeDetector()
new BarcodeDetector(options)
```

### Parameters

`options` Optional

 An options object containing a series of `BarcodeFormats` to search for
 in the subsequent `detect()` calls. The
 options are:

`formats` Optional

 An `Array` of barcode formats as strings.
 If not provided, `detect()` calls search for all supported formats.
 Limiting to specific formats is therefore recommended for performance reasons.
 To see a full list of supported formats see the supported barcode format.

### Exceptions

`TypeError`

Thrown if the `formats` is specified and the parameter is empty or contains `unknown`.

Examples
--------

 This example creates a new barcode detector object, with specified supported formats
 and tests for browser compatibility.

```js
// check compatibility
if (!("BarcodeDetector" in globalThis)) {
  console.log("Barcode Detector is not supported by this browser.");
} else {
  console.log("Barcode Detector supported!");

  // create new detector
  const barcodeDetector = new BarcodeDetector({
    formats: ["code\_39", "codabar", "ean\_13"],
  });
}
```

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

| Specification |
| --- |
| Accelerated Shape Detection in Images # dom-barcodedetector-barcodedetector |

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

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


BarcodeDetector: detect() method - Web APIs

BarcodeDetector: detect() method
================================

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

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

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

 The **`detect()`** method of the
 `BarcodeDetector` interface returns a `Promise` which fulfills
 with an `Array` of detected barcodes within an image.

Syntax
------

```js
detect(imageBitmapSource)
```

### Parameters

`imageBitmapSource`

Receives an image source as a parameter. This can be a `HTMLImageElement`, a `SVGImageElement`, a `HTMLVideoElement`, a `HTMLCanvasElement`, an `ImageBitmap`, an `OffscreenCanvas`, a `VideoFrame`, a `Blob` of type image or an `ImageData` object.

### Return value

 Returns a `Promise` which fulfills with an array of
 `DetectedBarcode` objects with the following properties:

`boundingBox`

 A `DOMRectReadOnly`, which returns the
 dimensions of a rectangle representing the extent of a detected barcode, aligned with
 the image.

`cornerPoints`

 The x and y co-ordinates of the four corner points of the
 detected barcode relative to the image, starting with the top left and working
 clockwise. This may not be square due to perspective distortions within the image.

`format`

 The detected barcode format. (For a full list of formats see
 the supported barcode format).

`rawValue`

A string decoded from the barcode data.

### Exceptions

`TypeError`

Thrown if no parameter is specified or the `type` is not that of an `ImageBitmapSource`.

`SecurityError` `DOMException`

Thrown if the `imageBitmapSource` has an origin and is not the same as the document's origin, or if the `imageBitmapSource` is a `HTMLCanvasElement` and its origin-clean flag is set to `false`.

`InvalidStateError` `DOMException`

Thrown if the `imageBitmapSource` is an `HTMLImageElement` and is not fully decoded or decoding failed, or is an `HTMLVideoElement` and its `readyState` is `HAVE_NOTHING` or `HAVE_METADATA`.

Examples
--------

 This example uses the `detect()` method to detect the barcodes within the
 given image. These are iterated over and the barcode data is logged to the console.

```js
barcodeDetector
  .detect(imageEl)
  .then((barcodes) => {
    barcodes.forEach((barcode) => console.log(barcode.rawValue));
  })
  .catch((err) => {
    console.error(err);
  });
```

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

| Specification |
| --- |
| Accelerated Shape Detection in Images # dom-barcodedetector-detect |

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

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


HashChangeEvent: newURL property - Web APIs

HashChangeEvent: newURL property
================================

 The **`newURL`** read-only property of the
 `HashChangeEvent` interface returns the new URL to which the window is
 navigating.

Value
-----

A string.

Examples
--------

```js
window.addEventListener("hashchange", (event) => {
  console.log(`Hash changed to ${event.newURL}`);
});
```

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

| Specification |
| --- |
| HTML Standard # dom-hashchangeevent-newurl-dev |

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

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


HashChangeEvent: oldURL property - Web APIs

HashChangeEvent: oldURL property
================================

 The **`oldURL`** read-only property of the
 `HashChangeEvent` interface returns the previous URL from which the window
 was navigated.

Value
-----

A string.

Examples
--------

```js
window.addEventListener("hashchange", (event) => {
  console.log(`Hash changed from ${event.oldURL}`);
});
```

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

| Specification |
| --- |
| HTML Standard # dom-hashchangeevent-oldurl-dev |

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

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


HashChangeEvent: HashChangeEvent() constructor - Web APIs

HashChangeEvent: HashChangeEvent() constructor
==============================================

The **`HashChangeEvent()`** constructor creates a new `HashChangeEvent` object, that is used by the `hashchange` event fired at the `window` object when the fragment of the URL changes.

**Note:** A web developer doesn't typically need to call this constructor, as the browser creates these objects itself when firing `hashchange` events.

Syntax
------

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

### Parameters

`type`

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

`options` Optional

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

`oldURL` Optional

A string containing the old URL. Its default value is the empty string (`""`).

`newURL`Optional

A string containing the new URL. Its default value is the empty string (`""`).

### Return value

A new `HashChangeEvent` object.

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

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

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

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

See also
--------

* `hashchange` event


XRWebGLLayer: getNativeFramebufferScaleFactor() static method - Web APIs

XRWebGLLayer: getNativeFramebufferScaleFactor() static method
=============================================================

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

 The static method
 **`XRWebGLLayer.getNativeFramebufferScaleFactor()`** returns a
 floating-point scaling factor by which one can multiply the specified
 `XRSession`'s resolution to get the native resolution of the WebXR
 device's frame buffer.

 This information can be used when creating a new `XRWebGLLayer` to configure
 the `framebufferScaleFactor` in the `layerInit` configuration object
 specified when calling the `XRWebGLLayer()` constructor. See the
 Usage notes and Examples for details.

 If the scaling factor is 1.0, then the frame buffer pixels and the native display
 pixels are the same size. If the scaling factor is greater than zero, then the frame
 buffer is smaller than the display's native dimensions, resulting in the output being
 up-scaled for display to the screen after rendering into the frame buffer. If the
 scaling factor is less than zero, the frame buffer is *larger* than the native
 resolution of the display, resulting in the frame buffer's contents being scaled down
 for display to the XR device. This can happen for display environments which use
 superscaling or anti-aliasing techniques to improve perceived image quality.

Syntax
------

```js
XRWebGLLayer.getNativeFramebufferScaleFactor(session)
```

### Parameters

`session`

 The `XRSession` for which to return the native framebuffer scaling
 factor.

### Return value

 A floating-point value which, when multiplied by the `XRSession`'s
 recommended framebuffer dimensions, results in the XR device's native frame buffer
 resolution. If the session has ended, this function returns 0.0.

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

 The scaling factor returned by this function will be 1.0 if the native resolution of
 the XR device and the resolution of the XR device match. In any case, multiplying the
 recommended resolution as identified by the `XRSession` by this value will
 result in the actual native resolution of the XR hardware.

 The recommended WebGL frame buffer resolution is the best possible estimate of the
 resolution necessary to contain all of the `XRView`s needed by the device
 while at the same time providing typical applications an acceptable balance of image
 quality and performance.

 For example, consider a device which uses a 2560x1440 pixel frame buffer (which is used
 to render two views, for the left and right eyes, side by side each at a resolution of
 1280x1440 pixels). Consider a frame buffer which at full size looks like this:

![Diagram showing how a framebuffer is divided between two eyes' viewpoints](/en-US/docs/Web/API/XRWebGLLayer/getNativeFramebufferScaleFactor_static/twoviewsoneframebuffer.svg)

 If, on this device, it's determined that due to GPU limitations the browser needs to
 reduce image quality in order to improve performance to an acceptable level, it might
 choose to halve the resolution. In this case, the value returned by
 `XRWebGLLayer.getNativeFramebufferScaleFactor()` will be 2.0. This method of
 dividing the frame buffer between views is shown in the following diagram.

![Diagram showing frame buffer as scaled to half resolution](/en-US/docs/Web/API/XRWebGLLayer/getNativeFramebufferScaleFactor_static/twoviewsoneframe-scaledby2.svg)

 Now the width and height of the frame buffer are 50% what they were before, resulting
 in a total frame buffer size of 1280 by 720 pixels, with each eye's half of the buffer
 being 640x720 pixels. Now we can see the coordinates of each of the viewports
 representing these two views:

![Framebuffer and viewports with coordinates](/en-US/docs/Web/API/XRWebGLLayer/getNativeFramebufferScaleFactor_static/twoviewsviewportcoords-scaledby2.svg)

 Since each eye gets half of the frame buffer, the result is that the left eye gets a
 640x720 portion of the buffer with the viewport's `x` and `y` at
 0, the width at 640, and the height set to 720. The right eye gets the other half of the
 frame buffer, with its viewport's `x` set at 639.

 While rendering a frame for this scene, we get the viewport for the view and apply it to WebGL, then
 render the scene. This ensures that the scene we render will not only match the
 viewpoint we need to express (which is defined by the position and orientation data in
 the pose), but that the rendered output will be constrained within the correct portion
 of the frame buffer for the eye we're drawing, regardless of any scaling that is being
 performed.

Examples
--------

 In this example, we request a frame buffer at the device's native resolution,
 regardless of any performance concerns:

```js
function requestNativeScaleWebGLLayer(gl, xrSession) {
  return gl.makeXRCompatible().then(() => {
    let scaleFactor = XRWebGLLayer.getNativeFramebufferScaleFactor(xrSession);
    let glLayer = new XRWebGLLayer(xrSession, gl, {
      framebufferScaleFactor: scaleFactor,
    });
    xrSession.updateRenderState({ baseLayer: glLayer });
  });
}
```

 This starts by calling the WebGL rendering context function `makeXRCompatible()`. When the returned `promise` resolves, we proceed by
 calling `XRWebGLLayer`'s `getNativeFramebufferScaleFactor()`
 static function to get the scale factor needed to reach the native resolution, and we
 then pass that into the `WebGLLayer()`
 constructor as the value of the `framebufferScaleFactor`
 property in its `layerInit` configuration object.

 That gets us a new `XRWebGLLayer` object representing a rendering surface
 we can use for the `XRSession`; we set it as the rendering surface for
 `xrSession` by calling its `updateRenderState()` method, passing the new `glLayer` in using the
 `XRRenderState` dictionary's `XRRenderState.baseLayer`
 property. The result is a rendering context that looks like the diagram below:

![Framebuffer and viewports with coordinates](/en-US/docs/Web/API/XRWebGLLayer/getNativeFramebufferScaleFactor_static/twoviewsviewportcoords.svg)

 Each time the `XRViewerPose`'s `views`
 are iterated over for rendering, the rendering loop obtains an `XRView` for
 the left eye which has its top-left corner at (0, 0) with its width and height being
 1280x1440 pixels. The right eye it obtains has its top-left corner at 1280, 0 with the
 same width and height: 1280x1440.

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

| Specification |
| --- |
| WebXR Device API # dom-xrwebgllayer-getnativeframebufferscalefactor |

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

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

See also
--------

* WebXR Device API
* WebXR performance guide


XRWebGLLayer: framebuffer property - Web APIs

XRWebGLLayer: framebuffer property
==================================

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

 The read-only `XRWebGLLayer` property
 **`framebuffer`** is an opaque `WebGLFramebuffer`
 which is used to buffer the rendered image if the XR compositor is being used. Otherwise, this property's value is
 `null`. The opaque framebuffer is functionally nearly the same as a
 standard WebGL framebuffer, except for the differences covered in the section
 How opaque framebuffers are special below.

Value
-----

 A `WebGLFramebuffer` object representing the framebuffer into which the 3D
 scene is being rendered, or `null` if the XR compositor is disabled for the session.

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

### How opaque framebuffers are special

 The framebuffer represented by the `framebuffer` property is opaque. As
 such, its behavior is different in several ways from a standard WebGL context. These
 differences cause the opaque framebuffer to behave more like the default WebGL
 framebuffer:

* Opaque framebuffers *may* support anti-aliasing, even under
 WebGL 1.0, which don't normally do so.
* Opaque framebuffers' attachments (buffers and the like) can't be inspected or
 changed. Calling functions such as
 `framebufferTexture2D()`,
 `framebufferRenderbuffer()`, `deleteFramebuffer()`, or
 `getFramebufferAttachmentParameter()` on an opaque framebuffer results in the WebGL
 error `INVALID_OPERATION` (0x0502).
* Opaque framebuffers are considered incomplete and are not available for rendering
 other than while executing the `requestAnimationFrame()` callback. Attempting to clear, draw to, or read from the
 framebuffer results in a WebGL `INVALID_FRAMEBUFFER_OPERATION` error
 (0x0506). Calling `checkFramebufferStatus()` on the WebGL context from outside the animation frame
 callback causes the WebGL `FRAMEBUFFER_UNSUPPORTED` error (0x8CDD) to be
 reported.
* Opaque framebuffers initialized with the `depth` property set to `false` will not have a depth buffer and will
 rely on the coordinates alone to determine distance.
* Opaque framebuffers initialized without specifying a `stencil`")}}` will not have a stencil buffer.
* Opaque framebuffers will not have an alpha channel available unless the `alpha` property is `true` when
 creating the layer.
* The XR compositor assumes that opaque framebuffers use colors with premultiplied
 alpha, regardless of whether or not the WebGL context's
 `premultipliedAlpha`")}}` context
 attribute is set.

**Note:** The `depth` and `stencil` properties are
 not required to be supported in order for a browser to be construed as having full
 WebGL support.

### The default configuration of a new framebuffer

 Upon creating a new `XRWebGLLayer`, its new framebuffer is initialized
 just like the default framebuffer for any WebGL interface:

* The color buffer is configured with its clear value set to the color (0, 0, 0, 0)
 (meaning transparent black).
* The depth buffer's clear value is the number 1.0.
* The stencil buffer is filled with 0.
Examples
--------

 This example gets the `XRWebGLLayer` for a session and then passes its
 framebuffer into the WebGL context's `bindFramebuffer()` function.

```js
let glLayer = xrSession.renderState.baselayer;
gl.bindFramebuffer(gl.FRAMEBUFFER, glLayer.framebuffer);
```

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

| Specification |
| --- |
| WebXR Device API # dom-xrwebgllayer-framebuffer |

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

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

See also
--------

* WebXR Device API


XRWebGLLayer: framebufferHeight property - Web APIs

XRWebGLLayer: framebufferHeight property
========================================

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

 The read-only `XRWebGLLayer` property
 **`framebufferHeight`** indicates the height of the
 framebuffer, in pixels.

 You can get the width of the framebuffer using the
 `framebufferWidth` property.

Value
-----

 The height in pixels of the XR device's framebuffer. Each of the framebuffer's
 attachments (pixel, depth, color, and/or stencil buffers, for example) are all this many
 pixels tall.

Examples
--------

This snippet fetches the framebuffer's width and height for later use.

```js
let glLayer = xrSession.renderState.baseLayer;
gl.bindFramebuffer(gl.FRAMEBUFFER, glLayer.framebuffer);

frameWidth = glLayer.framebufferHeight;
frameHeight = glLayer.framebufferHeight;
```

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

| Specification |
| --- |
| WebXR Device API # dom-xrwebgllayer-framebufferheight |

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

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

See also
--------

* WebXR Device API