repo_id
stringlengths 22
103
| file_path
stringlengths 41
147
| content
stringlengths 181
193k
| __index_level_0__
int64 0
0
|
---|---|---|---|
data/mdn-content/files/en-us/web/api/videotracklist | data/mdn-content/files/en-us/web/api/videotracklist/removetrack_event/index.md | ---
title: "VideoTrackList: removetrack event"
short-title: removetrack
slug: Web/API/VideoTrackList/removetrack_event
page-type: web-api-event
browser-compat: api.VideoTrackList.removetrack_event
---
{{APIRef}}
The `removetrack` event is fired when a video track is removed from a [`VideoTrackList`](/en-US/docs/Web/API/VideoTrackList).
## Syntax
Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property.
```js
addEventListener("removetrack", (event) => {});
onremovetrack = (event) => {};
```
## Event type
A {{domxref("TrackEvent")}}. Inherits from {{domxref("Event")}}.
{{InheritanceDiagram("TrackEvent")}}
## Event properties
_In addition to the properties listed below, properties from the parent interface, {{domxref("Event")}}, are available._
- {{domxref("TrackEvent.track", "track")}} {{ReadOnlyInline}}
- : The newly-removed {{domxref("VideoTrack")}} the event is in reference to.
## Examples
Using `addEventListener()`:
```js
const videoElement = document.querySelector("video");
videoElement.videoTracks.addEventListener("removetrack", (event) => {
console.log(`Video track: ${event.track.label} removed`);
});
```
Using the `onremovetrack` event handler property:
```js
const videoElement = document.querySelector("video");
videoElement.videoTracks.onremovetrack = (event) => {
console.log(`Video track: ${event.track.label} removed`);
};
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- Related events: [`addtrack`](/en-US/docs/Web/API/VideoTrackList/addtrack_event), [`change`](/en-US/docs/Web/API/VideoTrackList/change_event)
- This event on [`AudioTrackList`](/en-US/docs/Web/API/AudioTrackList) targets: [`removetrack`](/en-US/docs/Web/API/AudioTrackList/removetrack_event)
- This event on [`MediaStream`](/en-US/docs/Web/API/MediaStream) targets: [`removetrack`](/en-US/docs/Web/API/MediaStream/removetrack_event)
- [Media Capture and Streams API](/en-US/docs/Web/API/Media_Capture_and_Streams_API)
- [WebRTC](/en-US/docs/Web/API/WebRTC_API)
| 0 |
data/mdn-content/files/en-us/web/api/videotracklist | data/mdn-content/files/en-us/web/api/videotracklist/selectedindex/index.md | ---
title: "VideoTrackList: selectedIndex property"
short-title: selectedIndex
slug: Web/API/VideoTrackList/selectedIndex
page-type: web-api-instance-property
browser-compat: api.VideoTrackList.selectedIndex
---
{{APIRef("HTML DOM")}}
The read-only **{{domxref("VideoTrackList")}}**
property **`selectedIndex`** returns the index of the
currently selected track, if any, or `-1` otherwise.
## Value
A number indicating the index of the currently selected track, if any, or
`-1` otherwise.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/videotracklist | data/mdn-content/files/en-us/web/api/videotracklist/change_event/index.md | ---
title: "VideoTrackList: change event"
short-title: change
slug: Web/API/VideoTrackList/change_event
page-type: web-api-event
browser-compat: api.VideoTrackList.change_event
---
{{APIRef}}
The `change` event is fired when a video track is made active or inactive, for example by changing the track's [`selected`](/en-US/docs/Web/API/VideoTrack/selected) property.
## Syntax
Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property.
```js
addEventListener("change", (event) => {});
onchange = (event) => {};
```
## Event type
A generic {{DOMxRef("Event")}} with no added properties.
## Examples
Using `addEventListener()`:
```js
const videoElement = document.querySelector("video");
videoElement.videoTracks.addEventListener("change", (event) => {
console.log(`'${event.type}' event fired`);
});
// changing the value of `selected` will trigger the `change` event
const toggleTrackButton = document.querySelector(".toggle-track");
toggleTrackButton.addEventListener("click", () => {
const track = videoElement.videoTracks[0];
track.selected = !track.selected;
});
```
Using the `onchange` event handler property:
```js
const videoElement = document.querySelector("video");
videoElement.videoTracks.onchange = (event) => {
console.log(`'${event.type}' event fired`);
};
// changing the value of `selected` will trigger the `change` event
const toggleTrackButton = document.querySelector(".toggle-track");
toggleTrackButton.addEventListener("click", () => {
const track = videoElement.videoTracks[0];
track.selected = !track.selected;
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- Related events: [`addtrack`](/en-US/docs/Web/API/VideoTrackList/addtrack_event), [`removetrack`](/en-US/docs/Web/API/VideoTrackList/removetrack_event)
- This event on [`AudioTrackList`](/en-US/docs/Web/API/AudioTrackList) targets: [`change`](/en-US/docs/Web/API/AudioTrackList/change_event)
- [Media Capture and Streams API](/en-US/docs/Web/API/Media_Capture_and_Streams_API)
- [WebRTC](/en-US/docs/Web/API/WebRTC_API)
| 0 |
data/mdn-content/files/en-us/web/api/videotracklist | data/mdn-content/files/en-us/web/api/videotracklist/gettrackbyid/index.md | ---
title: "VideoTrackList: getTrackById() method"
short-title: getTrackById()
slug: Web/API/VideoTrackList/getTrackById
page-type: web-api-instance-method
browser-compat: api.VideoTrackList.getTrackById
---
{{APIRef("HTML DOM")}}
The **{{domxref("VideoTrackList")}}** method
**`getTrackById()`** returns the first
{{domxref("VideoTrack")}} object from the track list whose {{domxref("VideoTrack.id",
"id")}} matches the specified string.
This lets you find a specified track if
you know its ID string.
## Syntax
```js-nolint
getTrackById(id)
```
### Parameters
- `id`
- : A string indicating the ID of the track to locate within the track
list.
### Return value
A {{domxref("VideoTrack")}} object indicating the first track found within the
`VideoTrackList` whose `id` matches the specified string. If no
match is found, this method returns `null`.
The tracks are searched in their natural order; that is, in the order defined by the
media resource itself, or, if the resource doesn't define an order, the relative order
in which the tracks are declared by the media resource.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/htmloptgroupelement/index.md | ---
title: HTMLOptGroupElement
slug: Web/API/HTMLOptGroupElement
page-type: web-api-interface
browser-compat: api.HTMLOptGroupElement
---
{{ APIRef("HTML DOM") }}
The **`HTMLOptGroupElement`** interface provides special properties and methods (beyond the regular {{domxref("HTMLElement")}} object interface they also have available to them by inheritance) for manipulating the layout and presentation of {{HTMLElement("optgroup")}} elements.
{{InheritanceDiagram}}
## Instance properties
_Inherits properties from its parent, {{domxref("HTMLElement")}}._
- {{domxref("HTMLOptGroupElement.disabled")}}
- : A boolean value representing whether or not the whole list of children {{HTMLElement("option")}} is disabled (true) or not (false).
- {{domxref("HTMLOptGroupElement.label")}}
- : A string representing the label for the group.
## Instance methods
_No specific method; inherits methods from its parent, {{domxref("HTMLElement")}}._
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The HTML element implementing this interface: {{ HTMLElement("optgroup") }}.
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/fontface/index.md | ---
title: FontFace
slug: Web/API/FontFace
page-type: web-api-interface
browser-compat: api.FontFace
---
{{APIRef("CSS Font Loading API")}}
The **`FontFace`** interface of the [CSS Font Loading API](/en-US/docs/Web/API/CSS_Font_Loading_API) represents a single usable font face.
This interface defines the source of a font face, either a URL to an external resource or a buffer, and font properties such as `style`, `weight`, and so on.
For URL font sources it allows authors to trigger when the remote font is fetched and loaded, and to track loading status.
## Constructor
- {{domxref("FontFace.FontFace", "FontFace()")}}
- : Constructs and returns a new `FontFace` object, built from an external resource described by a URL or from an {{jsxref("ArrayBuffer")}}.
## Instance properties
- {{domxref("FontFace.ascentOverride")}}
- : A string that retrieves or sets the _ascent metric_ of the font. It is equivalent to the {{cssxref("@font-face/ascent-override", "ascent-override")}} descriptor.
- {{domxref("FontFace.descentOverride")}}
- : A string that retrieves or sets the _descent metric_ of the font. It is equivalent to the {{cssxref("@font-face/descent-override", "descent-override")}} descriptor.
- {{domxref("FontFace.display")}}
- : A string that determines how a font face is displayed based on whether and when it is downloaded and ready to use.
- {{domxref("FontFace.family")}}
- : A string that retrieves or sets the _family_ of the font. It is equivalent to the {{cssxref("@font-face/font-family", "font-family")}} descriptor.
- {{domxref("FontFace.featureSettings")}}
- : A string that retrieves or sets infrequently used font features that are not available from a font's variant properties. It is equivalent to the CSS {{cssxref("font-feature-settings")}} property.
- {{domxref("FontFace.lineGapOverride")}}
- : A string that retrieves or sets the _line-gap metric_ of the font. It is equivalent to the {{cssxref("@font-face/line-gap-override", "line-gap-override")}} descriptor.
- {{domxref("FontFace.loaded")}} {{ReadOnlyInline}}
- : Returns a {{jsxref("Promise")}} that resolves with the current `FontFace` object when the font specified in the object's constructor is done loading or rejects with a `SyntaxError` {{domxref("DOMException")}}.
- {{domxref("FontFace.status")}} {{ReadOnlyInline}}
- : Returns an enumerated value indicating the status of the font, one of `"unloaded"`, `"loading"`, `"loaded"`, or `"error"`.
- {{domxref("FontFace.stretch")}}
- : A string that retrieves or sets how the font _stretches_. It is equivalent to the {{cssxref("@font-face/font-stretch", "font-stretch")}} descriptor.
- {{domxref("FontFace.style")}}
- : A string that retrieves or sets the _style_ of the font. It is equivalent to the {{cssxref("@font-face/font-style", "font-style")}} descriptor.
- {{domxref("FontFace.unicodeRange")}}
- : A string that retrieves or sets the _range of unicode code points_ encompassing the font. It is equivalent to the {{cssxref("@font-face/unicode-range", "unicode-range")}} descriptor.
- {{domxref("FontFace.variant")}}
- : A string that retrieves or sets the _variant_ of the font.
- {{domxref("FontFace.variationSettings")}} {{Experimental_Inline}}
- : A string that retrieves or sets the _variation settings_ of the font. It is equivalent to the {{cssxref("@font-face/font-variation-settings", "font-variation-settings")}} descriptor.
- {{domxref("FontFace.weight")}}
- : A string that contains the _weight_ of the font. It is equivalent to the {{cssxref("@font-face/font-weight", "font-weight")}} descriptor.
- {{domxref("FontFace.load()")}}
- : Loads a font based on current object's constructor-passed requirements, including a location or source buffer, and returns a {{jsxref('Promise')}} that resolves with the current FontFace object.
## Examples
The code below defines a font face using data at the URL "myfont.woff" with a few font descriptors.
Just to show how it works, we then define the `stretch` descriptor using a property.
```js
//Define a FontFace
const font = new FontFace("myfont", "url(myfont.woff)", {
style: "italic",
weight: "400",
});
font.stretch = "condensed";
```
Next we load the font using {{domxref("FontFace.load()")}} and use the returned promise to track completion or report an error.
```js
//Load the font
font.load().then(
() => {
// Resolved - add font to document.fonts
},
(err) => {
console.error(err);
},
);
```
To actually _use_ the font we will need to add it to a {{domxref("FontFaceSet")}}.
We could do that before or after loading the font.
For additional examples see [CSS Font Loading API > Examples](/en-US/docs/Web/API/CSS_Font_Loading_API#examples).
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [@font-face](/en-US/docs/Web/CSS/@font-face)
| 0 |
data/mdn-content/files/en-us/web/api/fontface | data/mdn-content/files/en-us/web/api/fontface/linegapoverride/index.md | ---
title: "FontFace: lineGapOverride property"
short-title: lineGapOverride
slug: Web/API/FontFace/lineGapOverride
page-type: web-api-instance-property
browser-compat: api.FontFace.lineGapOverride
---
{{APIRef("CSS Font Loading API")}}
The **`lineGapOverride`** property of the {{domxref("FontFace")}} interface returns and sets the value of the {{cssxref("@font-face/line-gap-override")}} descriptor.
The possible values are `normal`, indicating that the metric used should be obtained from the font file, or a percentage.
## Value
A string.
## Examples
```js
let fontFace = new FontFace(
"Roboto",
"url(https://fonts.example.com/roboto.woff2)",
{ lineGapOverride: "90%" },
);
console.log(fontFace.lineGapOverride); // 90%
fontFace.lineGapOverride = "normal";
console.log(fontFace.lineGapOverride); // 'normal'
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/fontface | data/mdn-content/files/en-us/web/api/fontface/featuresettings/index.md | ---
title: "FontFace: featureSettings property"
short-title: featureSettings
slug: Web/API/FontFace/featureSettings
page-type: web-api-instance-property
browser-compat: api.FontFace.featureSettings
---
{{APIRef("CSS Font Loading API")}}
The **`featureSettings`** property of the {{domxref("FontFace")}} interface retrieves or sets infrequently used font features that are not available from a font's variant properties.
This property is equivalent to the {{cssxref("font-feature-settings")}} descriptor.
## Value
A string containing a descriptor.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/fontface | data/mdn-content/files/en-us/web/api/fontface/family/index.md | ---
title: "FontFace: family property"
short-title: family
slug: Web/API/FontFace/family
page-type: web-api-instance-property
browser-compat: api.FontFace.family
---
{{APIRef("CSS Font Loading API")}}
The **`FontFace.family`** property allows the author to get or set the font family of a {{domxref("FontFace")}} object.
The value is used for name matching against a particular font face when styling elements using the [`font-family`](/en-US/docs/Web/CSS/font-family) property.
Any name may be used, and this overrides any name specified in the underlying font data.
This property is equivalent to the {{cssxref("@font-face/font-family", "font-family")}} descriptor of {{cssxref("@font-face")}}.
## Value
A string.
## Examples
```js
let fontFace = new FontFace(
"Roboto",
"url(https://fonts.example.com/roboto.woff2)",
);
console.log(fontFace.family); // 'Roboto'
fontFace.family = "newRoboto";
console.log(fontFace.family); // 'newRoboto'
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/fontface | data/mdn-content/files/en-us/web/api/fontface/variationsettings/index.md | ---
title: "FontFace: variationSettings property"
short-title: variationSettings
slug: Web/API/FontFace/variationSettings
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.FontFace.variationSettings
---
{{APIRef("CSS Font Loading API")}}{{SeeCompatTable}}
The **`variationSettings`** property of the {{domxref("FontFace")}} interface retrieves or sets low-level OpenType or TrueType font variations.
This property is equivalent to the {{cssxref("@font-face/font-variation-settings", "font-variation-settings")}} descriptor.
## Value
A string containing a descriptor.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/fontface | data/mdn-content/files/en-us/web/api/fontface/status/index.md | ---
title: "FontFace: status property"
short-title: status
slug: Web/API/FontFace/status
page-type: web-api-instance-property
browser-compat: api.FontFace.status
---
{{APIRef("CSS Font Loading API")}}
The **`status`** read-only property of the {{domxref("FontFace")}} interface returns an enumerated value indicating the status of the font, one of `"unloaded"`, `"loading"`, `"loaded"`, or `"error"`.
## Value
One of `"unloaded"`, `"loading"`, `"loaded"`, or `"error"`.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/fontface | data/mdn-content/files/en-us/web/api/fontface/display/index.md | ---
title: "FontFace: display property"
short-title: display
slug: Web/API/FontFace/display
page-type: web-api-instance-property
browser-compat: api.FontFace.display
---
{{APIRef("CSS Font Loading API")}}
The **`display`** property of the {{domxref("FontFace")}} interface determines how a font face is displayed based on whether and when it is downloaded and ready to use.
This property is equivalent to the CSS `font-display` descriptor.
When this property is used, font loading has a timeline with three periods.
The lengths of the first two periods depend on the value of the property and the user agent.
(See below.)
- block period
- : The browser invisibly prepares a fallback font. If the font face loads during this time, it's used to display the text and display is complete.
- swap period
- : If the font face is still not loaded, the fallback font will be shown.
When the font face loads, the fallback will be swapped for the downloaded font.
- failure period
- : If the font face still is not loaded, the fallback font will be shown and no swap will occur.
## Value
A string with one of the following values.
- `auto`
- : Use the font display strategy provided by the user agent.
- `block`
- : Gives the font face a short block period and an infinite swap period.
The spec recommends 3 seconds for the block period, though this may vary from browser to browser.
- `fallback`
- : Gives the font face a short block period and a short swap period.
The spec recommends 100 ms or less for the block period and 3 seconds for the swap period, though these values may vary from browser to browser.
- `optional`
- : Gives the font face a short block period and no swap period.
The spec recommends 100 ms or less, though this may vary from browser to browser.
- `swap`
- : Gives the font face a 0 second block period and an infinite swap period.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/fontface | data/mdn-content/files/en-us/web/api/fontface/style/index.md | ---
title: "FontFace: style property"
short-title: style
slug: Web/API/FontFace/style
page-type: web-api-instance-property
browser-compat: api.FontFace.style
---
{{APIRef("CSS Font Loading API")}}
The **`style`** property of the {{domxref("FontFace")}} interface retrieves or sets the font's style.
This property is equivalent to the {{cssxref("@font-face/font-style", "font-style")}} descriptor.
## Value
A string containing the descriptors defined in the style sheet's `@font-face` rule.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/fontface | data/mdn-content/files/en-us/web/api/fontface/ascentoverride/index.md | ---
title: "FontFace: ascentOverride property"
short-title: ascentOverride
slug: Web/API/FontFace/ascentOverride
page-type: web-api-instance-property
browser-compat: api.FontFace.ascentOverride
---
{{APIRef("CSS Font Loading API")}}
The **`ascentOverride`** property of the {{domxref("FontFace")}} interface returns and sets the ascent metric for the font, the height above the baseline that CSS uses to lay out line boxes in an inline formatting context.
This property is equivalent to the {{cssxref("@font-face/ascent-override")}} descriptor of {{cssxref("@font-face")}}.
## Value
A string. The possible values are `normal`, indicating that the metric used should be obtained from the font file, or a percentage.
This property accepts the same values as the {{cssxref("@font-face/ascent-override")}} descriptor.
## Examples
```js
let fontFace = new FontFace(
"Roboto",
"url(https://fonts.example.com/roboto.woff2)",
{ ascentOverride: "90%" },
);
console.log(fontFace.ascentOverride); // 90%
fontFace.ascentOverride = "normal";
console.log(fontFace.ascentOverride); // 'normal'
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/fontface | data/mdn-content/files/en-us/web/api/fontface/variant/index.md | ---
title: "FontFace: variant property"
short-title: variant
slug: Web/API/FontFace/variant
page-type: web-api-instance-property
browser-compat: api.FontFace.variant
---
{{APIRef("CSS Font Loading API")}}
The **`variant`** property of the
{{domxref("FontFace")}} interface programmatically retrieves or sets font variant
values.
## Value
A string containing a descriptor as it would be defined in a style
sheet's `@font-face` rule.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/fontface | data/mdn-content/files/en-us/web/api/fontface/loaded/index.md | ---
title: "FontFace: loaded property"
short-title: loaded
slug: Web/API/FontFace/loaded
page-type: web-api-instance-property
browser-compat: api.FontFace.loaded
---
{{APIRef("CSS Font Loading API")}}
The **`loaded`** read-only property of the {{domxref("FontFace")}} interface returns a {{jsxref('Promise')}} that resolves with the current `FontFace` object when the font specified in the object's constructor is done loading or rejects with a `SyntaxError`.
## Value
A {{jsxref('Promise')}} that resolves with the current `FontFace` object.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/fontface | data/mdn-content/files/en-us/web/api/fontface/fontface/index.md | ---
title: "FontFace: FontFace() constructor"
short-title: FontFace()
slug: Web/API/FontFace/FontFace
page-type: web-api-constructor
browser-compat: api.FontFace.FontFace
---
{{APIRef("CSS Font Loading API")}}
The **`FontFace()`** constructor creates a new {{domxref("FontFace")}} object.
## Syntax
```js-nolint
new FontFace(family, source)
new FontFace(family, source, descriptors)
```
### Parameters
- `family`
- : Specifies a font family name that can be used to match against this font face when styling elements.
Takes the same type of values as the {{cssxref("@font-face/font-family", "font-family")}} descriptor of {{cssxref("@font-face")}}.
This value may also be read and set using the [`FontFace.family`](/en-US/docs/Web/API/FontFace/family) property.
- `source`
- : The font source.
This can be either:
- A URL to a font face file.
- Binary font face data in an [`ArrayBuffer`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) or a [`TypedArray`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray).
- `descriptors` {{optional_inline}}
- : A set of optional descriptors passed as an object.
It can contain any of the descriptors available for `@font-face`:
- `ascentOverride`
- : With an allowable value for {{cssxref("@font-face/ascent-override")}}.
- `descentOverride`
- : With an allowable value for {{cssxref("@font-face/descent-override")}}.
- `display`
- : With an allowable value for {{cssxref("@font-face/font-display")}}.
- `featureSettings`
- : With an allowable value for {{cssxref("font-feature-settings")}}.
- `lineGapOverride`
- : With an allowable value for {{cssxref("@font-face/line-gap-override")}}.
- `stretch`
- : With an allowable value for {{cssxref("@font-face/font-stretch")}}.
- `style`
- : With an allowable value for {{cssxref("@font-face/font-style")}}.
- `unicodeRange`
- : With an allowable value for {{cssxref("@font-face/unicode-range")}}.
- `variationSettings`
- : With an allowable value for {{cssxref("@font-face/font-variation-settings")}}.
- `weight`
- : With an allowable value for {{cssxref("@font-face/font-weight")}}.
### Exceptions
- `SyntaxError` {{domxref("DOMException")}}
- : Thrown when a descriptor string does not match the grammar of the corresponding {{cssxref("@font-face")}} descriptor, or the specified binary source cannot be loaded.
This error results in {{domxref("FontFace.status")}} being set to `error`.
## Examples
```js
async function loadFonts() {
const font = new FontFace("myfont", "url(myfont.woff)", {
style: "normal",
weight: "400",
stretch: "condensed",
});
// wait for font to be loaded
await font.load();
// add font to document
document.fonts.add(font);
// enable font with CSS class
document.body.classList.add("fonts-loaded");
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{cssxref("@font-face")}}
| 0 |
data/mdn-content/files/en-us/web/api/fontface | data/mdn-content/files/en-us/web/api/fontface/descentoverride/index.md | ---
title: "FontFace: descentOverride property"
short-title: descentOverride
slug: Web/API/FontFace/descentOverride
page-type: web-api-instance-property
browser-compat: api.FontFace.descentOverride
---
{{APIRef("CSS Font Loading API")}}
The **`descentOverride`** property of the {{domxref("FontFace")}} interface returns and sets the value of the {{cssxref("@font-face/descent-override")}} descriptor.
The possible values are `normal`, indicating that the metric used should be obtained from the font file, or a percentage.
## Value
A string.
## Examples
```js
let fontFace = new FontFace(
"Roboto",
"url(https://fonts.example.com/roboto.woff2)",
{ descentOverride: "90%" },
);
console.log(fontFace.descentOverride); // 90%
fontFace.descentOverride = "normal";
console.log(fontFace.descentOverride); // 'normal'
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/fontface | data/mdn-content/files/en-us/web/api/fontface/load/index.md | ---
title: "FontFace: load() method"
short-title: load()
slug: Web/API/FontFace/load
page-type: web-api-instance-method
browser-compat: api.FontFace.load
---
{{APIRef("CSS Font Loading API")}}
The **`load()`** method of the {{domxref("FontFace")}} interface requests and loads a font whose `source` was specified as a URL. It returns a {{jsxref('Promise')}} that resolves with the current `FontFace` object.
If the `source` for the font face was specified as binary data, or the font {{domxref("FontFace/status", "status")}} property of the font face is anything other than `unloaded`, then this method does nothing.
## Syntax
```js-nolint
load()
```
### Parameters
None.
### Return value
A {{jsxref('Promise')}} that resolves with a reference to the current `FontFace` object when the font loads or rejects with a `NetworkError` {{domxref("DOMException")}} if the loading process fails.
### Exceptions
- `NetworkError` {{domxref("DOMException")}}
- : Indicates that the attempt to load the font failed.
## Examples
This simple example loads a font and uses it to display some text in a canvas element (with an id of `js-canvas`).
```html hidden
<canvas id="js-canvas"></canvas>
```
```js
const canvas = document.getElementById("js-canvas");
// load the "Bitter" font from Google Fonts
const fontFile = new FontFace(
"FontFamily Style Bitter",
"url(https://fonts.gstatic.com/s/bitter/v7/HEpP8tJXlWaYHimsnXgfCOvvDin1pK8aKteLpeZ5c0A.woff2)",
);
document.fonts.add(fontFile);
fontFile.load().then(
() => {
// font loaded successfully!
canvas.width = 650;
canvas.height = 100;
const ctx = canvas.getContext("2d");
ctx.font = '36px "FontFamily Style Bitter"';
ctx.fillText("Bitter font loaded", 20, 50);
},
(err) => {
console.error(err);
},
);
```
{{EmbedLiveSample('Examples')}}
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/fontface | data/mdn-content/files/en-us/web/api/fontface/stretch/index.md | ---
title: "FontFace: stretch property"
short-title: stretch
slug: Web/API/FontFace/stretch
page-type: web-api-instance-property
browser-compat: api.FontFace.stretch
---
{{APIRef("CSS Font Loading API")}}
The **`stretch`** property of the {{domxref("FontFace")}} interface retrieves or sets how the font stretches.
This property is equivalent to the {{cssxref("@font-face/font-stretch", "font-stretch")}} descriptor.
## Value
A string containing a descriptor as it would be defined in a style sheet's `@font-face` rule.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/fontface | data/mdn-content/files/en-us/web/api/fontface/unicoderange/index.md | ---
title: "FontFace: unicodeRange property"
short-title: unicodeRange
slug: Web/API/FontFace/unicodeRange
page-type: web-api-instance-property
browser-compat: api.FontFace.unicodeRange
---
{{APIRef("CSS Font Loading API")}}
The **`unicodeRange`** property of the {{domxref("FontFace")}} interface retrieves or sets the range of unicode code points encompassing the font.
This property is equivalent to the {{cssxref("@font-face/unicode-range", "unicode-range")}} descriptor.
## Value
A string containing a descriptor as it would appear in a style sheet's `@font-face` rule.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/fontface | data/mdn-content/files/en-us/web/api/fontface/weight/index.md | ---
title: "FontFace: weight property"
short-title: weight
slug: Web/API/FontFace/weight
page-type: web-api-instance-property
browser-compat: api.FontFace.weight
---
{{APIRef("CSS Font Loading API")}}
The **`weight`** property of the {{domxref("FontFace")}} interface retrieves or sets the weight of the font.
This property is equivalent to the {{cssxref("@font-face/font-weight", "font-weight")}} descriptor.
## Value
A string containing a descriptor as it would be defined in a style sheet's `@font-face` rule.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/idbcursorwithvalue/index.md | ---
title: IDBCursorWithValue
slug: Web/API/IDBCursorWithValue
page-type: web-api-interface
browser-compat: api.IDBCursorWithValue
---
{{APIRef("IndexedDB")}}
The **`IDBCursorWithValue`** interface of the [IndexedDB API](/en-US/docs/Web/API/IndexedDB_API) represents a [cursor](/en-US/docs/Web/API/IndexedDB_API/Basic_Terminology#cursor) for traversing or iterating over multiple records in a database. It is the same as the {{domxref("IDBCursor")}}, except that it includes the `value` property.
The cursor has a source that indicates which index or object store it is iterating over. It has a position within the range, and moves in a direction that is increasing or decreasing in the order of record keys. The cursor enables an application to asynchronously process all the records in the cursor's range.
You can have an unlimited number of cursors at the same time. You always get the same `IDBCursorWithValue` object representing a given cursor. Operations are performed on the underlying index or object store.
{{AvailableInWorkers}}
{{InheritanceDiagram}}
## Instance methods
Inherits methods from its parent interface, {{domxref("IDBCursor")}}.
## Instance properties
Inherits properties from its parent interface, {{domxref("IDBCursor")}}.
- {{domxref("IDBCursorWithValue.value")}} {{ReadOnlyInline}}
- : Returns the value of the current cursor.
## Example
In this example we create a transaction, retrieve an object store, then use a cursor to iterate through all the records in the object store. The cursor does not require us to select the data based on a key; we can just grab all of it. Also note that in each iteration of the loop, you can grab data from the current record under the cursor object using `cursor.value.foo`. For a complete working example, see our [IDBCursor example](https://github.com/mdn/dom-examples/tree/main/indexeddb-examples/idbcursor) ([view example live](https://mdn.github.io/dom-examples/indexeddb-examples/idbcursor/).)
```js
function displayData() {
const transaction = db.transaction(["rushAlbumList"], "readonly");
const objectStore = transaction.objectStore("rushAlbumList");
objectStore.openCursor().onsuccess = (event) => {
const cursor = event.target.result;
if (cursor) {
const listItem = document.createElement("li");
listItem.textContent = `${cursor.value.albumTitle}, ${cursor.value.year}`;
list.appendChild(listItem);
cursor.continue();
} else {
console.log("Entries all displayed.");
}
};
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using IndexedDB](/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB)
- Starting transactions: {{domxref("IDBDatabase")}}
- Using transactions: {{domxref("IDBTransaction")}}
- Setting a range of keys: {{domxref("IDBKeyRange")}}
- Retrieving and making changes to your data: {{domxref("IDBObjectStore")}}
- Using cursors: {{domxref("IDBCursor")}}
- Reference example: [To-do Notifications](https://github.com/mdn/dom-examples/tree/main/to-do-notifications) ([View the example live](https://mdn.github.io/dom-examples/to-do-notifications/)).
| 0 |
data/mdn-content/files/en-us/web/api/idbcursorwithvalue | data/mdn-content/files/en-us/web/api/idbcursorwithvalue/value/index.md | ---
title: "IDBCursorWithValue: value property"
short-title: value
slug: Web/API/IDBCursorWithValue/value
page-type: web-api-instance-property
browser-compat: api.IDBCursorWithValue.value
---
{{ APIRef("IndexedDB") }}
The **`value`** read-only property of the
{{domxref("IDBCursorWithValue")}} interface returns the value of the current cursor,
whatever that is.
{{AvailableInWorkers}}
## Value
The value of the current cursor.
## Examples
In this example we create a transaction, retrieve an object store, then use a cursor to
iterate through all the records in the object store. Within each iteration we log the
value of the cursor with `cursor.value`.
The cursor does not require us to select the data based
on a key; we can just grab all of it. Also note that in each iteration of the loop,
you can grab data from the current record under the cursor object using `cursor.value.foo`.
For a complete working example, see our [IDBCursor example](https://github.com/mdn/dom-examples/tree/main/indexeddb-examples/idbcursor)
([view example live](https://mdn.github.io/dom-examples/indexeddb-examples/idbcursor/).)
```js
function displayData() {
const transaction = db.transaction(["rushAlbumList"], "readonly");
const objectStore = transaction.objectStore("rushAlbumList");
objectStore.openCursor().onsuccess = (event) => {
const cursor = event.target.result;
if (cursor) {
const listItem = document.createElement("li");
listItem.textContent = `${cursor.value.albumTitle}, ${cursor.value.year}`;
list.appendChild(listItem);
console.log(cursor.value);
cursor.continue();
} else {
console.log("Entries all displayed.");
}
};
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using IndexedDB](/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB)
- Starting transactions: {{domxref("IDBDatabase")}}
- Using transactions: {{domxref("IDBTransaction")}}
- Setting a range of keys: {{domxref("IDBKeyRange")}}
- Retrieving and making changes to your data: {{domxref("IDBObjectStore")}}
- Using cursors: {{domxref("IDBCursor")}}
- Reference example: [To-do Notifications](https://github.com/mdn/dom-examples/tree/main/to-do-notifications) ([View the example live](https://mdn.github.io/dom-examples/to-do-notifications/)).
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/svgfemorphologyelement/index.md | ---
title: SVGFEMorphologyElement
slug: Web/API/SVGFEMorphologyElement
page-type: web-api-interface
browser-compat: api.SVGFEMorphologyElement
---
{{APIRef("SVG")}}
The **`SVGFEMorphologyElement`** interface corresponds to the {{SVGElement("feMorphology")}} element.
{{InheritanceDiagram}}
## Constants
<table class="no-markdown">
<tbody>
<tr>
<th>Name</th>
<th>Value</th>
<th>Description</th>
</tr>
<tr>
<td><code>SVG_MORPHOLOGY_OPERATOR_UNKNOWN</code></td>
<td>0</td>
<td>
The type is not one of predefined types. It is invalid to attempt to
define a new value of this type or to attempt to switch an existing
value to this type.
</td>
</tr>
<tr>
<td><code>SVG_MORPHOLOGY_OPERATOR_ERODE</code></td>
<td>1</td>
<td>Corresponds to the <code>erode</code> value.</td>
</tr>
<tr>
<td><code>SVG_MORPHOLOGY_OPERATOR_DILATE</code></td>
<td>2</td>
<td>Corresponds to <code>dilate</code> value.</td>
</tr>
</tbody>
</table>
## Instance properties
_This interface also inherits properties from its parent interface, {{domxref("SVGElement")}}._
- {{domxref("SVGFEMorphologyElement.height")}} {{ReadOnlyInline}}
- : An {{domxref("SVGAnimatedLength")}} corresponding to the {{SVGAttr("height")}} attribute of the given element.
- {{domxref("SVGFEMorphologyElement.in1")}} {{ReadOnlyInline}}
- : An {{domxref("SVGAnimatedString")}} corresponding to the {{SVGAttr("in")}} attribute of the given element.
- {{domxref("SVGFEMorphologyElement.operator")}} {{ReadOnlyInline}}
- : An {{domxref("SVGAnimatedEnumeration")}} corresponding to the {{SVGAttr("operator")}} attribute of the given element. It takes one of the `SVG_MORPHOLOGY_OPERATOR_*` constants defined on this interface.
- {{domxref("SVGFEMorphologyElement.radiusX")}} {{ReadOnlyInline}}
- : An {{domxref("SVGAnimatedNumber")}} corresponding to the X component of the {{SVGAttr("radius")}} attribute of the given element.
- {{domxref("SVGFEMorphologyElement.radiusY")}} {{ReadOnlyInline}}
- : An {{domxref("SVGAnimatedNumber")}} corresponding to the Y component of the {{SVGAttr("radius")}} attribute of the given element.
- {{domxref("SVGFEMorphologyElement.result")}} {{ReadOnlyInline}}
- : An {{domxref("SVGAnimatedString")}} corresponding to the {{SVGAttr("result")}} attribute of the given element.
- {{domxref("SVGFEMorphologyElement.width")}} {{ReadOnlyInline}}
- : An {{domxref("SVGAnimatedLength")}} corresponding to the {{SVGAttr("width")}} attribute of the given element.
- {{domxref("SVGFEMorphologyElement.x")}} {{ReadOnlyInline}}
- : An {{domxref("SVGAnimatedLength")}} corresponding to the {{SVGAttr("x")}} attribute of the given element.
- {{domxref("SVGFEMorphologyElement.y")}} {{ReadOnlyInline}}
- : An {{domxref("SVGAnimatedLength")}} corresponding to the {{SVGAttr("y")}} attribute of the given element.
## Instance methods
_This interface does not provide any specific methods, but implements those of its parent, {{domxref("SVGElement")}}._
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{SVGElement("feMorphology")}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/svgviewelement/index.md | ---
title: SVGViewElement
slug: Web/API/SVGViewElement
page-type: web-api-interface
browser-compat: api.SVGViewElement
---
{{APIRef("SVG")}}
The **`SVGViewElement`** interface provides access to the properties of {{SVGElement("view")}} elements, as well as methods to manipulate them.
{{InheritanceDiagram}}
## Instance properties
_This interface also inherits properties from its parent interface, {{domxref("SVGElement")}}._
## Instance methods
_This interface doesn't implement any specific methods, but inherits methods from its parent interface, {{domxref("SVGElement")}}._
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{SVGElement("view")}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/gamepadhapticactuator/index.md | ---
title: GamepadHapticActuator
slug: Web/API/GamepadHapticActuator
page-type: web-api-interface
browser-compat: api.GamepadHapticActuator
---
{{APIRef("Gamepad API")}}{{securecontext_header}}
The **`GamepadHapticActuator`** interface of the [Gamepad API](/en-US/docs/Web/API/Gamepad_API) represents hardware in the controller designed to provide haptic feedback to the user (if available), most commonly vibration hardware.
This interface is accessible through the {{domxref("Gamepad.hapticActuators")}} property.
## Instance properties
- {{domxref("GamepadHapticActuator.type")}} {{ReadOnlyInline}}
- : Returns an enum representing the type of the haptic hardware.
## Instance methods
- {{domxref("GamepadHapticActuator.pulse()")}} {{ReadOnlyInline}}
- : Makes the hardware pulse at a certain intensity for a specified duration.
- {{domxref("GamepadHapticActuator.playEffect()")}} {{ReadOnlyInline}} {{Non-standard_Inline}}
- : Makes the hardware play a specific vibration pattern.
## Examples
```js
const gamepad = navigator.getGamepads()[0];
gamepad.hapticActuators[0].pulse(1.0, 200);
gamepad.vibrationActuator.playEffect("dual-rumble", {
startDelay: 0,
duration: 200,
weakMagnitude: 1.0,
strongMagnitude: 1.0,
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Gamepad API](/en-US/docs/Web/API/Gamepad_API)
| 0 |
data/mdn-content/files/en-us/web/api/gamepadhapticactuator | data/mdn-content/files/en-us/web/api/gamepadhapticactuator/pulse/index.md | ---
title: "GamepadHapticActuator: pulse() method"
short-title: pulse()
slug: Web/API/GamepadHapticActuator/pulse
page-type: web-api-instance-method
browser-compat: api.GamepadHapticActuator.pulse
---
{{APIRef("Gamepad")}}
The **`pulse()`** method of the {{domxref("GamepadHapticActuator")}} interface makes the hardware pulse at a certain intensity for a specified duration.
## Syntax
```js-nolint
pulse(value, duration)
```
### Parameters
- `value`
- : A double representing the intensity of the pulse. This can vary depending on the hardware type, but generally takes a value between 0.0 (no intensity) and 1.0 (full intensity).
- `duration`
- : A double representing the duration of the pulse, in milliseconds.
> **Note:** Repeated calls to `pulse()` override the previous calls if they are still ongoing.
### Return value
A promise that resolves with a value of `true` when the pulse has successfully completed.
## Examples
```js
const gamepad = navigator.getGamepads()[0];
gamepad.hapticActuators[0].pulse(1.0, 200);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Gamepad API](/en-US/docs/Web/API/Gamepad_API)
| 0 |
data/mdn-content/files/en-us/web/api/gamepadhapticactuator | data/mdn-content/files/en-us/web/api/gamepadhapticactuator/type/index.md | ---
title: "GamepadHapticActuator: type property"
short-title: type
slug: Web/API/GamepadHapticActuator/type
page-type: web-api-instance-property
browser-compat: api.GamepadHapticActuator.type
---
{{APIRef("Gamepad")}}
The **`type`** read-only property of the {{domxref("GamepadHapticActuator")}} interface returns an enum representing the type of the haptic hardware.
## Value
An enum of type [`GamepadHapticActuatorType`](https://w3c.github.io/gamepad/extensions.html#gamepadhapticactuatortype-enum); currently available types are:
- `vibration` — vibration hardware, which creates a rumbling effect.
## Examples
TBC
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Gamepad API](/en-US/docs/Web/API/Gamepad_API)
| 0 |
data/mdn-content/files/en-us/web/api/gamepadhapticactuator | data/mdn-content/files/en-us/web/api/gamepadhapticactuator/playeffect/index.md | ---
title: "GamepadHapticActuator: playEffect() method"
short-title: playEffect()
slug: Web/API/GamepadHapticActuator/playEffect
page-type: web-api-instance-method
status:
- non-standard
browser-compat: api.GamepadHapticActuator.playEffect
---
{{APIRef("Gamepad")}}{{Non-standard_Header}}
The **`playEffect()`** method of the {{domxref("GamepadHapticActuator")}} interface makes the hardware play a specific vibration pattern.
## Syntax
```js-nolint
playEffect(type, params)
```
### Parameters
- `type`
- : A string representing the desired effect. This can vary depending on the hardware type. Possible values are "dual-rumble" or "vibration".
- `params`
- : An object to describe a desired haptic effect.
Expected values are:
- `duration`
- : The duration of the effect in milliseconds.
- `startDelay`
- : The delay in milliseconds before the effect is started.
- `strongMagnitude`
- : Rumble intensity of the low-frequency (strong) rumble motors, normalized to the range between 0.0 and 1.0.
- `weakMagnitude`
- : Rumble intensity of the high-frequency (weak) rumble motors, normalized to the range between 0.0 and 1.0.
> **Note:** A new call to `playEffect()` overrides a previous ongoing call.
### Return value
A promise that resolves with `true` when the playEffect successfully completes.
## Examples
```js
const gamepad = navigator.getGamepads()[0];
gamepad.vibrationActuator.playEffect("dual-rumble", {
startDelay: 0,
duration: 200,
weakMagnitude: 1.0,
strongMagnitude: 1.0,
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Gamepad API](/en-US/docs/Web/API/Gamepad_API)
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/delaynode/index.md | ---
title: DelayNode
slug: Web/API/DelayNode
page-type: web-api-interface
browser-compat: api.DelayNode
---
{{APIRef("Web Audio API")}}
The **`DelayNode`** interface represents a [delay-line](https://en.wikipedia.org/wiki/Digital_delay_line); an {{domxref("AudioNode")}} audio-processing module that causes a delay between the arrival of an input data and its propagation to the output.
A `DelayNode` always has exactly one input and one output, both with the same amount of channels.

When creating a graph that has a cycle, it is mandatory to have at least one `DelayNode` in the cycle, or the nodes taking part in the cycle will be muted.
{{InheritanceDiagram}}
<table class="properties">
<tbody>
<tr>
<th scope="row">Number of inputs</th>
<td><code>1</code></td>
</tr>
<tr>
<th scope="row">Number of outputs</th>
<td><code>1</code></td>
</tr>
<tr>
<th scope="row">Channel count mode</th>
<td><code>"max"</code></td>
</tr>
<tr>
<th scope="row">Channel count</th>
<td><code>2</code> (not used in the default count mode)</td>
</tr>
<tr>
<th scope="row">Channel interpretation</th>
<td><code>"speakers"</code></td>
</tr>
</tbody>
</table>
## Constructor
- {{domxref("DelayNode.DelayNode", "DelayNode()")}}
- : Creates a new instance of an DelayNode object instance. As an alternative, you can use the {{domxref("BaseAudioContext.createDelay()")}} factory method; see [Creating an AudioNode](/en-US/docs/Web/API/AudioNode#creating_an_audionode).
## Instance properties
_Inherits properties from its parent, {{domxref("AudioNode")}}._
- {{domxref("DelayNode.delayTime")}} {{ReadOnlyInline}}
- : An [a-rate](/en-US/docs/Web/API/AudioParam#a-rate) {{domxref("AudioParam")}} representing the amount of delay to apply, specified in seconds.
## Instance methods
_No specific methods; inherits methods from its parent, {{domxref("AudioNode")}}._
## Example
See [`BaseAudioContext.createDelay()`](/en-US/docs/Web/API/BaseAudioContext/createDelay#examples) for example code.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using the Web Audio API](/en-US/docs/Web/API/Web_Audio_API/Using_Web_Audio_API)
| 0 |
data/mdn-content/files/en-us/web/api/delaynode | data/mdn-content/files/en-us/web/api/delaynode/delaytime/index.md | ---
title: "DelayNode: delayTime property"
short-title: delayTime
slug: Web/API/DelayNode/delayTime
page-type: web-api-instance-property
browser-compat: api.DelayNode.delayTime
---
{{ APIRef("Web Audio API") }}
The `delayTime` property of the {{ domxref("DelayNode") }} interface is an [a-rate](/en-US/docs/Web/API/AudioParam#a-rate) {{domxref("AudioParam")}} representing the amount of delay to apply.
`delayTime` is expressed in seconds, its minimal value is `0`, and its maximum value is defined by the `maxDelayTime` argument of the {{domxref("BaseAudioContext.createDelay")}} method that created it.
> **Note:** Though the {{domxref("AudioParam")}} returned is read-only, the value it represents is not.
## Value
An {{domxref("AudioParam")}}.
## Examples
See [`BaseAudioContext.createDelay()`](/en-US/docs/Web/API/BaseAudioContext/createDelay#examples) for example code.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using the Web Audio API](/en-US/docs/Web/API/Web_Audio_API/Using_Web_Audio_API)
| 0 |
data/mdn-content/files/en-us/web/api/delaynode | data/mdn-content/files/en-us/web/api/delaynode/delaynode/index.md | ---
title: "DelayNode: DelayNode() constructor"
short-title: DelayNode()
slug: Web/API/DelayNode/DelayNode
page-type: web-api-constructor
browser-compat: api.DelayNode.DelayNode
---
{{APIRef("Web Audio API")}}
The **`DelayNode()`**
constructor of the [Web Audio API](/en-US/docs/Web/API/Web_Audio_API)
creates a new {{domxref("DelayNode")}} object with a delay-line; an AudioNode
audio-processing module that causes a delay between the arrival of an input data, and
its propagation to the output.
## Syntax
```js-nolint
new DelayNode(context)
new DelayNode(context, options)
```
### Parameters
- `context`
- : A reference to an {{domxref("AudioContext")}} or {{domxref("OfflineAudioContext")}}.
- `options` {{optional_inline}}
- : An object specifying the delay node options. Can contain the following members:
- `delayTime`
- : The initial delay time for the node, in seconds. The
default is `0`.
- `maxDelayTime`
- : The maximum delay time for the node, in seconds.
Defaults to `1`.
- `channelCount`
- : Represents an integer used to determine how many channels are used when [up-mixing and down-mixing](/en-US/docs/Web/API/Web_Audio_API/Basic_concepts_behind_Web_Audio_API#up-mixing_and_down-mixing) connections to any inputs to the node. (See
{{domxref("AudioNode.channelCount")}} for more information.) Its usage and precise
definition depend on the value of `channelCountMode`.
- `channelCountMode`
- : Represents an enumerated value describing the way channels must be matched between
the node's inputs and outputs. (See {{domxref("AudioNode.channelCountMode")}} for more
information including default values.)
- `channelInterpretation`
- : Represents an enumerated value describing the meaning of the channels. This
interpretation will define how audio [up-mixing and down-mixing](/en-US/docs/Web/API/Web_Audio_API/Basic_concepts_behind_Web_Audio_API#up-mixing_and_down-mixing) will happen.
The possible values are `"speakers"` or `"discrete"`. (See
{{domxref("AudioNode.channelCountMode")}} for more information including default
values.)
### Return value
A new {{domxref("DelayNode")}} object instance.
## Examples
```js
const audioCtx = new AudioContext();
const delayNode = new DelayNode(audioCtx, {
delayTime: 0.5,
maxDelayTime: 2,
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/webgl_multi_draw/index.md | ---
title: WEBGL_multi_draw extension
short-title: WEBGL_multi_draw
slug: Web/API/WEBGL_multi_draw
page-type: webgl-extension
browser-compat: api.WEBGL_multi_draw
---
{{APIRef("WebGL")}}
The **`WEBGL_multi_draw`** extension is part of the
[WebGL API](/en-US/docs/Web/API/WebGL_API) and allows to render more
than one primitive with a single function call. This can improve a WebGL application's performance
as it reduces binding costs in the renderer and speeds up GPU thread time with uniform data.
When this extension is enabled:
- New methods that handle multiple lists of arguments in one call are added
(see method list below).
- The `gl_DrawID` built-in is added to the shading language.
> **Note:** This extension is available to both,
> {{domxref("WebGLRenderingContext", "WebGL 1", "", 1)}} and
> {{domxref("WebGL2RenderingContext", "WebGL 2", "", 1)}} contexts.
>
> In shader code, the directive `#extension GL_ANGLE_multi_draw`
> needs to be called to enable the extension.
>
> This extension enables the {{domxref("ANGLE_instanced_arrays")}} extension implicitly.
## Instance methods
- [`ext.multiDrawArraysWEBGL()`](/en-US/docs/Web/API/WEBGL_multi_draw/multiDrawArraysWEBGL)
- : Renders multiple primitives from array data (identical to multiple calls to
[`drawArrays`](/en-US/docs/Web/API/WebGLRenderingContext/drawArrays)).
- [`ext.multiDrawElementsWEBGL()`](/en-US/docs/Web/API/WEBGL_multi_draw/multiDrawElementsWEBGL)
- : Renders multiple primitives from element array data (identical to multiple calls to
[`drawElements`](/en-US/docs/Web/API/WebGLRenderingContext/drawElements)).
- [`ext.multiDrawArraysInstancedWEBGL()`](/en-US/docs/Web/API/WEBGL_multi_draw/multiDrawArraysInstancedWEBGL)
- : Renders multiple primitives from array data (identical to multiple calls to
[`drawArraysInstanced`](/en-US/docs/Web/API/WebGL2RenderingContext/drawArraysInstanced)).
- [`ext.multiDrawElementsInstancedWEBGL()`](/en-US/docs/Web/API/WEBGL_multi_draw/multiDrawElementsInstancedWEBGL)
- : Renders multiple primitives from element array data (identical to multiple calls to
[`drawElementsInstanced`](/en-US/docs/Web/API/WebGL2RenderingContext/drawElementsInstanced)).
## Shader extension
Note: Although the extension name is named `WEBGL_multi_draw`,
the extension must be enabled with the `#extension GL_ANGLE_multi_draw`
directive to use the extension in a shader.
When this extension is enabled, the `gl_DrawID` built-in can be used
in shader code. For any `multi*` draw call variant,
the index of the draw `i` may be read by the vertex shader
as `gl_DrawID`. For non-`multi*` calls, the value of
`gl_DrawID` is `0`.
```html
<script type="x-shader/x-vertex">
#extension GL_ANGLE_multi_draw : require
void main() {
gl_Position = vec4(gl_DrawID, 0, 0, 1);
}
</script>
```
## Examples
### Enabling the extension
WebGL extensions are available using the {{domxref("WebGLRenderingContext.getExtension()")}} method.
For more information, see also [Using Extensions](/en-US/docs/Web/API/WebGL_API/Using_Extensions)
in the [WebGL tutorial](/en-US/docs/Web/API/WebGL_API/Tutorial).
```js
let ext = gl.getExtension("WEBGL_multi_draw");
```
### Drawing multiple arrays
Example calls for [`ext.multiDrawArraysWEBGL()`](/en-US/docs/Web/API/WEBGL_multi_draw/multiDrawArraysWEBGL)
and [`ext.multiDrawArraysInstancedWEBGL()`](/en-US/docs/Web/API/WEBGL_multi_draw/multiDrawArraysInstancedWEBGL):
```js
// multiDrawArrays variant
const firsts = new Int32Array(/* … */);
const counts = new Int32Array(/* … */);
ext.multiDrawArraysWEBGL(gl.TRIANGLES, firsts, 0, counts, 0, firsts.length);
```
```js
// multiDrawArraysInstanced variant
const firsts = new Int32Array(/* … */);
const counts = new Int32Array(/* … */);
const instanceCounts = new Int32Array(/* … */);
ext.multiDrawArraysInstancedWEBGL(
gl.TRIANGLES,
firsts,
0,
counts,
0,
instanceCounts,
0,
firsts.length,
);
```
### Drawing multiple elements
Example calls for [`ext.multiDrawElementsWEBGL()`](/en-US/docs/Web/API/WEBGL_multi_draw/multiDrawElementsWEBGL)
and [`ext.multiDrawElementsInstancedWEBGL()`](/en-US/docs/Web/API/WEBGL_multi_draw/multiDrawElementsInstancedWEBGL).
Assumes that the indices which have been previously uploaded to the
`ELEMENT_ARRAY_BUFFER` are to be treated as `UNSIGNED_SHORT`.
```js
// multiDrawElements variant
const counts = new Int32Array(/* … */);
const offsets = new Int32Array(/* … */);
ext.multiDrawElementsWEBGL(
gl.TRIANGLES,
counts,
0,
gl.UNSIGNED_SHORT,
offsets,
0,
counts.length,
);
```
```js
// multiDrawElementsInstanced variant
const counts = new Int32Array(/* … */);
const offsets = new Int32Array(/* … */);
const instanceCounts = new Int32Array(/* … */);
ext.multiDrawElementsInstancedWEBGL(
gl.TRIANGLES,
counts,
0,
gl.UNSIGNED_SHORT,
offsets,
0,
instanceCounts,
0,
counts.length,
);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("WebGLRenderingContext.drawArrays()")}}
- {{domxref("WebGLRenderingContext.drawElements()")}}
- {{domxref("ANGLE_instanced_arrays.drawArraysInstancedANGLE()")}} or
in WebGL 2: {{domxref("WebGL2RenderingContext.drawArraysInstanced()")}}
- {{domxref("ANGLE_instanced_arrays.drawElementsInstancedANGLE()")}} or
in WebGL 2: {{domxref("WebGL2RenderingContext.drawElementsInstanced()")}}
| 0 |
data/mdn-content/files/en-us/web/api/webgl_multi_draw | data/mdn-content/files/en-us/web/api/webgl_multi_draw/multidrawelementsinstancedwebgl/index.md | ---
title: "WEBGL_multi_draw: multiDrawElementsInstancedWEBGL() method"
short-title: multiDrawElementsInstancedWEBGL()
slug: Web/API/WEBGL_multi_draw/multiDrawElementsInstancedWEBGL
page-type: webgl-extension-method
browser-compat: api.WEBGL_multi_draw.multiDrawElementsInstancedWEBGL
---
{{APIRef("WebGL")}}
The **`WEBGL_multi_draw.multiDrawElementsWEBGL()`** method of
the
[WebGL API](/en-US/docs/Web/API/WebGL_API) renders multiple primitives from
array data. It is
identical to multiple calls to the
[`gl.drawElementsInstanced()`](/en-US/docs/Web/API/WebGL2RenderingContext/drawElementsInstanced)
method.
## Syntax
```js-nolint
multiDrawElementsInstancedWEBGL(mode,
countsList, countsOffset,
type,
firstsList, firstsOffset,
instanceCountsList, instanceCountsOffset,
drawCount);
```
### Parameters
- `mode`
- : A [`GLenum`](/en-US/docs/Web/API/WebGL_API/Types)
specifying the type primitive to render. Possible values are:
- `gl.POINTS`: Draws a single dot.
- `gl.LINE_STRIP`: Draws a straight line to the next vertex.
- `gl.LINE_LOOP`: Draws a straight line to the next vertex, and
connects the
last vertex back to the first.
- `gl.LINES`: Draws a line between a pair of vertices.
- [`gl.TRIANGLE_STRIP`](https://en.wikipedia.org/wiki/Triangle_strip)
- [`gl.TRIANGLE_FAN`](https://en.wikipedia.org/wiki/Triangle_fan)
- `gl.TRIANGLES`: Draws a triangle for a group of three vertices.
- `countsList`
- : An [`Int32Array`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int32Array)
or [`Array`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)
(of [`GLint`](/en-US/docs/Web/API/WebGL_API/Types))
specifying a list of numbers of indices to be rendered.
- `countsOffset`
- : A [`GLUint`](/en-US/docs/Web/API/WebGL_API/Types)
defining the starting point into the `countsList` array.
- type
- : A [`GLenum`](/en-US/docs/Web/API/WebGL_API/Types) specifying
the type of the values in the element array buffer. Possible values are:
- `gl.UNSIGNED_BYTE`
- `gl.UNSIGNED_SHORT`
- When using the [`OES_element_index_uint`](/en-US/docs/Web/API/OES_element_index_uint)
extension:
- `gl.UNSIGNED_INT`
- `offsetsList`
- : An [`Int32Array`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int32Array)
or [`Array`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)
(of [`GLsizei`](/en-US/docs/Web/API/WebGL_API/Types))
specifying a list of starting indices for the arrays of vector points.
- `offsetsOffset`
- : A [`GLuint`](/en-US/docs/Web/API/WebGL_API/Types)
defining the starting point into the `offsetsList` array.
- `instanceCountsList`
- : An [`Int32Array`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int32Array)
or [`Array`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)
(of [`GLsizei`](/en-US/docs/Web/API/WebGL_API/Types))
specifying a list of numbers of instances of the range of elements to execute.
- `instanceCountsOffset`
- : A [`GLuint`](/en-US/docs/Web/API/WebGL_API/Types)
defining the starting point into the `instanceCountsList` array.
- `drawCount`
- : A [`GLsizei`](/en-US/docs/Web/API/WebGL_API/Types)
specifying the number of instances of the range of elements to execute.
### Return value
None.
### Exceptions
- If `mode` is not one of the accepted values, a
`gl.INVALID_ENUM` error is thrown.
- If `drawCount` or items in `countsList`,
`offsetsList`, or `instanceCountsList` are negative,
a `gl.INVALID_VALUE` error is thrown.
## Examples
```js
const counts = new Int32Array(/* … */);
const offsets = new Int32Array(/* … */);
const instanceCounts = new Int32Array(/* … */);
ext.multiDrawElementsInstancedWEBGL(
gl.TRIANGLES,
counts,
0,
gl.UNSIGNED_SHORT,
offsets,
0,
instanceCounts,
0,
counts.length,
);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [`WebGLRenderingContext.drawElements()`](/en-US/docs/Web/API/WebGLRenderingContext/drawElements)
- [`WebGL2RenderingContext.drawElementsInstanced()`](/en-US/docs/Web/API/WebGL2RenderingContext/drawElementsInstanced)
| 0 |
data/mdn-content/files/en-us/web/api/webgl_multi_draw | data/mdn-content/files/en-us/web/api/webgl_multi_draw/multidrawarrayswebgl/index.md | ---
title: "WEBGL_multi_draw: multiDrawArraysWEBGL() method"
short-title: multiDrawArraysWEBGL()
slug: Web/API/WEBGL_multi_draw/multiDrawArraysWEBGL
page-type: webgl-extension-method
browser-compat: api.WEBGL_multi_draw.multiDrawArraysWEBGL
---
{{APIRef("WebGL")}}
The **`WEBGL_multi_draw.multiDrawArraysWEBGL()`** method of the
[WebGL API](/en-US/docs/Web/API/WebGL_API) renders multiple primitives from
array data. It is
identical to multiple calls to the
[`gl.drawArrays()`](/en-US/docs/Web/API/WebGLRenderingContext/drawArrays)
method.
## Syntax
```js-nolint
multiDrawArraysWEBGL(mode,
firstsList, firstsOffset,
countsList, countsOffset,
drawCount);
```
### Parameters
- `mode`
- : A [`GLenum`](/en-US/docs/Web/API/WebGL_API/Types)
specifying the type primitive to render. Possible values are:
- `gl.POINTS`: Draws a single dot.
- `gl.LINE_STRIP`: Draws a straight line to the next vertex.
- `gl.LINE_LOOP`: Draws a straight line to the next vertex, and
connects the
last vertex back to the first.
- `gl.LINES`: Draws a line between a pair of vertices.
- [`gl.TRIANGLE_STRIP`](https://en.wikipedia.org/wiki/Triangle_strip)
- [`gl.TRIANGLE_FAN`](https://en.wikipedia.org/wiki/Triangle_fan)
- `gl.TRIANGLES`: Draws a triangle for a group of three vertices.
- `firstsList`
- : An [`Int32Array`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int32Array)
or [`Array`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)
(of [`GLint`](/en-US/docs/Web/API/WebGL_API/Types))
specifying a list of starting indices for the arrays of vector points.
- `firstsOffset`
- : A [`GLuint`](/en-US/docs/Web/API/WebGL_API/Types)
defining the starting point into the `firstsLists` array.
- `countsList`
- : An [`Int32Array`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int32Array)
or [`Array`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)
(of [`GLsizei`](/en-US/docs/Web/API/WebGL_API/Types))
specifying a list of numbers of indices to be rendered.
- `countsOffset`
- : A [`GLuint`](/en-US/docs/Web/API/WebGL_API/Types)
defining the starting point into the `countsList` array.
- `drawCount`
- : A [`GLsizei`](/en-US/docs/Web/API/WebGL_API/Types)
specifying the number of instances of the range of elements to execute.
### Return value
None.
### Exceptions
- If `mode` is not one of the accepted values, a
`gl.INVALID_ENUM` error is thrown.
- If `drawCount` or items in `firstsList` and
`countsList` are negative,
a `gl.INVALID_VALUE` error is thrown.
- if `gl.CURRENT_PROGRAM` is
[`null`](/en-US/docs/Web/JavaScript/Reference/Operators/null),
a `gl.INVALID_OPERATION` error is thrown.
## Examples
```js
const firsts = new Int32Array(/* … */);
const counts = new Int32Array(/* … */);
ext.multiDrawArraysWEBGL(gl.TRIANGLES, firsts, 0, counts, 0, firsts.length);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [`WebGLRenderingContext.drawArrays()`](/en-US/docs/Web/API/WebGLRenderingContext/drawArrays)
- [`WebGL2RenderingContext.drawArraysInstanced()`](/en-US/docs/Web/API/WebGL2RenderingContext/drawArraysInstanced)
| 0 |
data/mdn-content/files/en-us/web/api/webgl_multi_draw | data/mdn-content/files/en-us/web/api/webgl_multi_draw/multidrawarraysinstancedwebgl/index.md | ---
title: "WEBGL_multi_draw: multiDrawArraysInstancedWEBGL() method"
short-title: multiDrawArraysInstancedWEBGL()
slug: Web/API/WEBGL_multi_draw/multiDrawArraysInstancedWEBGL
page-type: webgl-extension-method
browser-compat: api.WEBGL_multi_draw.multiDrawArraysInstancedWEBGL
---
{{APIRef("WebGL")}}
The **`WEBGL_multi_draw.multiDrawArraysInstancedWEBGL()`**
method of the
[WebGL API](/en-US/docs/Web/API/WebGL_API) renders multiple primitives from
array data. It is
identical to multiple calls to the
[`gl.drawArraysInstanced()`](/en-US/docs/Web/API/WebGL2RenderingContext/drawArraysInstanced)
method.
## Syntax
```js-nolint
multiDrawArraysInstancedWEBGL(mode,
firstsList, firstsOffset,
countsList, countsOffset,
instanceCountsList, instanceCountsOffset,
drawCount);
```
### Parameters
- `mode`
- : A [`GLenum`](/en-US/docs/Web/API/WebGL_API/Types)
specifying the type primitive to render. Possible values are:
- `gl.POINTS`: Draws a single dot.
- `gl.LINE_STRIP`: Draws a straight line to the next vertex.
- `gl.LINE_LOOP`: Draws a straight line to the next vertex, and
connects the
last vertex back to the first.
- `gl.LINES`: Draws a line between a pair of vertices.
- [`gl.TRIANGLE_STRIP`](https://en.wikipedia.org/wiki/Triangle_strip)
- [`gl.TRIANGLE_FAN`](https://en.wikipedia.org/wiki/Triangle_fan)
- `gl.TRIANGLES`: Draws a triangle for a group of three vertices.
- `firstsList`
- : An [`Int32Array`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int32Array)
or [`Array`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)
(of [`GLint`](/en-US/docs/Web/API/WebGL_API/Types))
specifying a list of starting indices for the arrays of vector points.
- `firstsOffset`
- : A [`GLuint`](/en-US/docs/Web/API/WebGL_API/Types)
defining the starting point into the `firstsLists` array.
- `countsList`
- : An [`Int32Array`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int32Array)
or [`Array`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)
(of [`GLsizei`](/en-US/docs/Web/API/WebGL_API/Types))
specifying a list of numbers of indices to be rendered.
- `countsOffset`
- : A [`GLuint`](/en-US/docs/Web/API/WebGL_API/Types)
defining the starting point into the `countsList` array.
- `instanceCountsList`
- : An [`Int32Array`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int32Array)
or [`Array`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)
(of [`GLsizei`](/en-US/docs/Web/API/WebGL_API/Types))
specifying a list of numbers of instances of the range of elements to execute.
- `instanceCountsOffset`
- : A [`GLuint`](/en-US/docs/Web/API/WebGL_API/Types)
defining the starting point into the `instanceCountsList` array.
- `drawCount`
- : A [`GLsizei`](/en-US/docs/Web/API/WebGL_API/Types)
specifying the number of instances of the range of elements to execute.
### Return value
None.
### Exceptions
- If `mode` is not one of the accepted values, a
`gl.INVALID_ENUM` error is thrown.
- If `drawCount` or items in `firstsList`,
`countsList`, or `instanceCountsList` are negative,
a `gl.INVALID_VALUE` error is thrown.
- if `gl.CURRENT_PROGRAM` is
[`null`](/en-US/docs/Web/JavaScript/Reference/Operators/null),
a `gl.INVALID_OPERATION` error is thrown.
## Examples
```js
const firsts = new Int32Array(/* … */);
const counts = new Int32Array(/* … */);
const instanceCounts = new Int32Array(/* … */);
ext.multiDrawArraysInstancedWEBGL(
gl.TRIANGLES,
firsts,
0,
counts,
0,
instanceCounts,
0,
firsts.length,
);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [`WebGLRenderingContext.drawArrays()`](/en-US/docs/Web/API/WebGLRenderingContext/drawArrays)
- [`WebGL2RenderingContext.drawArraysInstanced()`](/en-US/docs/Web/API/WebGL2RenderingContext/drawArraysInstanced)
| 0 |
data/mdn-content/files/en-us/web/api/webgl_multi_draw | data/mdn-content/files/en-us/web/api/webgl_multi_draw/multidrawelementswebgl/index.md | ---
title: "WEBGL_multi_draw: multiDrawElementsWEBGL() method"
short-title: multiDrawElementsWEBGL()
slug: Web/API/WEBGL_multi_draw/multiDrawElementsWEBGL
page-type: webgl-extension-method
browser-compat: api.WEBGL_multi_draw.multiDrawElementsWEBGL
---
{{APIRef("WebGL")}}
The **`WEBGL_multi_draw.multiDrawElementsWEBGL()`** method of
the
[WebGL API](/en-US/docs/Web/API/WebGL_API) renders multiple primitives from
array data. It is
identical to multiple calls to the
[`gl.drawElements()`](/en-US/docs/Web/API/WebGLRenderingContext/drawElements)
method.
## Syntax
```js-nolint
multiDrawElementsWEBGL(mode,
countsList, countsOffset,
type,
firstsList, firstsOffset,
drawCount);
```
### Parameters
- `mode`
- : A [`GLenum`](/en-US/docs/Web/API/WebGL_API/Types)
specifying the type primitive to render. Possible values are:
- `gl.POINTS`: Draws a single dot.
- `gl.LINE_STRIP`: Draws a straight line to the next vertex.
- `gl.LINE_LOOP`: Draws a straight line to the next vertex, and
connects the
last vertex back to the first.
- `gl.LINES`: Draws a line between a pair of vertices.
- [`gl.TRIANGLE_STRIP`](https://en.wikipedia.org/wiki/Triangle_strip)
- [`gl.TRIANGLE_FAN`](https://en.wikipedia.org/wiki/Triangle_fan)
- `gl.TRIANGLES`: Draws a triangle for a group of three vertices.
- `countsList`
- : An [`Int32Array`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int32Array)
or [`Array`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)
(of [`GLint`](/en-US/docs/Web/API/WebGL_API/Types))
specifying a list of numbers of indices to be rendered.
- `countsOffset`
- : A [`GLUint`](/en-US/docs/Web/API/WebGL_API/Types)
defining the starting point into the `countsList` array.
- type
- : A [`GLenum`](/en-US/docs/Web/API/WebGL_API/Types) specifying
the type of the values in the element array buffer. Possible values are:
- `gl.UNSIGNED_BYTE`
- `gl.UNSIGNED_SHORT`
- When using the [`OES_element_index_uint`](/en-US/docs/Web/API/OES_element_index_uint)
extension:
- `gl.UNSIGNED_INT`
- `offsetsList`
- : An [`Int32Array`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int32Array)
or [`Array`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)
(of [`GLsizei`](/en-US/docs/Web/API/WebGL_API/Types))
specifying a list of starting indices for the arrays of vector points.
- `offsetsOffset`
- : A [`GLuint`](/en-US/docs/Web/API/WebGL_API/Types)
defining the starting point into the `offsetsList` array.
- `drawCount`
- : A [`GLsizei`](/en-US/docs/Web/API/WebGL_API/Types)
specifying the number of instances of the range of elements to execute.
### Return value
None.
### Exceptions
- If `mode` is not one of the accepted values, a
`gl.INVALID_ENUM` error is thrown.
- If `drawCount` or items in `countsList` or
`offsetsList` are negative,
a `gl.INVALID_VALUE` error is thrown.
## Examples
```js
const counts = new Int32Array(/* … */);
const offsets = new Int32Array(/* … */);
ext.multiDrawElementsWEBGL(
gl.TRIANGLES,
counts,
0,
gl.UNSIGNED_SHORT,
offsets,
0,
counts.length,
);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [`WebGLRenderingContext.drawElements()`](/en-US/docs/Web/API/WebGLRenderingContext/drawElements)
- [`WebGL2RenderingContext.drawElementsInstanced()`](/en-US/docs/Web/API/WebGL2RenderingContext/drawElementsInstanced)
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/animationevent/index.md | ---
title: AnimationEvent
slug: Web/API/AnimationEvent
page-type: web-api-interface
browser-compat: api.AnimationEvent
---
{{APIRef("Web Animations")}}
The **`AnimationEvent`** interface represents events providing information related to [animations](/en-US/docs/Web/CSS/CSS_animations/Using_CSS_animations).
{{InheritanceDiagram}}
## Constructor
- {{domxref("AnimationEvent.AnimationEvent", "AnimationEvent()")}}
- : Creates an `AnimationEvent` event with the given parameters.
## Instance properties
_Also inherits properties from its parent {{domxref("Event")}}_.
- {{domxref("AnimationEvent.animationName")}} {{ReadOnlyInline}}
- : A string containing the value of the {{cssxref("animation-name")}} that generated the animation.
- {{domxref("AnimationEvent.elapsedTime")}} {{ReadOnlyInline}}
- : A `float` giving the amount of time the animation has been running, in seconds, when this event fired, excluding any time the animation was paused. For an `animationstart` event, `elapsedTime` is `0.0` unless there was a negative value for {{cssxref("animation-delay")}}, in which case the event will be fired with `elapsedTime` containing `(-1 * delay)`.
- {{domxref("AnimationEvent.pseudoElement")}} {{ReadOnlyInline}}
- : A string, starting with `'::'`, containing the name of the [pseudo-element](/en-US/docs/Web/CSS/Pseudo-elements) the animation runs on. If the animation doesn't run on a pseudo-element but on the element, an empty string: `''`.
## Instance methods
_Inherits methods from its parent, {{domxref("Event")}}_.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using CSS animations](/en-US/docs/Web/CSS/CSS_animations/Using_CSS_animations)
- Animation-related CSS properties and at-rules: {{cssxref("animation")}}, {{cssxref("animation-composition")}}, {{cssxref("animation-delay")}}, {{cssxref("animation-direction")}}, {{cssxref("animation-duration")}}, {{cssxref("animation-fill-mode")}}, {{cssxref("animation-iteration-count")}}, {{cssxref("animation-name")}}, {{cssxref("animation-play-state")}}, {{cssxref("animation-timing-function")}}, {{cssxref("@keyframes")}}.
| 0 |
data/mdn-content/files/en-us/web/api/animationevent | data/mdn-content/files/en-us/web/api/animationevent/elapsedtime/index.md | ---
title: "AnimationEvent: elapsedTime property"
short-title: elapsedTime
slug: Web/API/AnimationEvent/elapsedTime
page-type: web-api-instance-property
browser-compat: api.AnimationEvent.elapsedTime
---
{{APIRef("Web Animations")}}
The **`AnimationEvent.elapsedTime`** read-only property is a
`float` giving the amount of time the animation has been running, in seconds,
when this event fired, excluding any time the animation was paused. For an
{{domxref("Element/animationstart_event", "animationstart")}} event,
`elapsedTime` is `0.0` unless there was a negative value for
{{cssxref("animation-delay")}}, in which case the event will be fired with
`elapsedTime` containing `(-1 * delay)`.
## Value
A `float` giving the amount of time in seconds.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using CSS animations](/en-US/docs/Web/CSS/CSS_animations/Using_CSS_animations)
- Animation-related CSS properties and at-rules: {{cssxref("animation")}},
{{cssxref("animation-delay")}}, {{cssxref("animation-direction")}},
{{cssxref("animation-duration")}}, {{cssxref("animation-fill-mode")}},
{{cssxref("animation-iteration-count")}}, {{cssxref("animation-name")}},
{{cssxref("animation-play-state")}}, {{cssxref("animation-timing-function")}},
{{cssxref("@keyframes")}}.
- The {{domxref("AnimationEvent")}} interface it belongs to.
| 0 |
data/mdn-content/files/en-us/web/api/animationevent | data/mdn-content/files/en-us/web/api/animationevent/animationevent/index.md | ---
title: "AnimationEvent: AnimationEvent() constructor"
short-title: AnimationEvent()
slug: Web/API/AnimationEvent/AnimationEvent
page-type: web-api-constructor
browser-compat: api.AnimationEvent.AnimationEvent
---
{{APIRef("Web Animations")}}
The **`AnimationEvent()`** constructor returns a new {{domxref("AnimationEvent")}} object, representing an event in relation with an animation.
## Syntax
```js-nolint
new AnimationEvent(type)
new AnimationEvent(type, options)
```
### Parameters
- `type`
- : A string with the name of the type of the `AnimationEvent`.
It is case-sensitive and browsers set it to `animationstart`, `animationend`, or `animationiteration`.
- `options` {{optional_inline}}
- : An object that, _in addition of the properties defined in {{domxref("Event/Event", "Event()")}}_, has the following properties:
- `animationName` {{optional_inline}}
- : A string containing the value of the {{cssxref("animation-name")}} CSS property associated with the transition. It defaults to `""`.
- `elapsedTime` {{optional_inline}}
- : A `float` giving the amount of time the animation has been running, in seconds, when this event fired, excluding any time the animation was paused.
For an `animationstart` event, `elapsedTime` is `0.0` unless there was a negative value for {{cssxref("animation-delay")}},
in which case the event will be fired with `elapsedTime` containing `(-1 * delay)`. It defaults to `0.0`.
- `pseudoElement` {{optional_inline}}
- : A string, starting with `"::"`, containing the name of the [pseudo-element](/en-US/docs/Web/CSS/Pseudo-elements) the animation runs on. If the animation doesn't run on a pseudo-element but on the element itself, specify an empty string: `""`. It defaults to `""`.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using CSS animations](/en-US/docs/Web/CSS/CSS_animations/Using_CSS_animations)
- Animation-related CSS properties and at-rules: {{cssxref("animation")}},
{{cssxref("animation-delay")}}, {{cssxref("animation-direction")}},
{{cssxref("animation-duration")}}, {{cssxref("animation-fill-mode")}},
{{cssxref("animation-iteration-count")}}, {{cssxref("animation-name")}},
{{cssxref("animation-play-state")}}, {{cssxref("animation-timing-function")}},
{{cssxref("@keyframes")}}
- The {{domxref("AnimationEvent")}} interface it belongs to.
| 0 |
data/mdn-content/files/en-us/web/api/animationevent | data/mdn-content/files/en-us/web/api/animationevent/animationname/index.md | ---
title: "AnimationEvent: animationName property"
short-title: animationName
slug: Web/API/AnimationEvent/animationName
page-type: web-api-instance-property
browser-compat: api.AnimationEvent.animationName
---
{{APIRef("Web Animations")}}
The **`AnimationEvent.animationName`** read-only property is a
string containing the value of the {{cssxref("animation-name")}} CSS
property associated with the transition.
## Value
A string containing the value of the {{cssxref("animation-name")}} CSS property.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using CSS animations](/en-US/docs/Web/CSS/CSS_animations/Using_CSS_animations)
- Animation-related CSS properties and at-rules: {{cssxref("animation")}},
{{cssxref("animation-delay")}}, {{cssxref("animation-direction")}},
{{cssxref("animation-duration")}}, {{cssxref("animation-fill-mode")}},
{{cssxref("animation-iteration-count")}}, {{cssxref("animation-name")}},
{{cssxref("animation-play-state")}}, {{cssxref("animation-timing-function")}},
{{cssxref("@keyframes")}}.
- The {{domxref("AnimationEvent")}} interface it belongs to.
| 0 |
data/mdn-content/files/en-us/web/api/animationevent | data/mdn-content/files/en-us/web/api/animationevent/pseudoelement/index.md | ---
title: "AnimationEvent: pseudoElement property"
short-title: pseudoElement
slug: Web/API/AnimationEvent/pseudoElement
page-type: web-api-instance-property
browser-compat: api.AnimationEvent.pseudoElement
---
{{APIRef("Web Animations")}}
The **`AnimationEvent.pseudoElement`** read-only property is a
string, starting with `'::'`, containing the name of the [pseudo-element](/en-US/docs/Web/CSS/Pseudo-elements) the animation runs on.
If the animation doesn't run on a pseudo-element but on the element, an empty string: `''`.
## Value
A string, starting with `'::'`, containing the name of the [pseudo-element](/en-US/docs/Web/CSS/Pseudo-elements) the animation runs on.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using CSS animations](/en-US/docs/Web/CSS/CSS_animations/Using_CSS_animations)
- Animation-related CSS properties and at-rules: {{cssxref("animation")}},
{{cssxref("animation-delay")}}, {{cssxref("animation-direction")}},
{{cssxref("animation-duration")}}, {{cssxref("animation-fill-mode")}},
{{cssxref("animation-iteration-count")}}, {{cssxref("animation-name")}},
{{cssxref("animation-play-state")}}, {{cssxref("animation-timing-function")}},
{{cssxref("@keyframes")}}.
- The {{domxref("AnimationEvent")}} interface it belongs to.
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/cssunitvalue/index.md | ---
title: CSSUnitValue
slug: Web/API/CSSUnitValue
page-type: web-api-interface
browser-compat: api.CSSUnitValue
---
{{APIRef("CSS Typed Object Model API")}}
The **`CSSUnitValue`** interface of the {{domxref('CSS_Object_Model#css_typed_object_model','','',' ')}} represents values that contain a single unit type. For example, "42px" would be represented by a `CSSNumericValue`.
{{InheritanceDiagram}}
## Constructor
- {{domxref("CSSUnitValue.CSSUnitValue", "CSSUnitValue()")}}
- : Creates a new `CSSUnitValue` object.
## Instance properties
- {{domxref('CSSUnitValue.value')}}
- : Returns a double indicating the number of units.
- {{domxref('CSSUnitValue.unit')}}
- : Returns a string indicating the type of unit.
## Static methods
_The interface may also inherit methods from its parent interface, {{domxref("CSSNumericValue")}}._
## Instance methods
_The interface may also inherit methods from its parent interface, {{domxref("CSSNumericValue")}}._
## Examples
The following shows a method of creating a {{domxref('CSSPositionValue')}} from individual `CSSUnitValue` constructors.
```js
let pos = new CSSPositionValue(
new CSSUnitValue(5, "px"),
new CSSUnitValue(10, "px"),
);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/cssunitvalue | data/mdn-content/files/en-us/web/api/cssunitvalue/value/index.md | ---
title: "CSSUnitValue: value property"
short-title: value
slug: Web/API/CSSUnitValue/value
page-type: web-api-instance-property
browser-compat: api.CSSUnitValue.value
---
{{APIRef("CSS Typed Object Model API")}}
The **`CSSUnitValue.value`** property of the
{{domxref("CSSUnitValue")}} interface returns a double indicating the number of units.
## Value
A double.
## Examples
The following creates a {{domxref('CSSPositionValue')}} from individual
`CSSUnitValue` constructors, then queries the
`CSSUnitValue.value`.
```js
const pos = new CSSPositionValue(
new CSSUnitValue(5, "px"),
new CSSUnitValue(10, "px"),
);
console.log(pos.x.value); // 5
console.log(pos.y.value); // 10
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref('CSSUnitValue.unit')}}
- [Using the CSS Typed OM](/en-US/docs/Web/API/CSS_Typed_OM_API/Guide)
- [CSS Typed Object Model API](/en-US/docs/Web/API/CSS_Typed_OM_API)
| 0 |
data/mdn-content/files/en-us/web/api/cssunitvalue | data/mdn-content/files/en-us/web/api/cssunitvalue/cssunitvalue/index.md | ---
title: "CSSUnitValue: CSSUnitValue() constructor"
short-title: CSSUnitValue()
slug: Web/API/CSSUnitValue/CSSUnitValue
page-type: web-api-constructor
browser-compat: api.CSSUnitValue.CSSUnitValue
---
{{APIRef("CSS Typed Object Model API")}}
The **`CSSUnitValue()`** constructor creates a
new {{domxref("CSSUnitValue")}} object which returns a new {{domxref('CSSUnitValue')}}
object which represents values that contain a single unit type. For example, "42px"
would be represented by a `CSSNumericValue`.
## Syntax
```js-nolint
new CSSUnitValue()
```
### Parameters
- `value`
- : Returns a double indicating the number of units.
- `unit`
- : Returns a string indicating the type of unit.
## Examples
The following shows a method of creating a {{domxref('CSSPositionValue')}} from
individual `CSSUnitValue` constructors.
```js
let pos = new CSSPositionValue(
new CSSUnitValue(5, "px"),
new CSSUnitValue(10, "px"),
);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref('CSSUnitValue.unit')}}
- {{domxref('CSSUnitValue.value')}}
- [Using the CSS Typed OM](/en-US/docs/Web/API/CSS_Typed_OM_API/Guide)
- [CSS Typed Object Model API](/en-US/docs/Web/API/CSS_Typed_OM_API)
| 0 |
data/mdn-content/files/en-us/web/api/cssunitvalue | data/mdn-content/files/en-us/web/api/cssunitvalue/unit/index.md | ---
title: "CSSUnitValue: unit property"
short-title: unit
slug: Web/API/CSSUnitValue/unit
page-type: web-api-instance-property
browser-compat: api.CSSUnitValue.unit
---
{{APIRef("CSS Typed Object Model API")}}
The **`CSSUnitValue.unit`** read-only property
of the {{domxref("CSSUnitValue")}} interface returns a string
indicating the type of unit.
## Value
A string.
## Examples
The following creates a {{domxref('CSSPositionValue')}} from individual
`CSSUnitValue` constructors, then queries the
`CSSUnitValue.unit`.
```js
const pos = new CSSPositionValue(
new CSSUnitValue(5, "px"),
new CSSUnitValue(10, "em"),
);
console.log(pos.x.unit); // "px"
console.log(pos.y.unit); // "em"
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref('CSSUnitValue.value')}}
- [Dimensions in CSS units and values](/en-US/docs/Web/CSS/CSS_Values_and_Units#dimensions)
- [Using the CSS Typed OM](/en-US/docs/Web/API/CSS_Typed_OM_API/Guide)
- [CSS Typed Object Model API](/en-US/docs/Web/API/CSS_Typed_OM_API)
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/xrlightestimate/index.md | ---
title: XRLightEstimate
slug: Web/API/XRLightEstimate
page-type: web-api-interface
status:
- experimental
browser-compat: api.XRLightEstimate
---
{{APIRef("WebXR Device API")}} {{secureContext_header}}{{SeeCompatTable}}
The **`XRLightEstimate`** interface of the [WebXR Device API](/en-US/docs/Web/API/WebXR_Device_API) provides the estimated lighting values for an {{domxref("XRLightProbe")}} at the time represented by an {{domxref("XRFrame")}}.
To get an `XRLightEstimate` object, call the {{domxref("XRFrame.getLightEstimate()")}} method.
## Instance properties
- {{domxref("XRLightEstimate.primaryLightDirection")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : A {{domxref("DOMPointReadOnly")}} representing the direction to the primary light source from the `probeSpace` of an {{domxref("XRLightProbe")}}.
- {{domxref("XRLightEstimate.primaryLightIntensity")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : A {{domxref("DOMPointReadOnly")}} (with the `x`, `y`, `z` values mapped to RGB) representing the intensity of the primary light source from the `probeSpace` of an {{domxref("XRLightProbe")}}.
- {{domxref("XRLightEstimate.sphericalHarmonicsCoefficients")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : A {{jsxref("Float32Array")}} containing 9 spherical harmonics coefficients.
## Instance methods
None.
## Examples
### Getting an `XRLightProbe` object
First, use the {{domxref("XRSession.requestLightProbe()")}} method to get a light probe from a session.
Then, within an {{domxref("XRFrame")}} loop, the {{domxref("XRFrame.getLightEstimate", "getLightEstimate()")}} method will return a `XRLightEstimate` object containing the lighting values for each frame.
```js
const lightProbe = await xrSession.requestLightProbe();
// frame loop
function onXRFrame(time, xrFrame) {
let lightEstimate = xrFrame.getLightEstimate(lightProbe);
// Use light estimate data to light the scene
// Available properties
lightEstimate.sphericalHarmonicsCoefficients;
lightEstimate.primaryLightDirection;
lightEstimate.primaryLightIntensity;
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("XRFrame.getLightEstimate()")}}
| 0 |
data/mdn-content/files/en-us/web/api/xrlightestimate | data/mdn-content/files/en-us/web/api/xrlightestimate/sphericalharmonicscoefficients/index.md | ---
title: "XRLightEstimate: sphericalHarmonicsCoefficients property"
short-title: sphericalHarmonicsCoefficients
slug: Web/API/XRLightEstimate/sphericalHarmonicsCoefficients
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.XRLightEstimate.sphericalHarmonicsCoefficients
---
{{APIRef("WebXR Device API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The _read-only_ **`sphericalHarmonicsCoefficients`** property of the {{DOMxRef("XRLightEstimate")}} interface returns a {{jsxref("Float32Array")}} containing 9 spherical harmonics coefficients.
Spherical harmonic lighting is a technique that uses spherical functions instead of standard lighting equations. See [Wikipedia](https://en.wikipedia.org/wiki/Spherical_harmonic_lighting) for more information.
## Value
A {{jsxref("Float32Array")}} containing 9 spherical harmonics coefficients. The array contains 27 elements in total, with every 3 elements defining red, green, and blue components for each coefficient.
The first 3 elements must be a valid lighting estimate component; the rest may be 0 due to privacy settings or limitations of the device to provide more data.
## Examples
Within an {{domxref("XRFrame")}} loop, you can use the `sphericalHarmonicsCoefficients` property to light the scene.
```js
const lightProbe = await xrSession.requestLightProbe();
// frame loop
function onXRFrame(time, xrFrame) {
let lightEstimate = xrFrame.getLightEstimate(lightProbe);
// Render lights using lightEstimate.sphericalHarmonicsCoefficients
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("XRFrame.getLightEstimate()")}}
| 0 |
data/mdn-content/files/en-us/web/api/xrlightestimate | data/mdn-content/files/en-us/web/api/xrlightestimate/primarylightdirection/index.md | ---
title: "XRLightEstimate: primaryLightDirection property"
short-title: primaryLightDirection
slug: Web/API/XRLightEstimate/primaryLightDirection
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.XRLightEstimate.primaryLightDirection
---
{{APIRef("WebXR Device API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The _read-only_ **`primaryLightDirection`** property of the {{DOMxRef("XRLightEstimate")}} interface returns a {{domxref("DOMPointReadOnly")}} representing the direction to the primary light source from the `probeSpace` of an {{domxref("XRLightProbe")}}.
## Value
A {{domxref("DOMPointReadOnly")}} object. If no estimated values from the user's environment are available, the point will be `{ x: 0.0, y: 1.0, z: 0.0, w: 0.0 }`, representing a light shining straight down from above.
## Examples
Within an {{domxref("XRFrame")}} loop, you can use the `primaryLightDirection` and `primaryLightIntensity` properties
to render shadows based on the most prominent light source, for example.
```js
const lightProbe = await xrSession.requestLightProbe();
// frame loop
function onXRFrame(time, xrFrame) {
let lightEstimate = xrFrame.getLightEstimate(lightProbe);
// Render lights
// Available properties
lightEstimate.primaryLightDirection;
lightEstimate.primaryLightIntensity;
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("XRLightEstimate.primaryLightIntensity")}}
- {{domxref("XRLightProbe.probeSpace")}}
| 0 |
data/mdn-content/files/en-us/web/api/xrlightestimate | data/mdn-content/files/en-us/web/api/xrlightestimate/primarylightintensity/index.md | ---
title: "XRLightEstimate: primaryLightIntensity property"
short-title: primaryLightIntensity
slug: Web/API/XRLightEstimate/primaryLightIntensity
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.XRLightEstimate.primaryLightIntensity
---
{{APIRef("WebXR Device API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The _read-only_ **`primaryLightIntensity`** property of the {{DOMxRef("XRLightEstimate")}} interface returns a {{domxref("DOMPointReadOnly")}} representing the intensity of the primary light source from the `probeSpace` of an {{domxref("XRLightProbe")}}.
## Value
A {{domxref("DOMPointReadOnly")}} object where an RGB value is mapped to the `x`, `y`, and `z` values. The `w` value is always `1.0`. If no estimated values from the user's environment are available, the point will be `{x: 0.0, y: 0.0, z: 0.0, w: 1.0}`, representing no illumination.
## Examples
Within an {{domxref("XRFrame")}} loop, you can use the `primaryLightDirection` and `primaryLightIntensity` properties
to render shadows based on the most prominent light source, for example.
```js
const lightProbe = await xrSession.requestLightProbe();
// frame loop
function onXRFrame(time, xrFrame) {
let lightEstimate = xrFrame.getLightEstimate(lightProbe);
// Render lights
// Available properties
lightEstimate.primaryLightDirection;
lightEstimate.primaryLightIntensity;
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("XRLightEstimate.primaryLightDirection")}}
- {{domxref("XRLightProbe.probeSpace")}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/svglineargradientelement/index.md | ---
title: SVGLinearGradientElement
slug: Web/API/SVGLinearGradientElement
page-type: web-api-interface
browser-compat: api.SVGLinearGradientElement
---
{{APIRef("SVG")}}
The **`SVGLinearGradientElement`** interface corresponds to the {{SVGElement("linearGradient")}} element.
{{InheritanceDiagram}}
## Instance properties
_This interface also inherits properties from its parent, {{domxref("SVGGradientElement")}}._
- {{domxref("SVGLinearGradientElement.x1")}} {{ReadOnlyInline}}
- : An {{domxref("SVGAnimatedLength")}} corresponding to the {{SVGAttr("x1")}} attribute of the given {{SVGElement("linearGradient")}} element.
- {{domxref("SVGLinearGradientElement.y1")}} {{ReadOnlyInline}}
- : An {{domxref("SVGAnimatedLength")}} corresponding to the {{SVGAttr("y1")}} attribute of the given {{SVGElement("linearGradient")}} element.
- {{domxref("SVGLinearGradientElement.x2")}} {{ReadOnlyInline}}
- : An {{domxref("SVGAnimatedLength")}} corresponding to the {{SVGAttr("x2")}} attribute of the given {{SVGElement("linearGradient")}} element.
- {{domxref("SVGLinearGradientElement.y2")}} {{ReadOnlyInline}}
- : An {{domxref("SVGAnimatedLength")}} corresponding to the {{SVGAttr("y2")}} attribute of the given {{SVGElement("linearGradient")}} element.
## Instance methods
_This interface doesn't implement any specific methods, but inherits methods from its parent interface, {{domxref("SVGGradientElement")}}._
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/touch_events/index.md | ---
title: Touch events
slug: Web/API/Touch_events
page-type: web-api-overview
browser-compat:
- api.Touch
- api.TouchEvent
- api.TouchList
spec-urls: https://w3c.github.io/touch-events/
---
{{DefaultAPISidebar("Touch Events")}}
To provide quality support for touch-based user interfaces, touch events offer the ability to interpret finger (or stylus) activity on touch screens or trackpads.
The touch events interfaces are relatively low-level APIs that can be used to support application-specific multi-touch interactions such as a two-finger gesture. A multi-touch interaction starts when a finger (or stylus) first touches the contact surface. Other fingers may subsequently touch the surface and optionally move across the touch surface. The interaction ends when the fingers are removed from the surface. During this interaction, an application receives touch events during the start, move, and end phases.
Touch events are similar to mouse events except they support simultaneous touches and at different locations on the touch surface. The {{domxref("TouchEvent")}} interface encapsulates all of the touchpoints that are currently active. The {{domxref("Touch")}} interface, which represents a single touchpoint, includes information such as the position of the touch point relative to the browser viewport.
## Definitions
- Surface
- : The touch-sensitive surface. This may be a screen or trackpad.
- Touch point
- : A point of contact with the surface. This may be a finger (or elbow, ear, nose, whatever, but typically a finger) or stylus.
## Interfaces
- {{domxref("TouchEvent")}}
- : Represents an event that occurs when the state of touches on the surface changes.
- {{domxref("Touch")}}
- : Represents a single point of contact between the user and the touch surface.
- {{domxref("TouchList")}}
- : Represents a group of touches; this is used when the user has, for example, multiple fingers on the surface at the same time.
## Example
This example tracks multiple touchpoints at a time, allowing the user to draw in a {{HTMLElement("canvas")}} with more than one finger at a time. It will only work on a browser that supports touch events.
> **Note:** The text below uses the term "finger" when describing the contact with the surface, but it could, of course, also be a stylus or other contact method.
### Create a canvas
```html
<canvas id="canvas" width="600" height="600" style="border:solid black 1px;">
Your browser does not support canvas element.
</canvas>
<br />
Log:
<pre id="log" style="border: 1px solid #ccc;"></pre>
```
```css
#log {
height: 200px;
width: 600px;
overflow: scroll;
}
```
### Setting up the event handlers
When the page loads, the `startup()` function shown below will be called.
This sets up all the event listeners for our {{HTMLElement("canvas")}} element so we can handle the touch events as they occur.
```js
function startup() {
const el = document.getElementById("canvas");
el.addEventListener("touchstart", handleStart);
el.addEventListener("touchend", handleEnd);
el.addEventListener("touchcancel", handleCancel);
el.addEventListener("touchmove", handleMove);
log("Initialized.");
}
document.addEventListener("DOMContentLoaded", startup);
```
#### Tracking new touches
We'll keep track of the touches in-progress.
```js
const ongoingTouches = [];
```
When a {{domxref("Element/touchstart_event", "touchstart")}} event occurs, indicating that a new touch on the surface has occurred, the `handleStart()` function below is called.
```js
function handleStart(evt) {
evt.preventDefault();
log("touchstart.");
const el = document.getElementById("canvas");
const ctx = el.getContext("2d");
const touches = evt.changedTouches;
for (let i = 0; i < touches.length; i++) {
log(`touchstart: ${i}.`);
ongoingTouches.push(copyTouch(touches[i]));
const color = colorForTouch(touches[i]);
log(`color of touch with id ${touches[i].identifier} = ${color}`);
ctx.beginPath();
ctx.arc(touches[i].pageX, touches[i].pageY, 4, 0, 2 * Math.PI, false); // a circle at the start
ctx.fillStyle = color;
ctx.fill();
}
}
```
This calls {{domxref("event.preventDefault()")}} to keep the browser from continuing to process the touch event (this also prevents a mouse event from also being delivered). Then we get the context and pull the list of changed touch points out of the event's {{domxref("TouchEvent.changedTouches")}} property.
After that, we iterate over all the {{domxref("Touch")}} objects in the list, pushing them onto an array of active touchpoints and drawing the start point for the draw as a small circle; we're using a 4-pixel wide line, so a 4-pixel radius circle will show up neatly.
#### Drawing as the touches move
Each time one or more fingers move, a {{domxref("Element/touchmove_event", "touchmove")}} event is delivered, resulting in our `handleMove()` function being called. Its responsibility in this example is to update the cached touch information and to draw a line from the previous position to the current position of each touch.
```js
function handleMove(evt) {
evt.preventDefault();
const el = document.getElementById("canvas");
const ctx = el.getContext("2d");
const touches = evt.changedTouches;
for (let i = 0; i < touches.length; i++) {
const color = colorForTouch(touches[i]);
const idx = ongoingTouchIndexById(touches[i].identifier);
if (idx >= 0) {
log(`continuing touch ${idx}`);
ctx.beginPath();
log(
`ctx.moveTo( ${ongoingTouches[idx].pageX}, ${ongoingTouches[idx].pageY} );`,
);
ctx.moveTo(ongoingTouches[idx].pageX, ongoingTouches[idx].pageY);
log(`ctx.lineTo( ${touches[i].pageX}, ${touches[i].pageY} );`);
ctx.lineTo(touches[i].pageX, touches[i].pageY);
ctx.lineWidth = 4;
ctx.strokeStyle = color;
ctx.stroke();
ongoingTouches.splice(idx, 1, copyTouch(touches[i])); // swap in the new touch record
} else {
log("can't figure out which touch to continue");
}
}
}
```
This iterates over the changed touches as well, but it looks in our cached touch information array for the previous information about each touch to determine the starting point for each touch's new line segment to be drawn. This is done by looking at each touch's {{domxref("Touch.identifier")}} property. This property is a unique integer for each touch and remains consistent for each event during the duration of each finger's contact with the surface.
This lets us get the coordinates of the previous position of each touch and use the appropriate context methods to draw a line segment joining the two positions together.
After drawing the line, we call [`Array.splice()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice) to replace the previous information about the touchpoint with the current information in the `ongoingTouches` array.
#### Handling the end of a touch
When the user lifts a finger off the surface, a {{domxref("Element/touchend_event", "touchend")}} event is sent. We handle this by calling the `handleEnd()` function below. Its job is to draw the last line segment for each touch that ended and remove the touchpoint from the ongoing touch list.
```js
function handleEnd(evt) {
evt.preventDefault();
log("touchend");
const el = document.getElementById("canvas");
const ctx = el.getContext("2d");
const touches = evt.changedTouches;
for (let i = 0; i < touches.length; i++) {
const color = colorForTouch(touches[i]);
let idx = ongoingTouchIndexById(touches[i].identifier);
if (idx >= 0) {
ctx.lineWidth = 4;
ctx.fillStyle = color;
ctx.beginPath();
ctx.moveTo(ongoingTouches[idx].pageX, ongoingTouches[idx].pageY);
ctx.lineTo(touches[i].pageX, touches[i].pageY);
ctx.fillRect(touches[i].pageX - 4, touches[i].pageY - 4, 8, 8); // and a square at the end
ongoingTouches.splice(idx, 1); // remove it; we're done
} else {
log("can't figure out which touch to end");
}
}
}
```
This is very similar to the previous function; the only real differences are that we draw a small square to mark the end and that when we call [`Array.splice()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice), we remove the old entry from the ongoing touch list, without adding in the updated information. The result is that we stop tracking that touchpoint.
#### Handling canceled touches
If the user's finger wanders into browser UI, or the touch otherwise needs to be canceled, the {{domxref("Element/touchcancel_event", "touchcancel")}} event is sent, and we call the `handleCancel()` function below.
```js
function handleCancel(evt) {
evt.preventDefault();
log("touchcancel.");
const touches = evt.changedTouches;
for (let i = 0; i < touches.length; i++) {
let idx = ongoingTouchIndexById(touches[i].identifier);
ongoingTouches.splice(idx, 1); // remove it; we're done
}
}
```
Since the idea is to immediately abort the touch, we remove it from the ongoing touch list without drawing a final line segment.
### Convenience functions
This example uses two convenience functions that should be looked at briefly to help make the rest of the code more clear.
#### Selecting a color for each touch
To make each touch's drawing look different, the `colorForTouch()` function is used to pick a color based on the touch's unique identifier.
This identifier is an opaque number, but we can at least rely on it differing between the currently-active touches.
```js
function colorForTouch(touch) {
let r = touch.identifier % 16;
let g = Math.floor(touch.identifier / 3) % 16;
let b = Math.floor(touch.identifier / 7) % 16;
r = r.toString(16); // make it a hex digit
g = g.toString(16); // make it a hex digit
b = b.toString(16); // make it a hex digit
const color = `#${r}${g}${b}`;
return color;
}
```
The result from this function is a string that can be used when calling {{HTMLElement("canvas")}} functions to set drawing colors.
For example, for a {{domxref("Touch.identifier")}} value of 10, the resulting string is "#a31".
#### Copying a touch object
Some browsers (mobile Safari, for one) re-use touch objects between events, so it's best to copy the properties you care about, rather than referencing the entire object.
```js
function copyTouch({ identifier, pageX, pageY }) {
return { identifier, pageX, pageY };
}
```
#### Finding an ongoing touch
The `ongoingTouchIndexById()` function below scans through the `ongoingTouches` array to find the touch matching the given identifier then returns that touch's index into the array.
```js
function ongoingTouchIndexById(idToFind) {
for (let i = 0; i < ongoingTouches.length; i++) {
const id = ongoingTouches[i].identifier;
if (id === idToFind) {
return i;
}
}
return -1; // not found
}
```
#### Showing what's going on
```js
function log(msg) {
const container = document.getElementById("log");
container.textContent = `${msg} \n${container.textContent}`;
}
```
### Result
You can test this example on mobile devices by touching the box below.
{{EmbedLiveSample('Example','100%', 900)}}
> **Note:** More generally, the example will work on platforms that provide touch events.
> You can test this on desktop platforms that can simulate such events:
>
> - On Firefox enable "touch simulation" in [Responsive Design Mode](https://firefox-source-docs.mozilla.org/devtools-user/responsive_design_mode/index.html#toggling-responsive-design-mode) (you may need to reload the page).
> - On Chrome use [Device mode](https://developer.chrome.com/docs/devtools/device-mode/) and set the [Device type](https://developer.chrome.com/docs/devtools/device-mode/#type) to one that sends touch events.
## Additional tips
This section provides additional tips on how to handle touch events in your web application.
### Handling clicks
Since calling `preventDefault()` on a {{domxref("Element/touchstart_event", "touchstart")}} or the first {{domxref("Element/touchmove_event", "touchmove")}} event of a series prevents the corresponding mouse events from firing, it's common to call `preventDefault()` on `touchmove` rather than `touchstart`. That way, mouse events can still fire and things like links will continue to work. Alternatively, some frameworks have taken to re-firing touch events as mouse events for this same purpose. (This example is oversimplified and may result in strange behavior. It is only intended as a guide.)
```js
function onTouch(evt) {
evt.preventDefault();
if (
evt.touches.length > 1 ||
(evt.type === "touchend" && evt.touches.length > 0)
)
return;
const newEvt = document.createEvent("MouseEvents");
let type = null;
let touch = null;
switch (evt.type) {
case "touchstart":
type = "mousedown";
touch = evt.changedTouches[0];
break;
case "touchmove":
type = "mousemove";
touch = evt.changedTouches[0];
break;
case "touchend":
type = "mouseup";
touch = evt.changedTouches[0];
break;
}
newEvt.initMouseEvent(
type,
true,
true,
evt.originalTarget.ownerDocument.defaultView,
0,
touch.screenX,
touch.screenY,
touch.clientX,
touch.clientY,
evt.ctrlKey,
evt.altKey,
evt.shiftKey,
evt.metaKey,
0,
null,
);
evt.originalTarget.dispatchEvent(newEvt);
}
```
### Calling preventDefault() only on a second touch
One technique for preventing things like `pinchZoom` on a page is to call `preventDefault()` on the second touch in a series. This behavior is not well defined in the touch events spec and results in different behavior for different browsers (i.e., iOS will prevent zooming but still allow panning with both fingers; Android will allow zooming but not panning; Opera and Firefox currently prevent all panning and zooming.) Currently, it's not recommended to depend on any particular behavior in this case, but rather to depend on meta viewport to prevent zooming.
## Specifications
{{Specifications}}
## Browser compatibility
Touch events are typically available on devices with a touch screen, but many browsers make the touch events API unavailable on all desktop devices, even those with touch screens.
The reason for this is that some websites use the availability of parts of the touch events API as an indicator that the browser is running on a mobile device. If the touch events API is available, these websites will assume a mobile device and serve mobile-optimized content. This may then provide a poor experience for users of desktop devices that have touch screens.
To support both touch and mouse across all types of devices, use [pointer events](/en-US/docs/Web/API/Pointer_events) instead.
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/touch_events | data/mdn-content/files/en-us/web/api/touch_events/using_touch_events/index.md | ---
title: Using Touch Events
slug: Web/API/Touch_events/Using_Touch_Events
page-type: guide
---
{{DefaultAPISidebar("Touch Events")}}
Today, most Web content is designed for keyboard and mouse input. However, devices with touch screens (especially portable devices) are mainstream and Web applications can either directly process touch-based input by using {{domxref("Touch_events","Touch Events")}} or the application can use _interpreted mouse events_ for the application input. A disadvantage to using mouse events is that they do not support concurrent user input, whereas touch events support multiple simultaneous inputs (possibly at different locations on the touch surface), thus enhancing user experiences.
The touch events interfaces support application specific single and multi-touch interactions such as a two-finger gesture. A multi-touch interaction starts when a finger (or stylus) first touches the contact surface. Other fingers may subsequently touch the surface and optionally move across the touch surface. The interaction ends when the fingers are removed from the surface. During this interaction, an application receives touch events during the start, move, and end phases. The application may apply its own semantics to the touch inputs.
## Interfaces
Touch events consist of three interfaces ({{domxref("Touch")}}, {{domxref("TouchEvent")}} and {{domxref("TouchList")}}) and the following event types:
- {{domxref("Element/touchstart_event", "touchstart")}} - fired when a touch point is placed on the touch surface.
- {{domxref("Element/touchmove_event", "touchmove")}} - fired when a touch point is moved along the touch surface.
- {{domxref("Element/touchend_event", "touchend")}} - fired when a touch point is removed from the touch surface.
- {{domxref("Element/touchcancel_event", "touchcancel")}} - fired when a touch point has been disrupted in an implementation-specific manner (for example, too many touch points are created).
The {{domxref("Touch")}} interface represents a single contact point on a touch-sensitive device. The contact point is typically referred to as a _touch point_ or just a _touch_. A touch is usually generated by a finger or stylus on a touchscreen, pen or trackpad. A touch point's [properties](/en-US/docs/Web/API/Touch#instance_properties) include a unique identifier, the touch point's target element as well as the _X_ and _Y_ coordinates of the touch point's position relative to the viewport, page, and screen.
The {{domxref("TouchList")}} interface represents a _list_ of contact points with a touch surface, one touch point per contact. Thus, if the user activated the touch surface with one finger, the list would contain one item, and if the user touched the surface with three fingers, the list length would be three.
The {{domxref("TouchEvent")}} interface represents an event sent when the state of contacts with a touch-sensitive surface changes. The state changes are starting contact with a touch surface, moving a touch point while maintaining contact with the surface, releasing a touch point and canceling a touch event. This interface's attributes include the state of several _modifier keys_ (for example the <kbd>shift</kbd> key) and the following touch lists:
- {{domxref("TouchEvent.touches","touches")}} - a list of all of the touch points currently on the screen.
- {{domxref("TouchEvent.targetTouches","targetTouches")}} - a list of the touch points on the _target_ DOM element.
- {{domxref("TouchEvent.changedTouches","changedTouches")}} - a list of the touch points whose items depend on the associated event type:
- For the {{domxref("Element/touchstart_event", "touchstart")}} event, it is a list of the touch points that became active with the current event.
- For the {{domxref("Element/touchmove_event", "touchmove")}} event, it is a list of the touch points that have changed since the last event.
- For the {{domxref("Element/touchend_event", "touchend")}} event, it is a list of the touch points that have been removed from the surface (that is, the set of touch points corresponding to fingers no longer touching the surface).
Together, these interfaces define a relatively low-level set of features, yet they support many kinds of touch-based interaction, including the familiar multi-touch gestures such as multi-finger swipe, rotation, pinch and zoom.
## From interfaces to gestures
An application may consider different factors when defining the semantics of a gesture. For instance, the distance a touch point traveled from its starting location to its location when the touch ended. Another potential factor is time; for example, the time elapsed between the touch's start and the touch's end, or the time lapse between two _consecutive_ taps intended to create a double-tap gesture. The directionality of a swipe (for example left to right, right to left, etc.) is another factor to consider.
The touch list(s) an application uses depends on the semantics of the application's _gestures_. For example, if an application supports a single touch (tap) on one element, it would use the {{domxref("TouchEvent.targetTouches","targetTouches")}} list in the {{domxref("Element/touchstart_event", "touchstart")}} event handler to process the touch point in an application-specific manner. If an application supports two-finger swipe for any two touch points, it will use the {{domxref("TouchEvent.changedTouches","changedTouches")}} list in the {{domxref("Element/touchmove_event", "touchmove")}} event handler to determine if two touch points had moved and then implement the semantics of that gesture in an application-specific manner.
Browsers typically dispatch _emulated_ mouse and click events when there is only a single active touch point. Multi-touch interactions involving two or more active touch points will usually only generate touch events. To prevent the emulated mouse events from being sent, use the {{domxref("Event.preventDefault()","preventDefault()")}} method in the touch event handlers. If you want to interact with both mouse and touches, use {{domxref("Pointer events", "", "", "nocode")}} instead.
## Basic steps
This section contains a basic usage of using the above interfaces. See the {{domxref("Touch_events","Touch Events Overview")}} for a more detailed example.
Register an event handler for each touch event type.
```js
// Register touch event handlers
someElement.addEventListener("touchstart", process_touchstart, false);
someElement.addEventListener("touchmove", process_touchmove, false);
someElement.addEventListener("touchcancel", process_touchcancel, false);
someElement.addEventListener("touchend", process_touchend, false);
```
Process an event in an event handler, implementing the application's gesture semantics.
```js
// touchstart handler
function process_touchstart(ev) {
// Use the event's data to call out to the appropriate gesture handlers
switch (ev.touches.length) {
case 1:
handle_one_touch(ev);
break;
case 2:
handle_two_touches(ev);
break;
case 3:
handle_three_touches(ev);
break;
default:
gesture_not_supported(ev);
break;
}
}
```
Access the attributes of a touch point.
```js
// Create touchstart handler
someElement.addEventListener(
"touchstart",
(ev) => {
// Iterate through the touch points that were activated
// for this element and process each event 'target'
for (let i = 0; i < ev.targetTouches.length; i++) {
process_target(ev.targetTouches[i].target);
}
},
false,
);
```
Prevent the browser from processing _emulated mouse events_.
```js
// touchmove handler
function process_touchmove(ev) {
// Set call preventDefault()
ev.preventDefault();
}
```
## Best practices
Here are some _best practices_ to consider when using touch events:
- Minimize the amount of work that is done in the touch handlers.
- Add the touch point handlers to the specific target element (rather than the entire document or nodes higher up in the document tree).
- Add {{domxref("Element/touchmove_event", "touchmove")}}, {{domxref("Element/touchend_event", "touchend")}} and {{domxref("Element/touchcancel_event", "touchcancel")}} event handlers within the {{domxref("Element/touchstart_event", "touchstart")}}.
- The target touch element or node should be large enough to accommodate a finger touch. If the target area is too small, touching it could result in firing other events for adjacent elements.
## Implementation and deployment status
The [touch events browser compatibility data](/en-US/docs/Web/API/Touch_events#browser_compatibility) indicates touch event support among mobile browsers is relatively broad, with desktop browser support lagging although additional implementations are in progress.
Some new features regarding a touch point's [touch area](/en-US/docs/Web/API/Touch#touch_area) - the area of contact between the user and the touch surface - are in the process of being standardized. The new features include the _X_ and _Y_ radius of the ellipse that most closely circumscribes a touch point's contact area with the touch surface. The touch point's _rotation angle_ - the number of degrees of rotation to apply to the described ellipse to align with the contact area - is also be standardized as is the amount of pressure applied to a touch point.
## What about Pointer Events?
The introduction of new input mechanisms results in increased application complexity to handle various input events, such as key events, mouse events, pen/stylus events, and touch events. To help address this problem, the [Pointer Events standard](https://www.w3.org/TR/pointerevents/) _defines events and related interfaces for handling hardware agnostic pointer input from devices including a mouse, pen, touchscreen, etc._. That is, the abstract _pointer_ creates a unified input model that can represent a contact point for a finger, pen/stylus or mouse. See the [Pointer Events MDN article](/en-US/docs/Web/API/Pointer_events).
The pointer event model can simplify an application's input processing since a pointer represents input from any input device. Additionally, the pointer event types are very similar to mouse event types (for example, `pointerdown` and `pointerup`) thus code to handle pointer events closely matches mouse handling code.
The implementation status of pointer events in browsers is [relatively high](https://caniuse.com/#search=pointer) with Chrome, Firefox, IE11 and Edge having complete implementations.
## Examples and demos
The following documents describe how to use touch events and include example code:
- {{domxref("Touch_events","Touch Events Overview")}}
- [Implement Custom Gestures](https://web.dev/articles/add-touch-to-your-site)
- [Add touch screen support to your website (The easy way)](https://www.codicode.com/art/easy_way_to_add_touch_support_to_your_website.aspx)
Touch event demonstrations:
- [Paint Program (by Rick Byers)](https://rbyers.github.io/paint.html)
- [Touch/pointer tests and demos (by Patrick H. Lauke)](https://patrickhlauke.github.io/touch/)
## Community
- [Touch Events Community Group](https://github.com/w3c/touch-events)
- [Mail list](https://lists.w3.org/Archives/Public/public-touchevents/)
- [W3C #touchevents IRC channel](irc://irc.w3.org:6667/)
## Related topics and resources
- [Pointer Events Standard](https://www.w3.org/TR/pointerevents/)
| 0 |
data/mdn-content/files/en-us/web/api/touch_events | data/mdn-content/files/en-us/web/api/touch_events/multi-touch_interaction/index.md | ---
title: Multi-touch interaction
slug: Web/API/Touch_events/Multi-touch_interaction
page-type: guide
---
{{DefaultAPISidebar("Touch Events")}}
The touch event interfaces support application-specific single and multi-touch interactions. However, the interfaces can be a bit tricky for programmers to use because touch events are very different from other DOM input events, such as {{domxref("MouseEvent","mouse events")}}. The application described in this guide shows how to use touch events for simple single and multi-touch interactions, the basics needed to build application-specific gestures.
A _live_ version of this application is available on [GitHub](https://mdn.github.io/dom-examples/touchevents/Multi-touch_interaction.html). The [source code is available on GitHub](https://github.com/mdn/dom-examples/tree/main/touchevents) and pull requests and [bug reports](https://github.com/mdn/dom-examples/issues) are welcome.
## Example
This example demonstrates using the {{domxref("Element/touchstart_event", "touchstart")}}, {{domxref("Element/touchmove_event", "touchmove")}}, {{domxref("Element/touchcancel_event", "touchcancel")}}, and {{domxref("Element/touchend_event", "touchend")}}) touch events for the following gestures: single touch, two (simultaneous) touches, more than two simultaneous touches, 1-finger swipe, and 2-finger move/pinch/swipe.
### Define touch targets
The application uses {{HTMLElement("div")}} elements to represent four touch areas.
```html
<style>
div {
margin: 0em;
padding: 2em;
}
#target1 {
background: white;
border: 1px solid black;
}
#target2 {
background: white;
border: 1px solid black;
}
#target3 {
background: white;
border: 1px solid black;
}
#target4 {
background: white;
border: 1px solid black;
}
</style>
```
### Global state
`tpCache` is used to cache touch points for processing outside of the event where they were fired.
```js
// Log events flag
const logEvents = false;
// Touch Point cache
const tpCache = [];
```
### Register event handlers
Event handlers are registered for all four touch event types. The {{domxref("Element/touchend_event", "touchend")}} and {{domxref("Element/touchcancel_event", "touchcancel")}} event types use the same handler.
```js
function set_handlers(name) {
// Install event handlers for the given element
const el = document.getElementById(name);
el.ontouchstart = start_handler;
el.ontouchmove = move_handler;
// Use same handler for touchcancel and touchend
el.ontouchcancel = end_handler;
el.ontouchend = end_handler;
}
function init() {
set_handlers("target1");
set_handlers("target2");
set_handlers("target3");
set_handlers("target4");
}
```
### Move/Pinch/Zoom handler
This function provides very basic support for 2-touch horizontal move/pinch/zoom handling. The code does not include error handling, or vertical moving. Note that the _threshold_ for pinch and zoom movement detection is application specific (and device dependent).
```js
// This is a very basic 2-touch move/pinch/zoom handler that does not include
// error handling, only handles horizontal moves, etc.
function handle_pinch_zoom(ev) {
if (ev.targetTouches.length === 2 && ev.changedTouches.length === 2) {
// Check if the two target touches are the same ones that started
// the 2-touch
const point1 = tpCache.findLastIndex(
(tp) => tp.identifier === ev.targetTouches[0].identifier,
);
const point2 = tpCache.findLastIndex(
(tp) => tp.identifier === ev.targetTouches[1].identifier,
);
if (point1 >= 0 && point2 >= 0) {
// Calculate the difference between the start and move coordinates
const diff1 = Math.abs(
tpCache[point1].clientX - ev.targetTouches[0].clientX,
);
const diff2 = Math.abs(
tpCache[point2].clientX - ev.targetTouches[1].clientX,
);
// This threshold is device dependent as well as application specific
const PINCH_THRESHOLD = ev.target.clientWidth / 10;
if (diff1 >= PINCH_THRESHOLD && diff2 >= PINCH_THRESHOLD)
ev.target.style.background = "green";
} else {
// empty tpCache
tpCache = [];
}
}
}
```
### Touch start handler
The {{domxref("Element/touchstart_event", "touchstart")}} event handler caches touch points to support 2-touch gestures. It also calls {{domxref("Event.preventDefault","preventDefault()")}} to keep the browser from applying further event handling (for example, mouse event emulation).
```js
function start_handler(ev) {
// If the user makes simultaneous touches, the browser will fire a
// separate touchstart event for each touch point. Thus if there are
// three simultaneous touches, the first touchstart event will have
// targetTouches length of one, the second event will have a length
// of two, and so on.
ev.preventDefault();
// Cache the touch points for later processing of 2-touch pinch/zoom
if (ev.targetTouches.length === 2) {
for (let i = 0; i < ev.targetTouches.length; i++) {
tpCache.push(ev.targetTouches[i]);
}
}
if (logEvents) log("touchStart", ev, true);
update_background(ev);
}
```
### Touch move handler
The {{domxref("Element/touchmove_event", "touchmove")}} handler calls {{domxref("Event.preventDefault","preventDefault()")}} for the same reason mentioned above, and invokes the pinch/zoom handler.
```js
function move_handler(ev) {
// Note: if the user makes more than one "simultaneous" touches, most browsers
// fire at least one touchmove event and some will fire several touchmoves.
// Consequently, an application might want to "ignore" some touchmoves.
//
// This function sets the target element's border to "dashed" to visually
// indicate the target received a move event.
//
ev.preventDefault();
if (logEvents) log("touchMove", ev, false);
// To avoid too much color flashing many touchmove events are started,
// don't update the background if two touch points are active
if (!(ev.touches.length === 2 && ev.targetTouches.length === 2))
update_background(ev);
// Set the target element's border to dashed to give a clear visual
// indication the element received a move event.
ev.target.style.border = "dashed";
// Check this event for 2-touch Move/Pinch/Zoom gesture
handle_pinch_zoom(ev);
}
```
### Touch end handler
The {{domxref("Element/touchend_event", "touchend")}} handler restores the event target's background color back to its original color.
```js
function end_handler(ev) {
ev.preventDefault();
if (logEvents) log(ev.type, ev, false);
if (ev.targetTouches.length === 0) {
// Restore background and border to original values
ev.target.style.background = "white";
ev.target.style.border = "1px solid black";
}
}
```
### Application UI
The application uses {{HTMLElement("div")}} elements for the touch areas and provides buttons to enable logging and clear the log.
```html
<div id="target1">Tap, Hold or Swipe me 1</div>
<div id="target2">Tap, Hold or Swipe me 2</div>
<div id="target3">Tap, Hold or Swipe me 3</div>
<div id="target4">Tap, Hold or Swipe me 4</div>
<!-- UI for logging/debugging -->
<button id="log" onclick="enableLog(event);">Start/Stop event logging</button>
<button id="clearlog" onclick="clearLog(event);">Clear the log</button>
<p></p>
<output></output>
```
### Miscellaneous functions
These functions support the application but aren't directly involved with the event flow.
#### Update background color
The background color of the touch areas will change as follows: no touch is `white`; one touch is `yellow`; two simultaneous touches is `pink`, and three or more simultaneous touches is `lightblue`. See [touch move](#touch_move) for information about the background color changing when a 2-finger move/pinch/zoom is detected.
```js
function update_background(ev) {
// Change background color based on the number simultaneous touches
// in the event's targetTouches list:
// yellow - one tap (or hold)
// pink - two taps
// lightblue - more than two taps
switch (ev.targetTouches.length) {
case 1:
// Single tap`
ev.target.style.background = "yellow";
break;
case 2:
// Two simultaneous touches
ev.target.style.background = "pink";
break;
default:
// More than two simultaneous touches
ev.target.style.background = "lightblue";
}
}
```
#### Event logging
The functions are used to log event activity to the application window, to support debugging and learning about the event flow.
```js
function enableLog(ev) {
logEvents = !logEvents;
}
function log(name, ev, printTargetIds) {
const o = document.getElementsByTagName("output")[0];
let s =
`${name}: touches = ${ev.touches.length} ; ` +
`targetTouches = ${ev.targetTouches.length} ; ` +
`changedTouches = ${ev.changedTouches.length}`;
o.innerHTML += `${s}<br>`;
if (printTargetIds) {
s = "";
for (let i = 0; i < ev.targetTouches.length; i++) {
s += `... id = ${ev.targetTouches[i].identifier}<br>`;
}
o.innerHTML += s;
}
}
function clearLog(event) {
const o = document.getElementsByTagName("output")[0];
o.innerHTML = "";
}
```
## Related topics and resources
- {{domxref("Pointer_events","Pointer Events")}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/medialist/index.md | ---
title: MediaList
slug: Web/API/MediaList
page-type: web-api-interface
browser-compat: api.MediaList
---
{{APIRef("CSSOM")}}
The **`MediaList`** interface represents the media queries of a stylesheet, e.g. those set using a {{htmlelement("link")}} element's `media` attribute.
> **Note:** `MediaList` is a live list; updating the list using properties or methods listed below will immediately update the behavior of the document.
## Instance properties
- {{domxref("MediaList.mediaText")}}
- : A {{Glossary("stringifier")}} that returns a string representing the `MediaList` as text, and also allows you to set a new `MediaList`.
- {{domxref("MediaList.length")}} {{ReadOnlyInline}}
- : Returns the number of media queries in the `MediaList`.
## Instance methods
- {{domxref("MediaList.appendMedium()")}}
- : Adds a media query to the `MediaList`.
- {{domxref("MediaList.deleteMedium()")}}
- : Removes a media query from the `MediaList`.
- {{domxref("MediaList.item()")}}
- : A getter that returns a string representing a media query as text, given the media query's index value inside the `MediaList`. This method can also be called using the bracket (`[]`) syntax.
## Examples
The following would log to the console a textual representation of the `MediaList` of the first stylesheet applied to the current document.
```js
const stylesheets = document.styleSheets;
let stylesheet = stylesheets[0];
console.log(stylesheet.media.mediaText);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/medialist | data/mdn-content/files/en-us/web/api/medialist/deletemedium/index.md | ---
title: "MediaList: deleteMedium() method"
short-title: deleteMedium()
slug: Web/API/MediaList/deleteMedium
page-type: web-api-instance-method
browser-compat: api.MediaList.deleteMedium
---
{{APIRef("CSSOM")}}
The `deleteMedium()` method of the {{DOMxRef("MediaList")}} interface removes from this `MediaList` the given media query.
## Syntax
```js-nolint
deleteMedium(medium)
```
### Parameters
- `medium`
- : A string containing the media query to remove from the list.
### Return value
None ([undefined](/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined)).
### Exceptions
- `NotFoundError` {{domxref("DOMException")}}
- : Thrown when the media query to remove is not in the list.
## Examples
The following removes the media query `print` from the
`MediaList` associated with the first stylesheet applied to the current document.
```js
const stylesheet = document.styleSheets[0];
stylesheet.media.removeMedium("print");
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/medialist | data/mdn-content/files/en-us/web/api/medialist/length/index.md | ---
title: "MediaList: length property"
short-title: length
slug: Web/API/MediaList/length
page-type: web-api-instance-property
browser-compat: api.MediaList.length
---
{{APIRef("CSSOM")}}
The read-only **`length`** property of the {{DOMxRef("MediaList")}} interface returns the number of media queries in the list.
## Value
A positive integer.
## Examples
The following would log to the console the number of media queries stored in the
`MediaList` associated with the first stylesheet applied to the current document.
```js
const stylesheets = document.styleSheets;
const stylesheet = stylesheets[0];
console.log(stylesheet.media.length);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/medialist | data/mdn-content/files/en-us/web/api/medialist/item/index.md | ---
title: "MediaList: item() method"
short-title: item()
slug: Web/API/MediaList/item
page-type: web-api-instance-method
browser-compat: api.MediaList.item
---
{{ APIRef("CSSOM") }}
The **`item()`** method of the {{domxref("MediaList")}} interface returns the media query at the specified `index`, or `null` if the specified `index` doesn't exist.
## Syntax
```js-nolint
item(index)
[index]
```
> **Note:** The bracket (`[]`) syntax can be used instead of the `item()` syntax.
### Parameters
- `index`
- : An integer.
### Return value
If the bracket (`[]`) syntax is used and there is no entry for the given index, `undefined` is returned.
## Examples
The following would log to the console each media query stored in the
`MediaList` associated with the first stylesheet applied to the current document.
```js
const stylesheet = document.styleSheets[0];
console.log(stylesheet.media.length);
console.log(stylesheet.media.item(0)); // Returns a string like "print"
console.log(stylesheet.media.item(5)); // Returns null if there is no 5th entry
console.log(stylesheet.media[1]); // Returns a string like "print"
console.log(stylesheet.media[5]); // Returns undefined if there is no 5th entry
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/medialist | data/mdn-content/files/en-us/web/api/medialist/appendmedium/index.md | ---
title: "MediaList: appendMedium() method"
short-title: appendMedium()
slug: Web/API/MediaList/appendMedium
page-type: web-api-instance-method
browser-compat: api.MediaList.appendMedium
---
{{APIRef("CSSOM")}}
The `appendMedium()` method of the {{DomxRef("MediaList")}} interface adds a media query to the list. If the media query is already in the collection, this method does nothing.
## Syntax
```js-nolint
appendMedium(medium)
```
### Parameters
- `medium`
- : A string containing the media query to add.
### Return value
None ([undefined](/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined)).
## Examples
The following adds the media query `print` into the
`MediaList` associated with the first stylesheet applied to the current document.
```js
const stylesheet = document.styleSheets[0];
stylesheet.media.appendMedium("print");
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/medialist | data/mdn-content/files/en-us/web/api/medialist/mediatext/index.md | ---
title: "MediaList: mediaText property"
short-title: mediaText
slug: Web/API/MediaList/mediaText
page-type: web-api-instance-property
browser-compat: api.MediaList.mediaText
---
{{APIRef("CSSOM")}}
The **`mediaText`** property of the {{domxref("MediaList")}}
interface is a {{Glossary("stringifier")}} that returns a string representing the
`MediaList` as text, and also allows you to set a new `MediaList`.
## Value
A string representing the media queries of a stylesheet. Each one is
separated by a comma, for example
`screen and (min-width: 480px), print`.
If you wish to set new media queries on the document, the string value must have the
different queries separated by commas, e.g. `screen, print`. Note that the
`MediaList` is a live list; updating the list via
`mediaText` will immediately update the behavior of the
document.
Also note that is you try to set
`mediaText` to `null`, it will be treated as an empty
string, i.e. the value will be set to
`""`.
## Examples
The following would log to the console a textual representation of the
`MediaList` of the first stylesheet applied to the current document.
```js
const stylesheets = document.styleSheets;
let stylesheet = stylesheets[0];
console.log(stylesheet.media.mediaText);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/sharedstorageselecturloperation/index.md | ---
title: SharedStorageSelectURLOperation
slug: Web/API/SharedStorageSelectURLOperation
page-type: web-api-interface
status:
- experimental
browser-compat: api.SharedStorageSelectURLOperation
---
{{APIRef("Shared Storage API")}}{{SeeCompatTable}}
The **`SharedStorageSelectURLOperation`** interface of the {{domxref("Shared Storage API", "Shared Storage API", "", "nocode")}} represents a [URL Selection output gate](/en-US/docs/Web/API/Shared_Storage_API#url_selection) operation.
{{InheritanceDiagram}}
## Instance methods
- {{domxref("SharedStorageSelectURLOperation.run", "run()")}} {{Experimental_Inline}}
- : Defines the structure to which the `run()` method defined inside a URL Selection output gate operation should conform.
## Examples
In this example, a class called `SelectURLOperation` is defined in a worklet and is registered using {{domxref("SharedStorageWorkletGlobalScope.register()")}} with the name `ab-testing`. `SharedStorageSelectURLOperation` defines the structure to which this class needs to conform, essentially defining the parameters required for the `run()` method. Other than this requirement, the functionality of the class can be defined flexibly.
```js
// ab-testing-worklet.js
class SelectURLOperation {
async run(urls, data) {
// Read the user's experiment group from Shared Storage
const experimentGroup = await this.sharedStorage.get("ab-testing-group");
// Return the group number
return experimentGroup;
}
}
// Register the operation
register("ab-testing", SelectURLOperation);
```
> **Note:** It is possible to define and register multiple operations in the same shared storage worklet module script with different names; see {{domxref("SharedStorageOperation")}} for an example.
In the main browsing context, the `ab-testing` operation is invoked using the {{domxref("WindowSharedStorage.selectURL()")}} method:
```js
// Randomly assigns a user to a group 0 or 1
function getExperimentGroup() {
return Math.round(Math.random());
}
async function injectContent() {
// Register the Shared Storage worklet
await window.sharedStorage.worklet.addModule("ab-testing-worklet.js");
// Assign user to a random group (0 or 1) and store it in Shared Storage
window.sharedStorage.set("ab-testing-group", getExperimentGroup(), {
ignoreIfPresent: true,
});
// Run the URL selection operation
const fencedFrameConfig = await window.sharedStorage.selectURL(
"ab-testing",
[
{ url: `https://your-server.example/content/default-content.html` },
{ url: `https://your-server.example/content/experiment-content-a.html` },
],
{
resolveToConfig: true,
},
);
// Render the chosen URL into a fenced frame
document.getElementById("content-slot").config = fencedFrameConfig;
}
injectContent();
```
For more details about this example and links to other examples, see the [Shared Storage API](/en-US/docs/Web/API/Shared_Storage_API) landing page.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Shared Storage API](/en-US/docs/Web/API/Shared_Storage_API)
| 0 |
data/mdn-content/files/en-us/web/api/sharedstorageselecturloperation | data/mdn-content/files/en-us/web/api/sharedstorageselecturloperation/run/index.md | ---
title: "SharedStorageSelectURLOperation: run() method"
short-title: run()
slug: Web/API/SharedStorageSelectURLOperation/run
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.SharedStorageSelectURLOperation.run
---
{{APIRef("Shared Storage API")}}{{SeeCompatTable}}
The **`run()`** method of the {{domxref("SharedStorageSelectURLOperation")}} interface defines the structure to which the `run()` method defined inside a URL Selection output gate operation should conform.
## Syntax
```js-nolint
run(urls, data)
```
### Parameters
- `urls`
- : An array of objects representing the URLs to be chosen by the URL Selection operation. Each object contains two properties:
- `url`
- : A string representing the URL.
- `reportingMetadata` {{optional_inline}}
- : An object containing properties where names are event types and values are URLs pointing to reporting destinations, for example `"click" : "my-reports/report1.html"`. The URLs act as destinations for reports submitted with a destination of type `"shared-storage-select-url"`, typically submitted via a {{domxref("Fence.reportEvent()")}} or {{domxref("Fence.setReportEventDataForAutomaticBeacons()")}} method call.
- `data`
- : An object representing any data required for executing the operation.
### Return value
A {{jsxref("Promise")}} that fulfills with a number defining the array index of the URL selected by the operation.
## Examples
See the main {{domxref("SharedStorageSelectURLOperation")}} page for an example.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Shared Storage API](/en-US/docs/Web/API/Shared_Storage_API)
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/paymentmethodchangeevent/index.md | ---
title: PaymentMethodChangeEvent
slug: Web/API/PaymentMethodChangeEvent
page-type: web-api-interface
browser-compat: api.PaymentMethodChangeEvent
---
{{securecontext_header}}{{APIRef("Payment Request API")}}
The **`PaymentMethodChangeEvent`** interface of the [Payment Request API](/en-US/docs/Web/API/Payment_Request_API) describes the {{domxref("PaymentRequest/paymentmethodchange_event", "paymentmethodchange")}} event which is fired by some payment handlers when the user switches payment instruments (e.g., a user selects a "store" card to make a purchase while using Apple Pay).
{{InheritanceDiagram}}
## Constructor
- {{domxref("PaymentMethodChangeEvent.PaymentMethodChangeEvent", "PaymentMethodChangeEvent()")}}
- : Creates and returns a new `PaymentMethodChangeEvent` object.
## Instance properties
_In addition to the properties below, this interface includes properties inherited from {{domxref("PaymentRequestUpdateEvent")}}._
- {{domxref("PaymentMethodChangeEvent.methodDetails", "methodDetails")}} {{ReadOnlyInline}}
- : An object containing payment method-specific data useful when handling a payment method change. If no such information is available, this value is `null`.
- {{domxref("PaymentMethodChangeEvent.methodName", "methodName")}} {{ReadOnlyInline}}
- : A string containing the payment method identifier, a string which uniquely identifies a particular payment method. This identifier is usually a URL used during the payment process, but may be a standardized non-URL string as well, such as `basic-card`. The default value is the empty string, `""`.
## Instance methods
_This interface includes methods inherited from {{domxref("PaymentRequestUpdateEvent")}}._
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/paymentmethodchangeevent | data/mdn-content/files/en-us/web/api/paymentmethodchangeevent/methodname/index.md | ---
title: "PaymentMethodChangeEvent: methodName property"
short-title: methodName
slug: Web/API/PaymentMethodChangeEvent/methodName
page-type: web-api-instance-property
browser-compat: api.PaymentMethodChangeEvent.methodName
---
{{securecontext_header}}{{APIRef("Payment Request API")}}
The read-only **`methodName`** property of the {{domxref("PaymentMethodChangeEvent")}} interface is a string which
uniquely identifies the payment handler currently selected by the user. The
payment handler may be a payment technology, such as Apple Pay or Android Pay, and each
payment handler may support multiple payment methods; changes to the payment method
within the payment handler are described by the `PaymentMethodChangeEvent`.
## Value
A string which uniquely identifies the currently-selected payment
handler. This may be a string chosen from the list of standardized payment method
identifiers, or a URL used by the payment processing service. See
[Payment method identifiers](/en-US/docs/Web/API/Payment_Request_API#payment_method_identifiers) for more information.
The default value is the empty string, `""`.
## Examples
This example uses the {{domxref("PaymentRequest.paymentmethodchange_event", "paymentmethodchange")}} event to watch for changes to
the payment method selected for Apple Pay, in order to compute a discount if the user
chooses to use a Visa card as their payment method.
```js
request.onpaymentmethodchange = (ev) => {
const { type: cardType } = ev.methodDetails;
const newStuff = {};
if (ev.methodName === "https://apple.com/apple-pay") {
switch (cardType) {
case "visa": {
// do Apple Pay specific handling for Visa card…
// methodDetails contains the card information
const discount = calculateDiscount(ev.methodDetails);
Object.assign(newStuff, discount);
break;
}
}
}
// finally…
ev.updateWith(newStuff);
};
const response = await request.show();
```
Note that the `methodDetails` property is being used by the `calculateDiscount()` function to compute any payment discount, then {{domxref("PaymentRequestUpdateEvent.updateWith", "updateWith()")}} is called to update the event with the computed update.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/paymentmethodchangeevent | data/mdn-content/files/en-us/web/api/paymentmethodchangeevent/paymentmethodchangeevent/index.md | ---
title: "PaymentMethodChangeEvent: PaymentMethodChangeEvent() constructor"
short-title: PaymentMethodChangeEvent()
slug: Web/API/PaymentMethodChangeEvent/PaymentMethodChangeEvent
page-type: web-api-constructor
browser-compat: api.PaymentMethodChangeEvent.PaymentMethodChangeEvent
---
{{securecontext_header}}{{APIRef("Payment Request API")}}
The **`PaymentMethodChangeEvent()`**
constructor creates a new {{domxref("PaymentMethodChangeEvent")}} object providing
details about a {{domxref("PaymentRequest.paymentmethodchange_event", "paymentmethodchange")}} event.
## Syntax
```js-nolint
new PaymentMethodChangeEvent(type)
new PaymentMethodChangeEvent(type, options)
```
### Parameters
- `type`
- : A string with the name of the event.
It is case-sensitive and browsers set it to `paymentmethodchange`.
- `options` {{optional_inline}}
- : An object that, _in addition of the properties defined in {{domxref("Event/Event", "Event()")}}_,
can have the following properties:
- `methodName` {{optional_inline}}
- : A string containing the payment method identifier for the
payment handler being used. This is an empty string by default.
- `methodDetails` {{optional_inline}}
- : An object providing payment method-specific information describing the changes
made to the payment, or `null` if there is no additional information
available or required. This is `null` by default.
### Return value
A new {{domxref("PaymentMethodChangeEvent")}} object describing a change to
the options specified for the payment method given in the `methodName`
property.
The type of the `methodDetails` property depends on the payment method. For
example, if `methodName` is `https://example.com/pay`, indicating that the
Example Pay payment method is being used for validation, the shape of `methodDetails`
is defined by the payment method.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Payment Request API](/en-US/docs/Web/API/Payment_Request_API)
- [Using the Payment Request API](/en-US/docs/Web/API/Payment_Request_API/Using_the_Payment_Request_API)
- [Payment processing concepts](/en-US/docs/Web/API/Payment_Request_API/Concepts)
| 0 |
data/mdn-content/files/en-us/web/api/paymentmethodchangeevent | data/mdn-content/files/en-us/web/api/paymentmethodchangeevent/methoddetails/index.md | ---
title: "PaymentMethodChangeEvent: methodDetails property"
short-title: methodDetails
slug: Web/API/PaymentMethodChangeEvent/methodDetails
page-type: web-api-instance-property
browser-compat: api.PaymentMethodChangeEvent.methodDetails
---
{{securecontext_header}}{{APIRef("Payment Request API")}}
The read-only **`methodDetails`** property of the {{domxref("PaymentMethodChangeEvent")}} interface is an object
containing any data the payment handler may provide to describe the change the user
has made to their payment method. The value is `null` if no details
are available.
## Value
An object containing any data needed to describe the changes made to the payment
method. The contents vary depending on the actual payment method chosen, so you will
need to refer to the {{domxref("PaymentMethodChangeEvent.methodName", "methodName")}}
property first, then interpret the `methodDetails` after that.
The default value is `null`, indicating that no additional details are
available.
## Examples
This example uses the {{domxref("PaymentRequest.paymentmethodchange_event", "paymentmethodchange")}} event to watch for changes to
the payment method selected for Apple Pay, in order to compute a discount if the user
chooses to use a Visa card as their payment method.
```js
request.onpaymentmethodchange = (ev) => {
const { type: cardType } = ev.methodDetails;
const newStuff = {};
if (ev.methodName === "https://apple.com/apple-pay") {
switch (cardType) {
case "visa": {
// do Apple Pay specific handling for Visa card…
// methodDetails contains the card information
const discount = calculateDiscount(ev.methodDetails);
Object.assign(newStuff, discount);
break;
}
}
}
// finally…
ev.updateWith(newStuff);
};
const response = await request.show();
```
Note that the `methodDetails` property is being used by the `calculateDiscount()` function to compute any payment discount, then {{domxref("PaymentRequestUpdateEvent.updateWith", "updateWith()")}} is called to update the event with the computed update.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/htmlmenuitemelement/index.md | ---
title: HTMLMenuItemElement
slug: Web/API/HTMLMenuItemElement
page-type: web-api-interface
status:
- deprecated
- non-standard
---
{{APIRef("HTML DOM")}}{{Deprecated_Header}}{{Non-standard_Header}}
The **`HTMLMenuItemElement`** interface provides special properties (beyond those defined on the regular {{DOMxRef("HTMLElement")}} interface it also has available to it by inheritance) for manipulating {{HTMLElement("menuitem")}} elements.
{{InheritanceDiagram}}
## Specifications
This feature is not part of any current specification. It is no longer on track to become a standard.
## Browser compatibility
No longer supported in any browser. Firefox, the only browser that supported this element, removed support in 85.
## See also
- {{DOMxRef("HTMLMenuElement")}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/absoluteorientationsensor/index.md | ---
title: AbsoluteOrientationSensor
slug: Web/API/AbsoluteOrientationSensor
page-type: web-api-interface
browser-compat: api.AbsoluteOrientationSensor
---
{{securecontext_header}}{{APIRef("Sensor API")}}
The **`AbsoluteOrientationSensor`** interface of the [Sensor APIs](/en-US/docs/Web/API/Sensor_APIs) describes the device's physical orientation in relation to the Earth's reference coordinate system.
To use this sensor, the user must grant permission to the `'accelerometer'`, `'gyroscope'`, and `'magnetometer'` device sensors through the [Permissions API](/en-US/docs/Web/API/Permissions_API).
This feature may be blocked by a [Permissions Policy](/en-US/docs/Web/HTTP/Permissions_Policy) set on your server.
{{InheritanceDiagram}}
## Constructor
- {{domxref("AbsoluteOrientationSensor.AbsoluteOrientationSensor", "AbsoluteOrientationSensor()")}}
- : Creates a new `AbsoluteOrientationSensor` object.
## Instance properties
_No specific properties; inherits properties from its ancestors {{domxref('OrientationSensor')}} and {{domxref('Sensor')}}._
## Instance methods
_No specific methods; inherits methods from its ancestors {{domxref('OrientationSensor')}} and {{domxref('Sensor')}}._
## Events
_No specific events; inherits methods from its ancestor, {{domxref('Sensor')}}._
## Examples
### Basic Example
The following example, which is loosely based on [Intel's Orientation Phone demo](https://intel.github.io/generic-sensor-demos/orientation-phone/), instantiates an `AbsoluteOrientationSensor` with a frequency of 60 times a second. On each reading it uses {{domxref('OrientationSensor.quaternion')}} to rotate a visual model of a phone.
```js
const options = { frequency: 60, referenceFrame: "device" };
const sensor = new AbsoluteOrientationSensor(options);
sensor.addEventListener("reading", () => {
// model is a Three.js object instantiated elsewhere.
model.quaternion.fromArray(sensor.quaternion).inverse();
});
sensor.addEventListener("error", (error) => {
if (event.error.name === "NotReadableError") {
console.log("Sensor is not available.");
}
});
sensor.start();
```
### Permissions Example
Using orientation sensors requires requesting permissions for multiple device sensors. Because the {{domxref('Permissions')}} interface uses promises, a good way to request permissions is to use {{jsxref('Promise.all')}}.
```js
const sensor = new AbsoluteOrientationSensor();
Promise.all([
navigator.permissions.query({ name: "accelerometer" }),
navigator.permissions.query({ name: "magnetometer" }),
navigator.permissions.query({ name: "gyroscope" }),
]).then((results) => {
if (results.every((result) => result.state === "granted")) {
sensor.start();
// …
} else {
console.log("No permissions to use AbsoluteOrientationSensor.");
}
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/absoluteorientationsensor | data/mdn-content/files/en-us/web/api/absoluteorientationsensor/absoluteorientationsensor/index.md | ---
title: "AbsoluteOrientationSensor: AbsoluteOrientationSensor() constructor"
short-title: AbsoluteOrientationSensor()
slug: Web/API/AbsoluteOrientationSensor/AbsoluteOrientationSensor
page-type: web-api-constructor
browser-compat: api.AbsoluteOrientationSensor.AbsoluteOrientationSensor
---
{{securecontext_header}}{{APIRef("Sensor API")}}
The **`AbsoluteOrientationSensor()`** constructor creates a new {{domxref("AbsoluteOrientationSensor")}} object which describes the device's physical orientation in relation to the Earth's reference coordinate system.
## Syntax
```js-nolint
new AbsoluteOrientationSensor()
new AbsoluteOrientationSensor(options)
```
### Parameters
- `options` {{optional_inline}}
- : Options are as follows:
- `frequency` {{optional_inline}}
- : The desired number of times per second a sample should be taken, meaning the number of times per second that the {{domxref('sensor.reading_event', 'reading')}} event will be called. A whole number or decimal may be used, the latter for frequencies less than a second. The actual reading frequency depends on the device hardware and consequently may be less than requested.
- `referenceFrame` {{optional_inline}}
- : Either `'device'` or `'screen'`. The default is `'device'`.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref('sensor.reading_event', 'reading')}} event
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/characterboundsupdateevent/index.md | ---
title: CharacterBoundsUpdateEvent
slug: Web/API/CharacterBoundsUpdateEvent
page-type: web-api-interface
status:
- experimental
browser-compat: api.CharacterBoundsUpdateEvent
---
{{APIRef("EditContext API")}}{{SeeCompatTable}}
The **`CharacterBoundsUpdateEvent`** interface is a {{domxref("Event", "DOM event")}} that represents a request from the operating system to know the bounds of certain characters within an editable region that's attached to an {{domxref("EditContext")}} instance.
This interface inherits properties from {{domxref("Event")}}.
{{InheritanceDiagram}}
## Constructor
- {{domxref("CharacterBoundsUpdateEvent.CharacterBoundsUpdateEvent", "CharacterBoundsUpdateEvent()")}} {{experimental_inline}}
- : Creates a new `CharacterBoundsUpdateEvent` object.
## Instance properties
- {{domxref('CharacterBoundsUpdateEvent.rangeStart')}} {{readonlyinline}} {{experimental_inline}}
- : The offset of the first character within the editable region text for which the operating system needs the bounds.
- {{domxref('CharacterBoundsUpdateEvent.rangeEnd')}} {{readonlyinline}} {{experimental_inline}}
- : The offset of the last character within the editable region text for which the operating system needs the bounds.
## Examples
### Updating the character bounds when needed
This example shows how to use the `characterboundsupdate` event and the `updateCharacterBounds` method to inform the operating system of the character bounds it requires. Note that the event listener callback is only called when using an IME window, or other platform-specific editing UI surfaces, to compose text.
```html
<canvas id="editor-canvas"></canvas>
```
```js
const FONT_SIZE = 40;
const FONT = `${FONT_SIZE}px Arial`;
const canvas = document.getElementById("editor-canvas");
const ctx = canvas.getContext("2d");
ctx.font = FONT;
const editContext = new EditContext();
canvas.editContext = editContext;
function computeCharacterBound(offset) {
// Measure the width from the start of the text to the character.
const widthBeforeChar = ctx.measureText(
editContext.text.substring(0, offset),
).width;
// Measure the character width.
const charWidth = ctx.measureText(editContext.text[offset]).width;
const charX = canvas.offsetLeft + widthBeforeChar;
const charY = canvas.offsetTop;
// Return a DOMRect representing the character bounds.
return DOMRect.fromRect({
x: charX,
y: charY - FONT_SIZE,
width: charWidth,
height: FONT_SIZE,
});
}
editContext.addEventListener("characterboundsupdate", (e) => {
const charBounds = [];
for (let offset = e.rangeStart; offset < e.rangeEnd; offset++) {
charBounds.push(computeCharacterBound(offset));
}
// Update the character bounds in the EditContext instance.
editContext.updateCharacterBounds(e.rangeStart, charBounds);
console.log(
"The required character bounds are",
charBounds
.map((bound) => {
return `(x: ${bound.x}, y: ${bound.y}, width: ${bound.width}, height: ${bound.height})`;
})
.join(", "),
);
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/characterboundsupdateevent | data/mdn-content/files/en-us/web/api/characterboundsupdateevent/rangeend/index.md | ---
title: "CharacterBoundsUpdateEvent: rangeEnd property"
short-title: rangeEnd
slug: Web/API/CharacterBoundsUpdateEvent/rangeEnd
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.CharacterBoundsUpdateEvent.rangeEnd
---
{{APIRef("EditContext API")}}{{SeeCompatTable}}
The **`CharacterBoundsUpdateEvent.rangeEnd`** read-only property represents the offset of the last character within the editable text region for which the operating system needs the bounds.
## Value
A {{jsxref("Number")}}.
## Examples
### Reading the `rangeEnd` value
This example shows how to use the `characterboundsupdate` event and read the value of the `rangeStart` and `rangeEnd` properties.
```js
const editContext = new EditContext();
editorElement.editContext = editContext;
editContext.addEventListener("characterboundsupdate", (e) => {
console.log(
`The OS needs the bounds of the chars at ${e.rangeStart} - ${e.rangeEnd}.`,
);
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/characterboundsupdateevent | data/mdn-content/files/en-us/web/api/characterboundsupdateevent/rangestart/index.md | ---
title: "CharacterBoundsUpdateEvent: rangeStart property"
short-title: rangeStart
slug: Web/API/CharacterBoundsUpdateEvent/rangeStart
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.CharacterBoundsUpdateEvent.rangeStart
---
{{APIRef("EditContext API")}}{{SeeCompatTable}}
The **`CharacterBoundsUpdateEvent.rangeStart`** read-only property represents the offset of the first character within the editable text region for which the operating system needs the bounds.
## Value
A {{jsxref("Number")}}.
## Examples
### Reading the `rangeStart` value
This example shows how to use the `characterboundsupdate` event and read the value of the `rangeStart` and `rangeEnd` properties.
```js
const editContext = new EditContext();
editorElement.editContext = editContext;
editContext.addEventListener("characterboundsupdate", (e) => {
console.log(
`The OS needs the bounds of the chars at ${e.rangeStart} - ${e.rangeEnd}.`,
);
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/characterboundsupdateevent | data/mdn-content/files/en-us/web/api/characterboundsupdateevent/characterboundsupdateevent/index.md | ---
title: "CharacterBoundsUpdateEvent: CharacterBoundsUpdateEvent() constructor"
short-title: CharacterBoundsUpdateEvent()
slug: Web/API/CharacterBoundsUpdateEvent/CharacterBoundsUpdateEvent
page-type: web-api-constructor
status:
- experimental
browser-compat: api.CharacterBoundsUpdateEvent.CharacterBoundsUpdateEvent
---
{{APIRef("CharacterBoundsUpdateEvent API")}}{{SeeCompatTable}}
The **`CharacterBoundsUpdateEvent()`** constructor returns a new {{DOMxRef("CharacterBoundsUpdateEvent")}} object.
## Syntax
```js-nolint
new CharacterBoundsUpdateEvent(type)
new CharacterBoundsUpdateEvent(type, options)
```
### Parameters
- `type`
- : A string representing the type of the event. Possible values: `"characterboundsupdate"`.
- `options` {{optional_inline}}
- : An optional object with the following properties:
- `rangeStart`
- : A number to set the offset of the first character within the editable text region which this event applies to.
- `rangeEnd`
- : A number to set the offset of the last character within the editable text region which this event applies to.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The {{DOMxRef("CharacterBoundsUpdateEvent")}} interface it belongs to.
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/aesctrparams/index.md | ---
title: AesCtrParams
slug: Web/API/AesCtrParams
page-type: web-api-interface
spec-urls: https://w3c.github.io/webcrypto/#dfn-AesCtrParams
---
{{ APIRef("Web Crypto API") }}
The **`AesCtrParams`** dictionary of the [Web Crypto API](/en-US/docs/Web/API/Web_Crypto_API) represents the object that should be passed as the `algorithm` parameter into {{domxref("SubtleCrypto.encrypt()")}}, {{domxref("SubtleCrypto.decrypt()")}}, {{domxref("SubtleCrypto.wrapKey()")}}, or {{domxref("SubtleCrypto.unwrapKey()")}}, when using the [AES-CTR](/en-US/docs/Web/API/SubtleCrypto/encrypt#aes-ctr) algorithm.
AES is a block cipher, meaning that it splits the message into blocks and encrypts it a block at a time. In CTR mode, every time a block of the message is encrypted, an extra block of data is mixed in. This extra block is called the "counter block".
A given counter block value must never be used more than once with the same key:
- Given a message _n_ blocks long, a different counter block must be used for every block.
- If the same key is used to encrypt more than one message, a different counter block must be used for all blocks across all messages.
Typically this is achieved by splitting the initial counter block value into two concatenated parts:
- A [nonce](https://en.wikipedia.org/wiki/Cryptographic_nonce) (that is, a number that may only be used once). The nonce part of the block stays the same for every block in the message. Each time a new message is to be encrypted, a new nonce is chosen. Nonces don't have to be secret, but they must not be reused with the same key.
- A counter. This part of the block gets incremented each time a block is encrypted.
Essentially: the nonce should ensure that counter blocks are not reused from one message to the next, while the counter should ensure that counter blocks are not reused within a single message.
> **Note:** See [Appendix B of the NIST SP800-38A standard](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38a.pdf#%5B%7B%22num%22%3A70%2C%22gen%22%3A0%7D%2C%7B%22name%22%3A%22Fit%22%7D%5D) for more information.
## Instance properties
- `name`
- : A string. This should be set to `AES-CTR`.
- `counter`
- : An {{jsxref("ArrayBuffer")}}, a {{jsxref("TypedArray")}}, or a {{jsxref("DataView")}} — the initial value of the counter block. This must be 16 bytes long (the AES block size). The rightmost `length` bits of this block are used for the counter, and the rest is used for the nonce. For example, if `length` is set to 64, then the first half of `counter` is the nonce and the second half is used for the counter.
- `length`
- : A `Number` — the number of bits in the counter block that are used for the actual counter. The counter must be big enough that it doesn't wrap: if the message is `n` blocks and the counter is `m` bits long, then the following must be true: `n <= 2^m`. The [NIST SP800-38A](https://csrc.nist.gov/publications/detail/sp/800-38a/final) standard, which defines CTR, suggests that the counter should occupy half of the counter block (see [Appendix B.2](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38a.pdf#%5B%7B%22num%22%3A73%2C%22gen%22%3A0%7D%2C%7B%22name%22%3A%22Fit%22%7D%5D)), so for AES it would be 64.
## Examples
See the examples for {{domxref("SubtleCrypto.encrypt()")}} and {{domxref("SubtleCrypto.decrypt()")}}.
## Specifications
{{Specifications}}
## Browser compatibility
Browsers that support the "AES-CTR" algorithm for the {{domxref("SubtleCrypto.encrypt()")}}, {{domxref("SubtleCrypto.decrypt()")}}, {{domxref("SubtleCrypto.wrapKey()")}}, or {{domxref("SubtleCrypto.unwrapKey()")}} methods will support this type.
## See also
- CTR mode is defined in section 6.5 of the [NIST SP800-38A standard](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38a.pdf#%5B%7B%22num%22%3A70%2C%22gen%22%3A0%7D%2C%7B%22name%22%3A%22Fit%22%7D%5D).
- {{domxref("SubtleCrypto.encrypt()")}}.
- {{domxref("SubtleCrypto.decrypt()")}}.
- {{domxref("SubtleCrypto.wrapKey()")}}.
- {{domxref("SubtleCrypto.unwrapKey()")}}.
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/webglprogram/index.md | ---
title: WebGLProgram
slug: Web/API/WebGLProgram
page-type: web-api-interface
browser-compat: api.WebGLProgram
---
{{APIRef("WebGL")}}
The **`WebGLProgram`** is part of the [WebGL API](/en-US/docs/Web/API/WebGL_API) and is a combination of two compiled {{domxref("WebGLShader")}}s consisting of a vertex shader and a fragment shader (both written in GLSL).
{{InheritanceDiagram}}
To create a `WebGLProgram`, call the GL context's {{domxref("WebGLRenderingContext.createProgram", "createProgram()")}} function. After attaching the shader programs using {{domxref("WebGLRenderingContext.attachShader", "attachShader()")}}, you link them into a usable program. This is shown in the code below.
```js
const program = gl.createProgram();
// Attach pre-existing shaders
gl.attachShader(program, vertexShader);
gl.attachShader(program, fragmentShader);
gl.linkProgram(program);
if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
const info = gl.getProgramInfoLog(program);
throw `Could not compile WebGL program. \n\n${info}`;
}
```
See {{domxref("WebGLShader")}} for information on creating the `vertexShader` and `fragmentShader` in the above example.
## Examples
### Using the program
The steps to actually do some work with the program involve telling the GPU to use the program, bind the appropriate data and configuration options, and finally draw something to the screen.
```js
// Use the program
gl.useProgram(program);
// Bind existing attribute data
gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
gl.enableVertexAttribArray(attributeLocation);
gl.vertexAttribPointer(attributeLocation, 3, gl.FLOAT, false, 0, 0);
// Draw a single triangle
gl.drawArrays(gl.TRIANGLES, 0, 3);
```
### Deleting the program
If there is an error linking the program or you wish to delete an existing program, then it is as simple as running {{domxref("WebGLRenderingContext.deleteProgram()")}}. This frees the memory of the linked program.
```js
gl.deleteProgram(program);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("WebGLShader")}}
- {{domxref("WebGLRenderingContext.attachShader()")}}
- {{domxref("WebGLRenderingContext.compileShader()")}}
- {{domxref("WebGLRenderingContext.createProgram()")}}
- {{domxref("WebGLRenderingContext.createShader()")}}
- {{domxref("WebGLRenderingContext.deleteProgram()")}}
- {{domxref("WebGLRenderingContext.deleteShader()")}}
- {{domxref("WebGLRenderingContext.detachShader()")}}
- {{domxref("WebGLRenderingContext.getAttachedShaders()")}}
- {{domxref("WebGLRenderingContext.getProgramParameter()")}}
- {{domxref("WebGLRenderingContext.getProgramInfoLog()")}}
- {{domxref("WebGLRenderingContext.getShaderParameter()")}}
- {{domxref("WebGLRenderingContext.getShaderPrecisionFormat()")}}
- {{domxref("WebGLRenderingContext.getShaderInfoLog()")}}
- {{domxref("WebGLRenderingContext.getShaderSource()")}}
- {{domxref("WebGLRenderingContext.isProgram()")}}
- {{domxref("WebGLRenderingContext.isShader()")}}
- {{domxref("WebGLRenderingContext.linkProgram()")}}
- {{domxref("WebGLRenderingContext.shaderSource()")}}
- {{domxref("WebGLRenderingContext.useProgram()")}}
- {{domxref("WebGLRenderingContext.validateProgram()")}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/webusb_api/index.md | ---
title: WebUSB API
slug: Web/API/WebUSB_API
page-type: web-api-overview
status:
- experimental
spec-urls: https://wicg.github.io/webusb/
---
{{securecontext_header}}{{DefaultAPISidebar("WebUSB API")}}{{SeeCompatTable}}
The **WebUSB API** provides a way to expose non-standard Universal Serial Bus (USB) compatible devices services to the web, to make USB safer and easier to use.
## Concepts and Usage
USB is the de-facto standard for wired peripherals. The USB devices that you connect to your computer are typically grouped into a number of device classes—such as keyboards, mice, video devices, and so on. These are supported using the operating system's class driver. Many of these are also web accessible via the {{domxref("WebHID API")}}.
In addition to these standardized devices, there are a large number of devices that don't fit into any class. These need custom drivers, and are inaccessible from the web due to the native code required to take advantage of them. Installing one of these devices often involves searching on a manufacturer's website for drivers and, should you wish to use the device on another computer, repeating the process again.
WebUSB provides a way for these non-standardized USB device services to be exposed to the web. This means that hardware manufacturers will be able to provide a way for their device to be accessed from the web, without having to provide their own API.
When connecting a new WebUSB-compatible device, the browser displays a notification providing a link to the manufacturer's website. On arriving at the site the browser prompts for permission to connect to the device, then the device is ready for use. No drivers need be downloaded and installed.
## Interfaces
- {{domxref("USB")}}
- : Provides attributes and methods for finding and connecting USB devices from a web page.
- {{domxref("USBConnectionEvent")}}
- : The event type passed to `USB` {{domxref("USB.connect_event", "connect")}} or {{domxref("USB.disconnect_event", "disconnect")}} events when the user agent detects a new USB device has been connected to, or disconnected from the host.
- {{domxref("USBDevice")}}
- : Provides access to metadata about a paired USB device and methods for controlling it.
- {{domxref("USBInTransferResult")}}
- : Represents the result from requesting a transfer of data from the USB device to the USB host.
- {{domxref("USBOutTransferResult")}}
- : Represents the result from requesting a transfer of data from the USB host to the USB device.
- {{domxref("USBIsochronousInTransferPacket")}}
- : Represents the status of an individual packet from a request to transfer data from the USB device to the USB host over an isochronous endpoint.
- {{domxref("USBIsochronousInTransferResult")}}
- : Represents the result from requesting a transfer of data from the USB device to the USB host.
- {{domxref("USBIsochronousOutTransferPacket")}}
- : Represents the status of an individual packet from a request to transfer data from the USB host to the USB device over an isochronous endpoint.
- {{domxref("USBIsochronousOutTransferResult")}}
- : Represents the result from requesting a transfer of data from the USB host to the USB device.
- {{domxref("USBConfiguration")}}
- : Provides information about a particular configuration of a USB device and the interfaces that it supports.
- {{domxref("USBInterface")}}
- : Provides information about an interface provided by the USB device.
- {{domxref("USBAlternateInterface")}}
- : Provides information about a particular configuration of an interface provided by the USB device.
- {{domxref("USBEndPoint")}}
- : Provides information about an endpoint provided by the USB device.
## Examples
### Accessing a connected device
The following example demonstrates how to access a connected Arduino device using {{domxref("USB.requestDevice()")}}, which has a vendorId of `0x2341`.
```js
navigator.usb
.requestDevice({ filters: [{ vendorId: 0x2341 }] })
.then((device) => {
console.log(device.productName); // "Arduino Micro"
console.log(device.manufacturerName); // "Arduino LLC"
})
.catch((error) => {
console.error(error);
});
```
### Finding all connected devices
You can find all connected devices with {{domxref("USB.getDevices()")}}. In the following example, with the Arduino device connected, product and manufacturer name are printed to the console.
```js
navigator.usb.getDevices().then((devices) => {
devices.forEach((device) => {
console.log(device.productName); // "Arduino Micro"
console.log(device.manufacturerName); // "Arduino LLC"
});
});
```
## Specifications
{{Specifications}}
## See also
- [Access USB Devices on the Web](https://developer.chrome.com/docs/capabilities/usb)
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/mediastreamevent/index.md | ---
title: MediaStreamEvent
slug: Web/API/MediaStreamEvent
page-type: web-api-interface
status:
- deprecated
- non-standard
browser-compat: api.MediaStreamEvent
---
{{APIRef("WebRTC")}}{{Deprecated_Header}}{{Non-standard_Header}}
The **`MediaStreamEvent`** interface represents events that occurs in relation to a {{domxref("MediaStream")}}. Two events of this type can be thrown: {{domxref("RTCPeerConnection.addstream_event", "addstream")}} and {{domxref("RTCPeerConnection.removestream_event", "removestream")}}.
## Instance properties
_A {{domxref("MediaStreamEvent")}} being an {{domxref("Event")}}, this event also implements these properties_.
- {{domxref("MediaStreamEvent.stream")}} {{ReadOnlyInline}} {{Deprecated_Inline}} {{Non-standard_Inline}}
- : Contains the {{domxref("MediaStream")}} containing the stream associated with the event.
## Constructors
- {{domxref("MediaStreamEvent.MediaStreamEvent()", "MediaStreamEvent()")}} {{Deprecated_Inline}} {{Non-standard_Inline}}
- : Returns a new `MediaStreamEvent`. It takes two parameters, the first being a string representing the type of the event; the second a dictionary containing the {{domxref("MediaStream")}} it refers to.
## Instance methods
A {{domxref("MediaStreamEvent")}} being an {{domxref("Event")}}, this event also implements these properties. There is no specific {{domxref("MediaStreamEvent")}} method.
## Examples
```js
pc.onaddstream = (ev) => {
alert(`A stream (id: '${ev.stream.id}') has been added to this connection.`);
};
```
## Browser compatibility
{{Compat}}
## See also
- [WebRTC](/en-US/docs/Web/API/WebRTC_API)
- Its usual target: {{domxref("RTCPeerConnection")}}.
| 0 |
data/mdn-content/files/en-us/web/api/mediastreamevent | data/mdn-content/files/en-us/web/api/mediastreamevent/stream/index.md | ---
title: "MediaStreamEvent: stream property"
short-title: stream
slug: Web/API/MediaStreamEvent/stream
page-type: web-api-instance-property
status:
- deprecated
- non-standard
browser-compat: api.MediaStreamEvent.stream
---
{{APIRef("WebRTC")}}{{deprecated_header}}{{Non-standard_header}}
The read-only property **`MediaStreamEvent.stream`** returns
the {{domxref("MediaStream")}} associated with the event.
## Syntax
```js-nolint
event.stream
```
## Example
```js
pc.onaddstream = (ev) => {
alert(`A stream (id: '${ev.stream.id}') has been added to this connection.`);
};
```
## Browser compatibility
{{Compat}}
## See also
- {{domxref("RTCPeerConnection.addstream_event", "addstream")}}, {{domxref("RTCPeerConnection.removestream_event", "removestream")}}
- {{domxref("RTCPeerConnection")}}
| 0 |
data/mdn-content/files/en-us/web/api/mediastreamevent | data/mdn-content/files/en-us/web/api/mediastreamevent/mediastreamevent/index.md | ---
title: "MediaStreamEvent: MediaStreamEvent() constructor"
short-title: MediaStreamEvent()
slug: Web/API/MediaStreamEvent/MediaStreamEvent
page-type: web-api-constructor
status:
- deprecated
- non-standard
browser-compat: api.MediaStreamEvent.MediaStreamEvent
---
{{APIRef("WebRTC")}}{{Deprecated_Header}}{{Non-standard_Header}}
The **`MediaStreamEvent()`** constructor creates a new {{domxref("MediaStreamEvent")}} object.
## Syntax
```js-nolint
new MediaStreamEvent(type, options)
```
### Values
- `type`
- : A string with the name of the event, like `addstream` or `removestream`.
- `options`
- : An object that, in addition of the properties defined in {{domxref("Event/Event", "Event()")}}, can have the following properties:
- `stream`
- : A {{domxref("MediaStream")}} representing the stream being concerned by the event.
### Return value
A new {{domxref("MediaStreamEvent")}} object.
## Example
```js
// s is a MediaStream
const event = new MediaStreamEvent("addstream", { stream: s });
```
## Specifications
_This feature is no more part of any specification._
## Browser compatibility
{{Compat}}
## See also
- [WebRTC](/en-US/docs/Web/API/WebRTC_API)
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/gpurenderpipeline/index.md | ---
title: GPURenderPipeline
slug: Web/API/GPURenderPipeline
page-type: web-api-interface
status:
- experimental
browser-compat: api.GPURenderPipeline
---
{{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`GPURenderPipeline`** interface of the {{domxref("WebGPU API", "WebGPU API", "", "nocode")}} represents a pipeline that controls the vertex and fragment shader stages and can be used in a {{domxref("GPURenderPassEncoder")}} or {{domxref("GPURenderBundleEncoder")}}.
A `GPURenderPipeline` object instance can be created using the {{domxref("GPUDevice.createRenderPipeline()")}} or {{domxref("GPUDevice.createRenderPipelineAsync()")}} methods.
{{InheritanceDiagram}}
## Instance properties
- {{domxref("GPURenderPipeline.label", "label")}} {{Experimental_Inline}}
- : A string providing a label that can be used to identify the object, for example in {{domxref("GPUError")}} messages or console warnings.
## Instance methods
- {{domxref("GPURenderPipeline.getBindGroupLayout", "getBindGroupLayout()")}} {{Experimental_Inline}}
- : Returns the pipeline's {{domxref("GPUBindGroupLayout")}} object with the given index (i.e. included in the originating {{domxref("GPUDevice.createRenderPipeline()")}} or {{domxref("GPUDevice.createRenderPipelineAsync()")}} call's pipeline layout).
## Examples
> **Note:** The [WebGPU samples](https://webgpu.github.io/webgpu-samples/) feature many more examples.
### Basic example
Our [basic render demo](https://mdn.github.io/dom-examples/webgpu-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
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The [WebGPU API](/en-US/docs/Web/API/WebGPU_API)
| 0 |
data/mdn-content/files/en-us/web/api/gpurenderpipeline | data/mdn-content/files/en-us/web/api/gpurenderpipeline/getbindgrouplayout/index.md | ---
title: "GPURenderPipeline: getBindGroupLayout() method"
short-title: getBindGroupLayout()
slug: Web/API/GPURenderPipeline/getBindGroupLayout
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.GPURenderPipeline.getBindGroupLayout
---
{{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`getBindGroupLayout()`** method of the
{{domxref("GPURenderPipeline")}} interface returns the pipeline's {{domxref("GPUBindGroupLayout")}} object with the given index (i.e. included in the originating {{domxref("GPUDevice.createRenderPipeline()")}} or {{domxref("GPUDevice.createRenderPipelineAsync()")}} call's pipeline layout).
If the {{domxref("GPURenderPipeline")}} was created with `layout: "auto"`, this method is the only way to retrieve the {{domxref("GPUBindGroupLayout")}}s generated by the pipeline.
## Syntax
```js-nolint
getBindGroupLayout(index)
```
### Parameters
- `index`
- : A number representing the index of the {{domxref("GPUBindGroupLayout")}} to return.
### Return value
A {{domxref("GPUBindGroupLayout")}} object instance.
### Validation
The following criteria must be met when calling **`getBindGroupLayout()`**, otherwise a {{domxref("GPUValidationError")}} is generated and an invalid {{domxref("GPUBindGroupLayout")}} object is returned:
- `index` is less than the number of {{domxref("GPUBindGroupLayout")}} objects used in the pipeline layout.
## Examples
> **Note:** You can see complete working examples with `getBindGroupLayout()` in action in the [WebGPU samples](https://webgpu.github.io/webgpu-samples/).
```js
// ...
// Create a render pipeline using layout: "auto" to automatically generate
// appropriate bind group layouts
const fullscreenQuadPipeline = device.createRenderPipeline({
layout: "auto",
vertex: {
module: device.createShaderModule({
code: fullscreenTexturedQuadWGSL,
}),
entryPoint: "vert_main",
},
fragment: {
module: device.createShaderModule({
code: fullscreenTexturedQuadWGSL,
}),
entryPoint: "frag_main",
targets: [
{
format: presentationFormat,
},
],
},
primitive: {
topology: "triangle-list",
},
});
// ...
// Create a bind group with the auto-generated layout from the render pipeline
const showResultBindGroup = device.createBindGroup({
layout: fullscreenQuadPipeline.getBindGroupLayout(0),
entries: [
{
binding: 0,
resource: sampler,
},
{
binding: 1,
resource: textures[1].createView(),
},
],
});
// ...
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The [WebGPU API](/en-US/docs/Web/API/WebGPU_API)
| 0 |
data/mdn-content/files/en-us/web/api/gpurenderpipeline | data/mdn-content/files/en-us/web/api/gpurenderpipeline/label/index.md | ---
title: "GPURenderPipeline: label property"
short-title: label
slug: Web/API/GPURenderPipeline/label
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.GPURenderPipeline.label
---
{{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`label`** property of the
{{domxref("GPURenderPipeline")}} interface provides a label that can be used to identify the object, for example in {{domxref("GPUError")}} messages or console warnings.
This can be set by providing a `label` property in the descriptor object passed into the originating {{domxref("GPUDevice.createRenderPipeline()")}} or {{domxref("GPUDevice.createRenderPipelineAsync()")}} call, or you can get and set it directly on the `GPURenderPipeline` object.
## Value
A string. If this has not been previously set as described above, it will be an empty string.
## Examples
Setting and getting a label via `GPURenderPipeline.label`:
```js
// ...
const pipelineDescriptor = {
vertex: {
module: shaderModule,
entryPoint: "vertex_main",
buffers: vertexBuffers,
},
fragment: {
module: shaderModule,
entryPoint: "fragment_main",
targets: [
{
format: navigator.gpu.getPreferredCanvasFormat(),
},
],
},
primitive: {
topology: "triangle-list",
},
layout: "auto",
};
const renderPipeline = device.createRenderPipeline(pipelineDescriptor);
renderPipeline.label = "myrenderpipeline";
console.log(renderPipeline.label); // "myrenderpipeline"
```
Setting a label via a {{domxref("GPUDevice.createRenderPipeline()")}} call, and then getting it via `GPURenderPipeline.label`:
```js
// ...
const pipelineDescriptor = {
vertex: {
module: shaderModule,
entryPoint: "vertex_main",
buffers: vertexBuffers,
},
fragment: {
module: shaderModule,
entryPoint: "fragment_main",
targets: [
{
format: navigator.gpu.getPreferredCanvasFormat(),
},
],
},
primitive: {
topology: "triangle-list",
},
layout: "auto",
label: "myrenderpipeline",
};
const renderPipeline = device.createRenderPipeline(pipelineDescriptor);
console.log(renderPipeline.label); // "myrenderpipeline"
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The [WebGPU API](/en-US/docs/Web/API/WebGPU_API)
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/vrstageparameters/index.md | ---
title: VRStageParameters
slug: Web/API/VRStageParameters
page-type: web-api-interface
status:
- deprecated
- non-standard
browser-compat: api.VRStageParameters
---
{{APIRef("WebVR API")}}{{Deprecated_Header}}{{Non-standard_Header}}
The **`VRStageParameters`** interface of the [WebVR API](/en-US/docs/Web/API/WebVR_API) represents the values describing the stage area for devices that support room-scale experiences.
> **Note:** This interface was part of the old [WebVR API](https://immersive-web.github.io/webvr/spec/1.1/). It has been superseded by the [WebXR Device API](https://immersive-web.github.io/webxr/).
This interface is accessible through the {{domxref("VRDisplay.stageParameters")}} property.
## Instance properties
- {{domxref("VRStageParameters.sittingToStandingTransform")}} {{Deprecated_Inline}} {{ReadOnlyInline}} {{Non-standard_Inline}}
- : Contains a matrix that transforms the sitting-space view matrices of {{domxref("VRFrameData")}} to standing-space.
- {{domxref("VRStageParameters.sizeX")}} {{Deprecated_Inline}} {{ReadOnlyInline}} {{Non-standard_Inline}}
- : _Returns the width_ of the play-area bounds in meters.
- {{domxref("VRStageParameters.sizeY")}} {{Deprecated_Inline}} {{ReadOnlyInline}} {{Non-standard_Inline}}
- : _Returns the depth_ of the play-area bounds in meters.
## Examples
```js
const info = document.querySelector("p");
let vrDisplay;
navigator.getVRDisplays().then((displays) => {
vrDisplay = displays[0];
const stageParams = vrDisplay.stageParameters;
// stageParams is a VRStageParameters object
if (stageParams === null) {
info.textContent =
"Your VR Hardware does not support room-scale experiences.";
} else {
info.innerHTML =
`<strong>Display stage parameters</strong><br>` +
`Sitting to standing transform: ${stageParams.sittingToStandingTransform}<br>` +
`Play area width (m): ${stageParams.sizeX}<br>` +
`Play area depth (m): ${stageParams.sizeY}`;
}
});
```
## Specifications
This interface was part of the old [WebVR API](https://immersive-web.github.io/webvr/spec/1.1/) that has been superseded by the [WebXR Device API](https://immersive-web.github.io/webxr/). It is no longer on track to becoming a standard.
Until all browsers have implemented the new [WebXR APIs](/en-US/docs/Web/API/WebXR_Device_API/Fundamentals), it is recommended to rely on frameworks, like [A-Frame](https://aframe.io/), [Babylon.js](https://www.babylonjs.com/), or [Three.js](https://threejs.org/), or a [polyfill](https://github.com/immersive-web/webxr-polyfill), to develop WebXR applications that will work across all browsers [\[1\]](https://developer.oculus.com/documentation/web/port-vr-xr/).
## Browser compatibility
{{Compat}}
## See also
- [WebVR API](/en-US/docs/Web/API/WebVR_API)
| 0 |
data/mdn-content/files/en-us/web/api/vrstageparameters | data/mdn-content/files/en-us/web/api/vrstageparameters/sittingtostandingtransform/index.md | ---
title: "VRStageParameters: sittingToStandingTransform property"
short-title: sittingToStandingTransform
slug: Web/API/VRStageParameters/sittingToStandingTransform
page-type: web-api-instance-property
status:
- deprecated
- non-standard
browser-compat: api.VRStageParameters.sittingToStandingTransform
---
{{APIRef("WebVR API")}}{{Deprecated_Header}}{{Non-standard_Header}}
The **`sittingToStandingTransform`** read-only property of the {{domxref("VRStageParameters")}} interface contains a matrix that transforms the sitting-space view matrices of {{domxref("VRFrameData")}} to standing-space.
> **Note:** This property was part of the old [WebVR API](https://immersive-web.github.io/webvr/spec/1.1/). It has been superseded by the [WebXR Device API](https://immersive-web.github.io/webxr/).
Basically, this can be passed into your WebGL code to transform the rendered view from a sitting to standing view.
## Value
A 16-element {{jsxref("Float32Array")}} containing the components of a 4×4 transform matrix.
## Examples
See [`VRStageParameters`](/en-US/docs/Web/API/VRStageParameters#examples) for example code.
## Specifications
This property was part of the old [WebVR API](https://immersive-web.github.io/webvr/spec/1.1/) that has been superseded by the [WebXR Device API](https://immersive-web.github.io/webxr/). It is no longer on track to becoming a standard.
Until all browsers have implemented the new [WebXR APIs](/en-US/docs/Web/API/WebXR_Device_API/Fundamentals), it is recommended to rely on frameworks, like [A-Frame](https://aframe.io/), [Babylon.js](https://www.babylonjs.com/), or [Three.js](https://threejs.org/), or a [polyfill](https://github.com/immersive-web/webxr-polyfill), to develop WebXR applications that will work across all browsers [\[1\]](https://developer.oculus.com/documentation/web/port-vr-xr/).
## Browser compatibility
{{Compat}}
## See also
- [WebVR API](/en-US/docs/Web/API/WebVR_API)
| 0 |
data/mdn-content/files/en-us/web/api/vrstageparameters | data/mdn-content/files/en-us/web/api/vrstageparameters/sizey/index.md | ---
title: "VRStageParameters: sizeY property"
short-title: sizeY
slug: Web/API/VRStageParameters/sizeY
page-type: web-api-instance-property
status:
- deprecated
- non-standard
browser-compat: api.VRStageParameters.sizeY
---
{{APIRef("WebVR API")}}{{Deprecated_Header}}{{Non-standard_Header}}
The **`sizeY`** read-only property of the {{domxref("VRStageParameters")}} interface _returns the depth_ of the play-area bounds in meters.
> **Note:** This property was part of the old [WebVR API](https://immersive-web.github.io/webvr/spec/1.1/). It has been superseded by the [WebXR Device API](https://immersive-web.github.io/webxr/).
The bounds are defined as an axis-aligned rectangle on the floor, for safety purposes. Content should not require the user to move beyond these bounds; however, it is possible for the user to ignore the bounds resulting in position values outside of this rectangle. The center of the rectangle is at (0,0,0) in standing-space coordinates.
## Value
A float representing the depth in meters.
## Examples
See [`VRStageParameters`](/en-US/docs/Web/API/VRStageParameters#examples) for example code.
## Specifications
This property was part of the old [WebVR API](https://immersive-web.github.io/webvr/spec/1.1/) that has been superseded by the [WebXR Device API](https://immersive-web.github.io/webxr/). It is no longer on track to becoming a standard.
Until all browsers have implemented the new [WebXR APIs](/en-US/docs/Web/API/WebXR_Device_API/Fundamentals), it is recommended to rely on frameworks, like [A-Frame](https://aframe.io/), [Babylon.js](https://www.babylonjs.com/), or [Three.js](https://threejs.org/), or a [polyfill](https://github.com/immersive-web/webxr-polyfill), to develop WebXR applications that will work across all browsers [\[1\]](https://developer.oculus.com/documentation/web/port-vr-xr/).
## Browser compatibility
{{Compat}}
## See also
- [WebVR API](/en-US/docs/Web/API/WebVR_API)
| 0 |
data/mdn-content/files/en-us/web/api/vrstageparameters | data/mdn-content/files/en-us/web/api/vrstageparameters/sizex/index.md | ---
title: "VRStageParameters: sizeX property"
short-title: sizeX
slug: Web/API/VRStageParameters/sizeX
page-type: web-api-instance-property
status:
- deprecated
- non-standard
browser-compat: api.VRStageParameters.sizeX
---
{{APIRef("WebVR API")}}{{Deprecated_Header}}{{Non-standard_Header}}
The **`sizeX`** read-only property of the {{domxref("VRStageParameters")}} interface _returns the width_ of the play-area bounds in meters.
> **Note:** This property was part of the old [WebVR API](https://immersive-web.github.io/webvr/spec/1.1/). It has been superseded by the [WebXR Device API](https://immersive-web.github.io/webxr/).
The bounds are defined as an axis-aligned rectangle on the floor, for safety purposes. Content should not require the user to move beyond these bounds; however, it is possible for the user to ignore the bounds resulting in position values outside of this rectangle. The center of the rectangle is at (0,0,0) in standing-space coordinates.
## Value
A float representing the width in meters.
## Examples
See [`VRStageParameters`](/en-US/docs/Web/API/VRStageParameters#examples) for example code.
## Specifications
This property was part of the old [WebVR API](https://immersive-web.github.io/webvr/spec/1.1/) that has been superseded by the [WebXR Device API](https://immersive-web.github.io/webxr/). It is no longer on track to becoming a standard.
Until all browsers have implemented the new [WebXR APIs](/en-US/docs/Web/API/WebXR_Device_API/Fundamentals), it is recommended to rely on frameworks, like [A-Frame](https://aframe.io/), [Babylon.js](https://www.babylonjs.com/), or [Three.js](https://threejs.org/), or a [polyfill](https://github.com/immersive-web/webxr-polyfill), to develop WebXR applications that will work across all browsers [\[1\]](https://developer.oculus.com/documentation/web/port-vr-xr/).
## Browser compatibility
{{Compat}}
## See also
- [WebVR API](/en-US/docs/Web/API/WebVR_API)
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/worklet/index.md | ---
title: Worklet
slug: Web/API/Worklet
page-type: web-api-interface
browser-compat: api.Worklet
---
{{APIRef("Worklets")}}{{SecureContext_Header}}
The **`Worklet`** interface is a lightweight version of {{domxref("Worker", "Web Workers")}} and gives developers access to low-level parts of the rendering pipeline.
With Worklets, you can run JavaScript and [WebAssembly](/en-US/docs/WebAssembly) code to do graphics rendering or audio processing where high performance is required.
Worklets allow static import of [ECMAScript modules](/en-US/docs/Web/JavaScript/Guide/Modules), if supported, using [`import`](/en-US/docs/Web/JavaScript/Reference/Statements/import).
Dynamic import is disallowed by the specification — calling [`import()`](/en-US/docs/Web/JavaScript/Reference/Operators/import) will throw.
## Worklet types
Worklets are restricted to specific use cases; they cannot be used for arbitrary computations like Web Workers. The `Worklet` interface abstracts properties and methods common to all kind of worklets, and cannot be created directly. Instead, you can use one of the following classes:
<table class="no-markdown">
<thead>
<tr>
<th>Name</th>
<th>Description</th>
<th>Location</th>
<th>Specification</th>
</tr>
</thead>
<tbody>
<tr>
<td>{{domxref("AudioWorklet")}}</td>
<td>For audio processing with custom AudioNodes.</td>
<td>Web Audio render thread</td>
<td>
<a href="https://webaudio.github.io/web-audio-api/#AudioWorklet"
>Web Audio API</a
>
</td>
</tr>
<tr>
<td>{{domxref("AnimationWorklet")}}</td>
<td>
For creating scroll-linked and other high performance procedural
animations.
</td>
<td>Compositor thread</td>
<td>
<a href="https://wicg.github.io/animation-worklet/"
>CSS Animation Worklet API</a
>
</td>
</tr>
<tr>
<td>{{domxref("LayoutWorklet")}}</td>
<td>For defining the positioning and dimensions of custom elements.</td>
<td></td>
<td>
<a
href="https://drafts.css-houdini.org/css-layout-api-1/#layout-worklet"
>CSS Layout API</a
>
</td>
</tr>
<tr>
<td>{{domxref("SharedStorageWorklet")}}</td>
<td>For running private operations on cross-site data, without risk of data leakage.</td>
<td>Main thread</td>
<td>
<a
href="https://wicg.github.io/shared-storage/"
>Shared Storage API</a
>
</td>
</tr>
</tbody>
</table>
> **Note:** Paint worklets, defined by the [CSS Painting API](/en-US/docs/Web/API/CSS_Painting_API), don't subclass {{domxref("Worklet")}}. They are accessed through a regular `Worklet` object obtained using {{DOMxref("CSS.paintWorklet_static", "CSS.paintWorklet")}}.
For 3D rendering with [WebGL](/en-US/docs/Web/API/WebGL_API), you don't use worklets. Instead, you write vertex shaders and fragment shaders using GLSL code, and those shaders will then run on the graphics card.
## Instance properties
_The Worklet interface does not define any properties._
## Instance methods
- {{domxref("Worklet.addModule()")}}
- : Adds the script module at the given URL to the current worklet.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Houdini: Demystifying CSS](https://developer.chrome.com/blog/houdini/) on Google Developers (2016)
- [AudioWorklet :: What, Why, and How](https://www.youtube.com/watch?v=g1L4O1smMC0&t=1m33s) on YouTube (2017)
- [Enter AudioWorklet](https://developer.chrome.com/blog/audio-worklet/) on Google Developers (2017)
- [Animation Worklet - HTTP203 Advent](https://www.youtube.com/watch?v=ZPkMMShYxKU&t=0m19s) on YouTube (2017)
| 0 |
data/mdn-content/files/en-us/web/api/worklet | data/mdn-content/files/en-us/web/api/worklet/addmodule/index.md | ---
title: "Worklet: addModule() method"
short-title: addModule()
slug: Web/API/Worklet/addModule
page-type: web-api-instance-method
browser-compat: api.Worklet.addModule
---
{{APIRef("Worklets")}}{{SecureContext_Header}}
The **`addModule()`** method of the
{{domxref("Worklet")}} interface loads the module in the given JavaScript file and
adds it to the current `Worklet`.
## Syntax
```js-nolint
addModule(moduleURL)
addModule(moduleURL, options)
```
### Parameters
- `moduleURL`
- : A {{jsxref("String")}} containing the URL of a JavaScript file with the module to
add.
- `options` {{optional_inline}}
- : An object with any of the following options:
- `credentials`
- : A {{domxref("Request.credentials")}} value that
indicates whether to send credentials (e.g. cookies and HTTP authentication)
when loading the module. Can be one of `"omit"`,
`"same-origin"`, or `"include"`. Defaults to
`"same-origin"`. See also {{domxref("Request.credentials")}}.
### Return value
A {{jsxref("Promise")}} that resolves once the module from the given URL has been
added. The promise doesn't return any value.
### Exceptions
If `addModule()` fails, it rejects the promise, delivering one of the
following errors to the rejection handler.
- `AbortError` {{domxref("DOMException")}}
- : The specified script is invalid or could not be loaded.
- `SyntaxError` {{domxref("DOMException")}}
- : The specified `moduleURL` is invalid.
## Examples
### AudioWorklet example
```js
const audioCtx = new AudioContext();
const audioWorklet = audioCtx.audioWorklet;
audioWorklet.addModule("modules/bypassFilter.js", {
credentials: "omit",
});
```
### PaintWorklet example
```js
CSS.paintWorklet.addModule(
"https://mdn.github.io/houdini-examples/cssPaint/intro/worklets/hilite.js",
);
```
Once the script has been added to the [paint worklet](/en-US/docs/Web/API/CSS/paintWorklet_static), the CSS {{cssxref("image/paint", "paint()")}} function
can be used to include the image created by the worklet:
```css
@supports (background-image: paint(id)) {
h1 {
background-image: paint(hollowHighlights, filled, 3px);
}
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/xrhand/hand.svg | <svg xmlns="http://www.w3.org/2000/svg" width="390.024" height="538.377" viewBox="0 0 103.194 142.445"><path style="fill:#dde3e3;fill-opacity:1;stroke:#000;stroke-width:.56179392;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1" d="M69.83 156.288c-2.208-8.56-4.393-17.113-8.163-26.12-7.634-3.082-14.808-11.671-21.996-20.105-2.546-5.212-5.019-10.425-9.794-15.637-2.9-5.367-6.559-10.418-10.397-15.165-1.1-4.987 4.005-6.858 8.592-5.886 4.588.972 9.602 5.937 12.459 9.881 3.277 2.88 6.105 6.21 8.935 9.537.852-5.43 4.202-9.273 4.21-19.847-1.713-6.043-3.098-12.086-4.124-18.13-1.04-4.639-1.816-9.279-1.718-13.918-.654-4.91-.528-12.055.558-15.08 1.087-3.023 5.039-3.969 7.303-1.546 2.265 2.423 3.27 9.665 3.91 14.22a904.244 904.244 0 0 0 3.093 12.029c1.408 3.994 2.758 7.414 4.382 13.575 1.772 1.752 3.577 1.807 4.382-1.03-.298-5.365-.721-10.753.086-15.896-.384-6.312.997-10.86 1.632-16.153.62-4.611 1.749-11.176 3.265-13.833s8.447-3.454 9.108.687c.66 4.142-.238 8.835-.344 13.747-.106 4.913.127 10.712-.172 16.067.023 5.07-.28 10.139-.945 15.208.455 1.144.201 3.941 2.578.602l3.007-10.912c.796-4.731 2.019-9.036 3.265-13.318.815-4.582 1.664-11.266 3.35-13.79 2.356-3.524 8.646-2.318 9.151 1.633.61 4.767-.685 9.784-1.332 14.133l-1.89 16.583c-1.505 4.296-2.59 8.592-3.179 12.888.29 2.698.599 5.355 3.35 2.234 1.013-2.882 2.192-4.993 3.438-7.217 1.615-3.398 2.98-5.094 4.382-8.335 1.401-3.24 2.51-8.044 4.64-10.74 2.129-2.695 6.752-1.87 7.045 2.32.292 4.191-.362 8.685-1.89 12.802-1.052 3.362-2.637 6.99-4.125 10.568-1.07 3.141-2.311 6.109-3.608 9.022-.36 4.958-1.577 9.701-2.836 14.435-1 7.014-2.304 14.003-6.014 20.792a52.71 52.71 0 0 1 0 8.506c1.522 7.876 3.665 15.752 6.1 23.628-9.943 6.576-22.88 9.46-39.695 7.561z" transform="translate(-19.052 -14.697)"/><path d="m25.665 110.204 15.478 16.537 16.933 24.077s28.707 24.077 59.531 48.154l-19.579-38.365-12.568-53.049-8.995-37.835-4.366-21.96-1.984-15.875" style="fill:none;stroke:#000;stroke-width:2.56500006;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:5.13000018,2.56500009;stroke-dashoffset:0;stroke-opacity:.4679803" transform="translate(-12.374 -9.545) scale(.64947)"/><path d="m144.547 33.247-3.38 18.27-4.556 22.82-6.636 39.006-4.387 43.303-7.98 42.326-5.994-41.967-1.973-51.365.65-42.659 2.422-26.331 1.72-15.743" style="fill:none;stroke:#000;stroke-width:2.56500006;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:5.13000024,2.56500012;stroke-dashoffset:0;stroke-opacity:.4679803" transform="translate(-12.374 -9.545) scale(.64947)"/><path d="m172.245 66.403-4.437 14.17-7.467 16.47-11.928 29.348-12.457 34.704-18.349 37.877" style="fill:none;stroke:#000;stroke-width:2.56500006;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:5.1300003,2.56500015;stroke-dashoffset:0;stroke-opacity:.4679803" transform="translate(-12.374 -9.545) scale(.64947)"/><g transform="translate(-12.374 -9.545) scale(.64947)"><circle r="8.864" cy="199.369" cx="117.872" style="opacity:1;fill:#adacac;fill-opacity:1;stroke-width:.26458332"/><text y="201.75" x="115.358" style="font-style:normal;font-weight:400;font-size:10.58333302px;line-height:1.25;font-family:sans-serif;letter-spacing:0;word-spacing:0;fill:#000;fill-opacity:1;stroke:none;stroke-width:.26458332" xml:space="preserve"><tspan style="stroke-width:.26458332" y="201.75" x="115.358"><tspan style="font-size:7.05555534px">0</tspan></tspan></text></g><g transform="translate(-32.412 -25.698) scale(.64947)"><circle r="5.424" cy="199.369" cx="117.872" style="opacity:1;fill:#00ac00;fill-opacity:1;stroke-width:.16190919"/><text y="201.75" x="115.623" style="font-style:normal;font-weight:400;font-size:10.58333302px;line-height:1.25;font-family:sans-serif;letter-spacing:0;word-spacing:0;fill:#000;fill-opacity:1;stroke:none;stroke-width:.26458332" xml:space="preserve"><tspan style="stroke-width:.26458332" y="201.75" x="115.623"><tspan style="font-size:7.05555534px">1</tspan> </tspan></text></g><g transform="translate(-51.133 -41.078) scale(.64947)"><circle r="5.424" cy="199.369" cx="117.872" style="opacity:1;fill:#00ac00;fill-opacity:1;stroke-width:.16190919"/><text y="201.75" x="115.623" style="font-style:normal;font-weight:400;font-size:10.58333302px;line-height:1.25;font-family:sans-serif;letter-spacing:0;word-spacing:0;fill:#000;fill-opacity:1;stroke:none;stroke-width:.26458332" xml:space="preserve"><tspan style="stroke-width:.26458332" y="201.75" x="115.623"><tspan style="font-size:7.05555534px">2</tspan> </tspan></text></g><g transform="translate(-62.424 -56.63) scale(.64947)"><circle r="5.424" cy="199.369" cx="117.872" style="opacity:1;fill:#00ac00;fill-opacity:1;stroke-width:.16190919"/><text y="201.75" x="115.623" style="font-style:normal;font-weight:400;font-size:10.58333302px;line-height:1.25;font-family:sans-serif;letter-spacing:0;word-spacing:0;fill:#000;fill-opacity:1;stroke:none;stroke-width:.26458332" xml:space="preserve"><tspan style="stroke-width:.26458332" y="201.75" x="115.623"><tspan style="font-size:7.05555534px">3</tspan> </tspan></text><circle r="5.424" cy="182.965" cx="102.831" style="opacity:1;fill:#00ac00;fill-opacity:1;stroke-width:.16190919"/><text y="185.346" x="100.582" style="font-style:normal;font-weight:400;font-size:10.58333302px;line-height:1.25;font-family:sans-serif;letter-spacing:0;word-spacing:0;fill:#000;fill-opacity:1;stroke:none;stroke-width:.26458332" xml:space="preserve"><tspan style="stroke-width:.26458332" y="185.346" x="100.582"><tspan style="font-size:7.05555534px;stroke-width:.26458332">4</tspan> </tspan></text></g><g transform="translate(-25.186 -34.548) scale(.64947)"><circle r="5.424" cy="199.369" cx="117.872" style="opacity:1;fill:#484aff;fill-opacity:1;stroke-width:.16190919"/><text y="201.75" x="115.623" style="font-style:normal;font-weight:400;font-size:10.58333302px;line-height:1.25;font-family:sans-serif;letter-spacing:0;word-spacing:0;fill:#000;fill-opacity:1;stroke:none;stroke-width:.26458332" xml:space="preserve"><tspan style="stroke-width:.26458332" y="201.75" x="115.623"><tspan style="font-size:7.05555534px">5</tspan> </tspan></text></g><g transform="translate(-33.338 -68.916) scale(.64947)"><circle r="5.424" cy="199.369" cx="117.872" style="opacity:1;fill:#484aff;fill-opacity:1;stroke-width:.16190919"/><text y="201.75" x="115.623" style="font-style:normal;font-weight:400;font-size:10.58333302px;line-height:1.25;font-family:sans-serif;letter-spacing:0;word-spacing:0;fill:#000;fill-opacity:1;stroke:none;stroke-width:.26458332" xml:space="preserve"><tspan style="stroke-width:.26458332" y="201.75" x="115.623"><tspan style="font-size:7.05555534px">6</tspan> </tspan></text><g transform="translate(-9.128 -37.703)"><circle r="5.424" cy="199.369" cx="117.872" style="opacity:1;fill:#484aff;fill-opacity:1;stroke-width:.16190919"/><text y="201.75" x="115.623" style="font-style:normal;font-weight:400;font-size:10.58333302px;line-height:1.25;font-family:sans-serif;letter-spacing:0;word-spacing:0;fill:#000;fill-opacity:1;stroke:none;stroke-width:.26458332" xml:space="preserve"><tspan style="stroke-width:.26458332" y="201.75" x="115.623"><tspan style="font-size:7.05555534px">7</tspan> </tspan></text><g transform="translate(-4.233 -22.622)"><circle r="5.424" cy="199.369" cx="117.872" style="opacity:1;fill:#484aff;fill-opacity:1;stroke-width:.16190919"/><text y="201.75" x="115.623" style="font-style:normal;font-weight:400;font-size:10.58333302px;line-height:1.25;font-family:sans-serif;letter-spacing:0;word-spacing:0;fill:#000;fill-opacity:1;stroke:none;stroke-width:.26458332" xml:space="preserve"><tspan style="stroke-width:.26458332" y="201.75" x="115.623"><tspan style="font-size:7.05555534px">8</tspan> </tspan></text></g></g></g><g transform="translate(-43.305 -118.062) scale(.64947)"><circle r="5.424" cy="199.369" cx="117.872" style="opacity:1;fill:#484aff;fill-opacity:1;stroke-width:.16190919"/><text y="201.75" x="115.623" style="font-style:normal;font-weight:400;font-size:10.58333302px;line-height:1.25;font-family:sans-serif;letter-spacing:0;word-spacing:0;fill:#000;fill-opacity:1;stroke:none;stroke-width:.26458332" xml:space="preserve"><tspan style="stroke-width:.26458332" y="201.75" x="115.623"><tspan style="font-size:7.05555534px">9</tspan> </tspan></text></g><g transform="translate(-15.896 -37.297) scale(.64947)"><circle r="5.424" cy="199.369" cx="117.343" style="opacity:1;fill:#e70000;fill-opacity:1;stroke-width:.16190919"/><text y="201.75" x="112.713" style="font-style:normal;font-weight:400;font-size:10.58333302px;line-height:1.25;font-family:sans-serif;letter-spacing:0;word-spacing:0;fill:#000;fill-opacity:1;stroke:none;stroke-width:.26458332" xml:space="preserve"><tspan style="stroke-width:.26458332" y="201.75" x="112.713"><tspan style="font-size:7.05555534px">10</tspan> </tspan></text></g><g transform="translate(-17.529 -70.548) scale(.64947)"><circle r="5.424" cy="199.369" cx="117.872" style="opacity:1;fill:#e70000;fill-opacity:1;stroke-width:.16190919"/><text y="201.75" x="113.242" style="font-style:normal;font-weight:400;font-size:10.58333302px;line-height:1.25;font-family:sans-serif;letter-spacing:0;word-spacing:0;fill:#000;fill-opacity:1;stroke:none;stroke-width:.26458332" xml:space="preserve"><tspan style="stroke-width:.26458332" y="201.75" x="113.242"><tspan style="font-size:7.05555534px">11</tspan> </tspan></text></g><g transform="translate(-17.1 -98.129) scale(.64947)"><circle style="opacity:1;fill:#e70000;fill-opacity:1;stroke-width:.16190919" cx="117.872" cy="199.369" r="5.424"/><text xml:space="preserve" style="font-style:normal;font-weight:400;font-size:10.58333302px;line-height:1.25;font-family:sans-serif;letter-spacing:0;word-spacing:0;fill:#000;fill-opacity:1;stroke:none;stroke-width:.26458332" x="113.242" y="201.75"><tspan x="113.242" y="201.75" style="stroke-width:.26458332"><tspan style="font-size:7.05555534px">12</tspan> </tspan></text><g transform="translate(1.984 -25.93)"><circle style="opacity:1;fill:#e70000;fill-opacity:1;stroke-width:.16190919" cx="117.872" cy="199.369" r="5.424"/><text xml:space="preserve" style="font-style:normal;font-weight:400;font-size:10.58333302px;line-height:1.25;font-family:sans-serif;letter-spacing:0;word-spacing:0;fill:#000;fill-opacity:1;stroke:none;stroke-width:.26458332" x="113.242" y="201.75"><tspan x="113.242" y="201.75" style="stroke-width:.26458332"><tspan style="font-size:7.05555534px">13</tspan> </tspan></text><g transform="translate(2.117 -16.272)"><circle style="opacity:1;fill:#e70000;fill-opacity:1;stroke-width:.16190919" cx="117.872" cy="199.369" r="5.424"/><text xml:space="preserve" style="font-style:normal;font-weight:400;font-size:10.58333302px;line-height:1.25;font-family:sans-serif;letter-spacing:0;word-spacing:0;fill:#000;fill-opacity:1;stroke:none;stroke-width:.26458332" x="113.242" y="201.75"><tspan x="113.242" y="201.75" style="stroke-width:.26458332"><tspan style="font-size:7.05555534px">14</tspan> </tspan></text></g></g></g><g transform="translate(-8.164 -36.696) scale(.64947)"><circle style="opacity:1;fill:#e728e5;fill-opacity:1;stroke-width:.16190919" cx="117.872" cy="199.369" r="5.424"/><text xml:space="preserve" style="font-style:normal;font-weight:400;font-size:10.58333302px;line-height:1.25;font-family:sans-serif;letter-spacing:0;word-spacing:0;fill:#000;fill-opacity:1;stroke:none;stroke-width:.26458332" x="113.242" y="201.75"><tspan x="113.242" y="201.75" style="stroke-width:.26458332"><tspan style="font-size:7.05555534px">15</tspan> </tspan></text></g><g transform="translate(-4.555 -65.221) scale(.64947)"><circle style="opacity:1;fill:#e728e5;fill-opacity:1;stroke-width:.16190919" cx="117.872" cy="199.369" r="5.424"/><text xml:space="preserve" style="font-style:normal;font-weight:400;font-size:10.58333302px;line-height:1.25;font-family:sans-serif;letter-spacing:0;word-spacing:0;fill:#000;fill-opacity:1;stroke:none;stroke-width:.26458332" x="113.242" y="201.75"><tspan x="113.242" y="201.75" style="stroke-width:.26458332"><tspan style="font-size:7.05555534px">16</tspan> </tspan></text></g><g transform="translate(-.001 -90.482) scale(.64947)"><circle style="opacity:1;fill:#e728e5;fill-opacity:1;stroke-width:.16190919" cx="117.872" cy="199.369" r="5.424"/><text xml:space="preserve" style="font-style:normal;font-weight:400;font-size:10.58333302px;line-height:1.25;font-family:sans-serif;letter-spacing:0;word-spacing:0;fill:#000;fill-opacity:1;stroke:none;stroke-width:.26458332" x="113.242" y="201.75"><tspan x="113.242" y="201.75" style="stroke-width:.26458332"><tspan style="font-size:7.05555534px">17</tspan> </tspan></text></g><g transform="translate(3.264 -105.69) scale(.64947)"><circle style="opacity:1;fill:#e728e5;fill-opacity:1;stroke-width:.16190919" cx="117.872" cy="199.369" r="5.424"/><text xml:space="preserve" style="font-style:normal;font-weight:400;font-size:10.58333302px;line-height:1.25;font-family:sans-serif;letter-spacing:0;word-spacing:0;fill:#000;fill-opacity:1;stroke:none;stroke-width:.26458332" x="113.242" y="201.75"><tspan x="113.242" y="201.75" style="stroke-width:.26458332"><tspan style="font-size:7.05555534px">18</tspan> </tspan></text></g><g transform="translate(5.24 -117.203) scale(.64947)"><circle style="opacity:1;fill:#e728e5;fill-opacity:1;stroke-width:.16190919" cx="117.872" cy="199.369" r="5.424"/><text xml:space="preserve" style="font-style:normal;font-weight:400;font-size:10.58333302px;line-height:1.25;font-family:sans-serif;letter-spacing:0;word-spacing:0;fill:#000;fill-opacity:1;stroke:none;stroke-width:.26458332" x="113.242" y="201.75"><tspan x="113.242" y="201.75" style="stroke-width:.26458332"><tspan style="font-size:7.05555534px">19</tspan> </tspan></text></g><g transform="translate(-.43 -34.204) scale(.64947)"><circle style="opacity:1;fill:#e0ed00;fill-opacity:1;stroke-width:.16190919" cx="117.872" cy="199.369" r="5.424"/><text xml:space="preserve" style="font-style:normal;font-weight:400;font-size:10.58333302px;line-height:1.25;font-family:sans-serif;letter-spacing:0;word-spacing:0;fill:#000;fill-opacity:1;stroke:none;stroke-width:.26458332" x="113.242" y="201.75"><tspan x="113.242" y="201.75" style="stroke-width:.26458332"><tspan style="font-size:7.05555534px">20</tspan> </tspan></text></g><g transform="translate(7.302 -57.23) scale(.64947)"><circle style="opacity:1;fill:#e0ed00;fill-opacity:1;stroke-width:.16190919" cx="117.872" cy="199.369" r="5.424"/><text xml:space="preserve" style="font-style:normal;font-weight:400;font-size:10.58333302px;line-height:1.25;font-family:sans-serif;letter-spacing:0;word-spacing:0;fill:#000;fill-opacity:1;stroke:none;stroke-width:.26458332" x="113.242" y="201.75"><tspan x="113.242" y="201.75" style="stroke-width:.26458332"><tspan style="font-size:7.05555534px">21</tspan> </tspan></text></g><g transform="translate(15.12 -76.047) scale(.64947)"><circle style="opacity:1;fill:#e0ed00;fill-opacity:1;stroke-width:.16190919" cx="117.872" cy="199.369" r="5.424"/><text xml:space="preserve" style="font-style:normal;font-weight:400;font-size:10.58333302px;line-height:1.25;font-family:sans-serif;letter-spacing:0;word-spacing:0;fill:#000;fill-opacity:1;stroke:none;stroke-width:.26458332" x="113.242" y="201.75"><tspan x="113.242" y="201.75" style="stroke-width:.26458332"><tspan style="font-size:7.05555534px">22</tspan> </tspan></text></g><g transform="translate(20.018 -86.53) scale(.64947)"><circle style="opacity:1;fill:#e0ed00;fill-opacity:1;stroke-width:.16190919" cx="117.872" cy="199.369" r="5.424"/><text xml:space="preserve" style="font-style:normal;font-weight:400;font-size:10.58333302px;line-height:1.25;font-family:sans-serif;letter-spacing:0;word-spacing:0;fill:#000;fill-opacity:1;stroke:none;stroke-width:.26458332" x="113.242" y="201.75"><tspan x="113.242" y="201.75" style="stroke-width:.26458332"><tspan style="font-size:7.05555534px">23</tspan> </tspan></text></g><g transform="translate(22.682 -95.723) scale(.64947)"><circle style="opacity:1;fill:#e0ed00;fill-opacity:1;stroke-width:.16190919" cx="117.872" cy="199.369" r="5.424"/><text xml:space="preserve" style="font-style:normal;font-weight:400;font-size:10.58333302px;line-height:1.25;font-family:sans-serif;letter-spacing:0;word-spacing:0;fill:#000;fill-opacity:1;stroke:none;stroke-width:.26458332" x="113.242" y="201.75"><tspan x="113.242" y="201.75" style="stroke-width:.26458332"><tspan style="font-size:7.05555534px">24</tspan> </tspan></text></g></svg> | 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/xrhand/index.md | ---
title: XRHand
slug: Web/API/XRHand
page-type: web-api-interface
browser-compat: api.XRHand
---
{{APIRef("WebXR Device API")}}
The **`XRHand`** interface is pair iterator (an ordered map) with the key being the hand joints and the value being an {{domxref("XRJointSpace")}}.
`XRHand` is returned by {{domxref("XRInputSource.hand")}}.
## Instance properties
- `size` {{ReadOnlyInline}} {{Experimental_Inline}}
- : Returns `25`, the size of the pair iterator.
## Instance methods
The `XRhand` object is a pair iterator. It can directly be used in a {{jsxref("Statements/for...of", "for...of")}} structure. `for (const joint of myHand)` is equivalent to `for (const joint of myHand.entries())`.
However, it's not a map-like object, so you don't have the `clear()`, `delete()`, `has()`, and `set()` methods.
- `entries()` {{Experimental_Inline}}
- : Returns an iterator with the hand joints/{{domxref("XRJointSpace")}} pairs for each element.
See {{jsxref("Map.prototype.entries()")}} for more details.
- `forEach()` {{Experimental_Inline}}
- : Runs a provided function once per each hand joint/{{domxref("XRJointSpace")}} pair.
See {{jsxref("Map.prototype.forEach()")}} for more details.
- `get()` {{Experimental_Inline}}
- : Returns a {{domxref("XRJointSpace")}} for a given hand joint or {{jsxref("undefined")}} if no such hand joint key is in the map.
See {{jsxref("Map.prototype.get()")}} for more details.
- `keys()` {{Experimental_Inline}}
- : Returns an iterator with all the hand joint keys.
See {{jsxref("Map.prototype.keys()")}} for more details.
- `values()` {{Experimental_Inline}}
- : Returns an iterator with all the {{domxref("XRJointSpace")}} values.
See {{jsxref("Map.prototype.values()")}} for more details.
## Hand joints
The `XRHand` object contains the following hand joints:

| Hand joint | Index |
| ---------------------------------- | ----- |
| wrist | 0 |
| thumb-metacarpal | 1 |
| thumb-phalanx-proximal | 2 |
| thumb-phalanx-distal | 3 |
| thumb-tip | 4 |
| index-finger-metacarpal | 5 |
| index-finger-phalanx-proximal | 6 |
| index-finger-phalanx-intermediate | 7 |
| index-finger-phalanx-distal | 8 |
| index-finger-tip | 9 |
| middle-finger-metacarpal | 10 |
| middle-finger-phalanx-proximal | 11 |
| middle-finger-phalanx-intermediate | 12 |
| middle-finger-phalanx-distal | 13 |
| middle-finger-tip | 14 |
| ring-finger-metacarpal | 15 |
| ring-finger-phalanx-proximal | 16 |
| ring-finger-phalanx-intermediate | 17 |
| ring-finger-phalanx-distal | 18 |
| ring-finger-tip | 19 |
| pinky-finger-metacarpal | 20 |
| pinky-finger-phalanx-proximal | 21 |
| pinky-finger-phalanx-intermediate | 22 |
| pinky-finger-phalanx-distal | 23 |
| pinky-finger-tip | 24 |
## Examples
### Using `XRHand` objects
```js
const wristJoint = inputSource.hand.get("wrist");
const indexFingerTipJoint = inputSource.hand.get("index-finger-tip");
for (const [joint, jointSpace] of inputSource.hand) {
console.log(joint);
console.log(jointSpace);
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("XRInputSource.hand")}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/cssvariablereferencevalue/index.md | ---
title: CSSVariableReferenceValue
slug: Web/API/CSSVariableReferenceValue
page-type: web-api-interface
browser-compat: api.CSSVariableReferenceValue
---
{{APIRef("CSSOM")}}
The **`CSSVariableReferenceValue`** interface of the {{domxref('CSS_Object_Model#css_typed_object_model','','',' ')}} allows you to create a custom name for a built-in CSS value. This object functionality is sometimes called a "CSS variable" and serves the same purpose as the {{cssxref("var", "var()")}} function. The custom name must begin with two dashes.
## Constructor
- {{domxref("CSSVariableReferenceValue.CSSVariableReferenceValue", "CSSVariableReferenceValue()")}}
- : Creates a new `CSSVariableReferenceValue` object.
## Instance properties
- {{domxref('CSSVariableReferenceValue.variable')}}
- : Returns the custom name passed to the constructor.
- {{domxref('CSSVariableReferenceValue.fallback')}} {{ReadOnlyInline}}
- : Returns the built-in CSS value for the custom name.
## Instance methods
None.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/cssvariablereferencevalue | data/mdn-content/files/en-us/web/api/cssvariablereferencevalue/variable/index.md | ---
title: "CSSVariableReferenceValue: variable property"
short-title: variable
slug: Web/API/CSSVariableReferenceValue/variable
page-type: web-api-instance-property
browser-compat: api.CSSVariableReferenceValue.variable
---
{{APIRef("CSSOM")}}
The **`variable`** property of the
{{domxref("CSSVariableReferenceValue")}} interface returns the [custom property name](/en-US/docs/Web/CSS/--*) of the
{{domxref("CSSVariableReferenceValue")}}.
## Value
A string beginning with `--` (that is, a [custom property name](/en-US/docs/Web/CSS/--*)).
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/cssvariablereferencevalue | data/mdn-content/files/en-us/web/api/cssvariablereferencevalue/cssvariablereferencevalue/index.md | ---
title: "CSSVariableReferenceValue: CSSVariableReferenceValue() constructor"
short-title: CSSVariableReferenceValue()
slug: Web/API/CSSVariableReferenceValue/CSSVariableReferenceValue
page-type: web-api-constructor
browser-compat: api.CSSVariableReferenceValue.CSSVariableReferenceValue
---
{{APIRef("CSSOM")}}
Creates a new {{domxref('CSSVariableReferenceValue')}}.
## Syntax
```js-nolint
new CSSVariableReferenceValue(variable)
new CSSVariableReferenceValue(variable, fallback)
```
### Parameters
- `variable`
- : A [custom property name](/en-US/docs/Web/CSS/--*).
- `fallback` {{optional_inline}}
- : A [custom property fallback value](/en-US/docs/Web/CSS/Using_CSS_custom_properties#custom_property_fallback_values).
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/cssvariablereferencevalue | data/mdn-content/files/en-us/web/api/cssvariablereferencevalue/fallback/index.md | ---
title: "CSSVariableReferenceValue: fallback property"
short-title: fallback
slug: Web/API/CSSVariableReferenceValue/fallback
page-type: web-api-instance-property
browser-compat: api.CSSVariableReferenceValue.fallback
---
{{APIRef("CSSOM")}}
The **`fallback`** read-only property of the
{{domxref("CSSVariableReferenceValue")}} interface returns the [custom property fallback value](/en-US/docs/Web/CSS/Using_CSS_custom_properties#custom_property_fallback_values) of the {{domxref("CSSVariableReferenceValue")}}.
## Value
A {{domxref('CSSUnparsedValue')}}.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/audioworkletnode/index.md | ---
title: AudioWorkletNode
slug: Web/API/AudioWorkletNode
page-type: web-api-interface
browser-compat: api.AudioWorkletNode
---
{{APIRef("Web Audio API")}}{{SecureContext_Header}}
> **Note:** Although the interface is available outside [secure contexts](/en-US/docs/Web/Security/Secure_Contexts), the {{domxref("BaseAudioContext.audioWorklet")}} property is not, thus custom {{domxref("AudioWorkletProcessor")}}s cannot be defined outside them.
The **`AudioWorkletNode`** interface of the [Web Audio API](/en-US/docs/Web/API/Web_Audio_API) represents a base class for a user-defined {{domxref("AudioNode")}}, which can be connected to an audio routing graph along with other nodes. It has an associated {{domxref("AudioWorkletProcessor")}}, which does the actual audio processing in a Web Audio rendering thread.
{{InheritanceDiagram}}
## Constructor
- {{domxref("AudioWorkletNode.AudioWorkletNode", "AudioWorkletNode()")}}
- : Creates a new instance of an `AudioWorkletNode` object.
## Instance properties
_Also Inherits properties from its parent, {{domxref("AudioNode")}}_.
- {{domxref("AudioWorkletNode.port")}} {{ReadOnlyInline}}
- : Returns a {{domxref("MessagePort")}} used for bidirectional communication between the node and its associated {{domxref("AudioWorkletProcessor")}}. The other end is available under the {{domxref("AudioWorkletProcessor.port", "port")}} property of the processor.
- {{domxref("AudioWorkletNode.parameters")}} {{ReadOnlyInline}}
- : Returns an {{domxref("AudioParamMap")}} — a collection of {{domxref("AudioParam")}} objects. They are instantiated during the creation of the underlying `AudioWorkletProcessor`. If the `AudioWorkletProcessor` has a static {{domxref("AudioWorkletProcessor.parameterDescriptors", "parameterDescriptors")}} getter, the {{domxref("AudioParamDescriptor")}} array returned from it is used to create `AudioParam` objects on the `AudioWorkletNode`. With this mechanism it is possible to make your own `AudioParam` objects accessible from your `AudioWorkletNode`. You can then use their values in the associated `AudioWorkletProcessor`.
### Events
- {{domxref("AudioWorkletNode.processorerror_event", "processorerror")}}
- : Fired when an error is thrown in associated {{domxref("AudioWorkletProcessor")}}. Once fired, the processor and consequently the node will output silence throughout its lifetime.
## Instance methods
_Also inherits methods from its parent, {{domxref("AudioNode")}}_.
_The `AudioWorkletNode` interface does not define any methods of its own._
## Examples
In this example we create a custom `AudioWorkletNode` that outputs random noise.
First, we need to define a custom {{domxref("AudioWorkletProcessor")}}, which will output random noise, and register it. Note that this should be done in a separate file.
```js
// random-noise-processor.js
class RandomNoiseProcessor extends AudioWorkletProcessor {
process(inputs, outputs, parameters) {
const output = outputs[0];
output.forEach((channel) => {
for (let i = 0; i < channel.length; i++) {
channel[i] = Math.random() * 2 - 1;
}
});
return true;
}
}
registerProcessor("random-noise-processor", RandomNoiseProcessor);
```
Next, in our main script file we'll load the processor, create an instance of `AudioWorkletNode` passing it the name of the processor, and connect the node to an audio graph.
```js
const audioContext = new AudioContext();
await audioContext.audioWorklet.addModule("random-noise-processor.js");
const randomNoiseNode = new AudioWorkletNode(
audioContext,
"random-noise-processor",
);
randomNoiseNode.connect(audioContext.destination);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Web Audio API](/en-US/docs/Web/API/Web_Audio_API)
- [Using the Web Audio API](/en-US/docs/Web/API/Web_Audio_API/Using_Web_Audio_API)
- [Using AudioWorklet](/en-US/docs/Web/API/Web_Audio_API/Using_AudioWorklet)
| 0 |
data/mdn-content/files/en-us/web/api/audioworkletnode | data/mdn-content/files/en-us/web/api/audioworkletnode/port/index.md | ---
title: "AudioWorkletNode: port property"
short-title: port
slug: Web/API/AudioWorkletNode/port
page-type: web-api-instance-property
browser-compat: api.AudioWorkletNode.port
---
{{APIRef("Web Audio API")}}{{SecureContext_Header}}
The read-only **`port`** property of the
{{domxref("AudioWorkletNode")}} interface returns the associated
{{domxref("MessagePort")}}. It can be used to communicate between the node and its
associated {{domxref("AudioWorkletProcessor")}}.
> **Note:** The port at the other end of the channel is
> available under the {{domxref("AudioWorkletProcessor.port", "port")}} property of the
> processor.
## Value
The {{domxref("MessagePort")}} object that is connecting the
`AudioWorkletNode` and its associated `AudioWorkletProcessor`.
## Examples
To demonstrate bidirectional communication capabilities, we'll create an
`AudioWorkletProcessor`, which will output silence and respond to ping
requests from its `AudioWorkletNode`.
First, we need to define a custom `AudioWorkletProcessor`, and register it.
Note that this should be done in a separate file.
```js
// ping-pong-processor.js
class PingPongProcessor extends AudioWorkletProcessor {
constructor(...args) {
super(...args);
this.port.onmessage = (e) => {
console.log(e.data);
this.port.postMessage("pong");
};
}
process(inputs, outputs, parameters) {
return true;
}
}
registerProcessor("ping-pong-processor", PingPongProcessor);
```
Now in our main scripts file we'll load the processor, create an instance of
`AudioWorkletNode` passing the name of the processor, and connect the node to
an audio graph.
```js
const audioContext = new AudioContext();
await audioContext.audioWorklet.addModule("ping-pong-processor.js");
const pingPongNode = new AudioWorkletNode(audioContext, "ping-pong-processor");
// send the message containing 'ping' string
// to the AudioWorkletProcessor from the AudioWorkletNode every second
setInterval(() => pingPongNode.port.postMessage("ping"), 1000);
pingPongNode.port.onmessage = (e) => console.log(e.data);
pingPongNode.connect(audioContext.destination);
```
This will output `"ping"` and `"pong"` strings to the console
every second.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Web Audio API](/en-US/docs/Web/API/Web_Audio_API)
- [Using the Web Audio API](/en-US/docs/Web/API/Web_Audio_API/Using_Web_Audio_API)
| 0 |
data/mdn-content/files/en-us/web/api/audioworkletnode | data/mdn-content/files/en-us/web/api/audioworkletnode/parameters/index.md | ---
title: "AudioWorkletNode: parameters property"
short-title: parameters
slug: Web/API/AudioWorkletNode/parameters
page-type: web-api-instance-property
browser-compat: api.AudioWorkletNode.parameters
---
{{APIRef("Web Audio API")}}{{SecureContext_Header}}
The read-only **`parameters`** property of the
{{domxref("AudioWorkletNode")}} interface returns the associated
{{domxref("AudioParamMap")}} — that is, a `Map`-like collection of
{{domxref("AudioParam")}} objects. They are instantiated during creation of the
underlying {{domxref("AudioWorkletProcessor")}} according to its
{{domxref("AudioWorkletProcessor.parameterDescriptors", "parameterDescriptors")}} static
getter.
## Value
The {{domxref("AudioParamMap")}} object containing {{domxref("AudioParam")}} instances.
They can be automated in the same way as with default `AudioNode`s, and their
calculated values can be used in the {{domxref("AudioWorkletProcessor.process",
"process")}} method of your {{domxref("AudioWorkletProcessor")}}.
## Examples
To demonstrate creation and usage of custom `AudioParam`s, we'll expand the
example from {{domxref("AudioWorkletNode")}} page. There we've created a simple node
which outputs white noise. Here, additionally, we'll create a custom gain parameter, so
we can directly change volume of the output (although you could use
{{domxref("GainNode")}} to achieve this as well).
First, we need to define a custom `AudioWorkletProcessor`, and register it.
Note that this should be done in a separate file.
We expand the processor by adding a static
{{domxref("AudioWorkletProcessor.parameterDescriptors", "parameterDescriptors")}}
getter. It will be used internally by the `AudioWorkletNode` constructor to
populate its `parameters` with instantiated `AudioParam` objects.
```js
// white-noise-processor.js
class WhiteNoiseProcessor extends AudioWorkletProcessor {
static get parameterDescriptors() {
return [
{
name: "customGain",
defaultValue: 1,
minValue: 0,
maxValue: 1,
automationRate: "a-rate",
},
];
}
process(inputs, outputs, parameters) {
const output = outputs[0];
output.forEach((channel) => {
for (let i = 0; i < channel.length; i++) {
channel[i] =
(Math.random() * 2 - 1) *
(parameters["customGain"].length > 1
? parameters["customGain"][i]
: parameters["customGain"][0]);
// note: a parameter contains an array of 128 values (one value for each of 128 samples),
// however it may contain a single value which is to be used for all 128 samples
// if no automation is scheduled for the moment.
}
});
return true;
}
}
registerProcessor("white-noise-processor", WhiteNoiseProcessor);
```
Next, in our main scripts file we'll load the processor, create an instance of
`AudioWorkletNode` passing it the name of the processor, and connect the node
to an audio graph.
```js
const audioContext = new AudioContext();
await audioContext.audioWorklet.addModule("white-noise-processor.js");
const whiteNoiseNode = new AudioWorkletNode(
audioContext,
"white-noise-processor",
);
whiteNoiseNode.connect(audioContext.destination);
```
Now we can change the gain on the node like this:
```js
const gainParam = whiteNoiseNode.parameters.get("customGain");
gainParam.setValueAtTime(0, audioContext.currentTime);
gainParam.linearRampToValueAtTime(0.5, audioContext.currentTime + 0.5);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Web Audio API](/en-US/docs/Web/API/Web_Audio_API)
- [Using the Web Audio API](/en-US/docs/Web/API/Web_Audio_API/Using_Web_Audio_API)
| 0 |
data/mdn-content/files/en-us/web/api/audioworkletnode | data/mdn-content/files/en-us/web/api/audioworkletnode/audioworkletnode/index.md | ---
title: "AudioWorkletNode: AudioWorkletNode() constructor"
short-title: AudioWorkletNode()
slug: Web/API/AudioWorkletNode/AudioWorkletNode
page-type: web-api-constructor
browser-compat: api.AudioWorkletNode.AudioWorkletNode
---
{{APIRef("Web Audio API")}}{{SecureContext_Header}}
The **`AudioWorkletNode()`**
constructor creates a new {{domxref("AudioWorkletNode")}} object, which represents an
{{domxref("AudioNode")}} that uses a JavaScript function to perform custom audio
processing.
## Syntax
```js-nolint
new AudioWorkletNode(context, name)
new AudioWorkletNode(context, name, options)
```
### Parameters
- `context`
- : The {{domxref("BaseAudioContext")}} instance this node will be associated with.
- `name`
- : A string, which represents the name of the {{domxref("AudioWorkletProcessor")}} this
node will be based on. A processor with the provided name must first be registered
using the {{domxref("AudioWorkletGlobalScope.registerProcessor()")}} method.
- `options` {{optional_inline}}
- : An object containing zero or more of the following optional properties to configure the new node:
<!-- The specification refers to this object as: AudioWorkletNodeOptions -->
> **Note:** The result of [the structured clone algorithm](/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm)
> applied to the object is also internally passed into the associated {{domxref("AudioWorkletProcessor.AudioWorkletProcessor", "AudioWorkletProcessor()")}} constructor
> — this allows custom initialization of an underlying user-defined {{domxref("AudioWorkletProcessor")}}.
- `numberOfInputs` {{optional_inline}}
- : The value to initialize the {{domxref("AudioNode.numberOfInputs", "numberOfInputs")}} property to. Defaults to 1.
- `numberOfOutputs` {{optional_inline}}
- : The value to initialize the {{domxref("AudioNode.numberOfOutputs", "numberOfOutputs")}} property to. Defaults to 1.
- `outputChannelCount` {{optional_inline}}
- : An **array** defining the number of channels for each output. For example, _outputChannelCount: \[n, m]_ specifies the number of channels in the first output to be _n_ and the second output to be _m_. The array length must match `numberOfOutputs`.
- `parameterData` {{optional_inline}}
- : An object containing the initial values of custom {{domxref("AudioParam")}} objects on this node (in its {{domxref("AudioWorkletNode.parameters", "parameters")}} property), with `key` being the name of a custom parameter and `value` being its initial value.
- `processorOptions` {{optional_inline}}
- : Any additional data that can be used for custom initialization of the underlying {{domxref("AudioWorkletProcessor")}}.
### Exceptions
- `NotSupportedError` {{domxref("DOMException")}}
- : The specified `options.outputChannelCount` is `0` or larger
than the current implementation supports.
Both `options.numberOfInputs` and `options.numberOfOutputs` are 0.
- `IndexSizeError` {{domxref("DOMException")}}
- : The length of `options.outputChannelCount` array does not match
`options.numberOfOutputs`.
## Usage notes
Different `options` parameter values can have the following effects.
If the number of inputs and number of outputs are both set to 0, a `NotSupportedError` will be thrown and the node construction process aborted. If the length of the `outputChannelCount` array doesn't match `numberOfOutputs`, an `IndexSizeError` {{domxref("DOMException")}} will be thrown.
If `outputChannelCount` isn't specified, and `numberOfInputs` and `numberOfOutputs` are both 1, the `AudioWorkletNode`'s initial channel count is set to 1. This has the effect of changing the output channel count to dynamically change to the computed number of channels, based on the input's channel count and the current setting of the {{domxref("AudioNode")}} property {{domxref("AudioNode.channelCountMode", "channelCountMode")}}.
Otherwise, if `outputChannelCount` is provided _and_ if the values of `numberOfInputs` and `numberOfOutputs` are both 1, the audio worklet node's channel count is set to the value of `outputChannelCount`. Otherwise, the channel count of each channel in the set of output channels is set to match the corresponding value in the `outputChannelCount` array.
## Examples
_For a complete example demonstrating user-defined audio processing, see the
{{domxref("AudioWorkletNode")}} page._
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Web Audio API](/en-US/docs/Web/API/Web_Audio_API)
- [Background audio processing using AudioWorklet](/en-US/docs/Web/API/Web_Audio_API/Using_AudioWorklet)
- {{domxref("AudioWorkletNode", "AudioWorkletNode")}} interface
| 0 |
data/mdn-content/files/en-us/web/api/audioworkletnode | data/mdn-content/files/en-us/web/api/audioworkletnode/processorerror_event/index.md | ---
title: "AudioWorkletNode: processorerror event"
short-title: processorerror
slug: Web/API/AudioWorkletNode/processorerror_event
page-type: web-api-event
browser-compat: api.AudioWorkletNode.processorerror_event
---
{{ APIRef("Web Audio API") }}{{SecureContext_Header}}
The `processorerror` event fires when the underlying {{domxref("AudioWorkletProcessor")}} behind the node throws an exception in its constructor, the {{domxref("AudioWorkletProcessor.process", "process")}} method, or any user-defined class method.
Once an exception is thrown, the processor (and thus the node) will output silence throughout its lifetime.
## Syntax
Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property.
```js-nolint
addEventListener("processorerror", (event) => { })
onprocessorerror = (event) => { }
```
## Event type
A generic {{domxref("Event")}}.
## Examples
To be informed when the processor throws an exception, you can add a handler to your {{domxref("AudioWorkletNode")}} instance using {{domxref("EventTarget.addEventListener", "addEventListener()")}}, like this:
```js
whiteNoiseNode.addEventListener("processorerror", (event) => {
console.error("There was an error!");
});
```
Alternatively, you can use the `onprocessorerror` event handler property to establish a handler for the `processorerror` event:
```js
whiteNoiseNode.onprocessorerror = (event) => {
console.error("There was an error!");
};
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using the Web Audio API](/en-US/docs/Web/API/Web_Audio_API/Using_Web_Audio_API)
| 0 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.