recursal/MDN huggingface dataset:
HTMLMediaElement: setSinkId() method
====================================

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

The **`HTMLMediaElement.setSinkId()`** method of the Audio Output Devices API sets the ID of the audio device to use for output and returns a `Promise`.

 This only works when the application is permitted to use the specified device.
 For more information see the security requirements below.

Syntax
------


```js
setSinkId(sinkId)
```

### Parameters

`sinkId`

The `MediaDeviceInfo.deviceId` of the audio output device.

### Return value

A `Promise` that resolves to `undefined`.

### Exceptions

`NotAllowedError` `DOMException`

Returned if a `speaker-selection` Permissions Policy is used to block use of audio outputs.

`NotFoundError` `DOMException`

Returned if the `deviceId` does not match any audio output device.

`AbortError` `DOMException`

Returned if switching the audio output device to the new audio device failed.

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

Access to the API is subject to the following constraints:

* The method must be called in a secure context.
* Access may be gated by the `speaker-selection` HTTP Permission Policy.
* User permission is required to access a non-default device.
 The user grants permission by selecting the device associated with the ID in the prompt displayed by `MediaDevices.selectAudioOutput()`.
Examples
--------

 This example shows how to select an audio output device from the array returned by `MediaDevices.enumerateDevices()`, and set it as the sink for audio.
 Note that the result of `enumerateDevices()` only includes devices for which user permission is not required or has already been granted.


```js
const devices = await navigator.mediaDevices.enumerateDevices();
const audioDevice = devices.find((device) => device.kind === "audiooutput");
const audio = document.createElement("audio");
await audio.setSinkId(audioDevice.deviceId);
console.log(`Audio is being output on ${audio.sinkId}`);
```

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

| Specification |
| --- |
| Audio Output Devices API # dom-htmlmediaelement-setsinkid |

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

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

See also
--------

* `MediaDevices.selectAudioOutput()`
* `HTMLMediaElement.sinkId`
HTMLMediaElement: muted property
================================

 The **`HTMLMediaElement.muted`** property indicates whether the media
 element is muted.

Value
-----

 A boolean value. `true` means muted and `false` means
 not muted.

Examples
--------


```js
const obj = document.createElement("video");
console.log(obj.muted); // false
```

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

| Specification |
| --- |
| HTML Standard # dom-media-muted-dev |

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

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

See also
--------

* `HTMLMediaElement`: Interface used to define the `HTMLMediaElement.muted` property
* `HTMLMediaElement.defaultMuted`
* `HTMLMediaElement.volume`
MIDIOutput: clear() method
==========================

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

The **`clear()`** method of the `MIDIOutput` interface clears the queue of messages being sent to the output device.

Syntax
------


```js
clear()
```

### Parameters

None.

### Return value

None (`undefined`).

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

| Specification |
| --- |
| Web MIDI API # dom-midioutput-clear |

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

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
MIDIOutput: send() method
=========================

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

The **`send()`** method of the `MIDIOutput` interface queues messages for the corresponding MIDI port. The message can be sent immediately, or with an optional timestamp to delay sending.

Syntax
------


```js
send(data)
send(data, timestamp)
```

### Parameters

`data`

A sequence of one or more valid MIDI messages. Each entry represents a single byte of data.

`timestamp` Optional

A `DOMHighResTimestamp` with the time in milliseconds when the message should be sent (relative to `Performance.timeOrigin`).

### Return value

None (`undefined`).

### Exceptions

`TypeError`

Thrown if `data` is not a valid sequence, or does not contain a valid MIDI message.

`InvalidAccessError` `DOMException`

Thrown if `data` is a system exclusive message, and the `MIDIAccess` did not enable exclusive access.

`InvalidStateError` `DOMException`

Thrown if the port is disconnected.

Examples
--------

In the following example a middle C note is sent immediately, followed by a note off message one second later.


```js
function sendMiddleC(midiAccess, portID) {
  const noteOnMessage = [0x90, 60, 0x7f]; // note on middle C, full velocity
  const output = midiAccess.outputs.get(portID);
  output.send(noteOnMessage); //omitting the timestamp means send immediately.
  output.send([0x80, 60, 0x40], window.performance.now() + 1000.0); // timestamp = now + 1000ms.
}
```

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

| Specification |
| --- |
| Web MIDI API # dom-midioutput-send |

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

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
NotificationEvent: notification property
========================================

The **`notification`** read-only property of the `NotificationEvent` interface returns the instance of the `Notification` that was clicked to fire the event. The `Notification` provides read-only access to many properties that were set at the instantiation time of the Notification such as `tag` and `data` attributes that allow you to store information for deferred use in the `notificationclick` event.

Value
-----

A `Notification` object.

Examples
--------


```js
self.addEventListener("notificationclick", (event) => {
  console.log("On notification click");

  // Data can be attached to the notification so that you
  // can process it in the notificationclick handler.
  console.log(`Notification Tag: ${event.notification.tag}`);
  console.log(`Notification Data: ${event.notification.data}`);
  event.notification.close();

  // This looks to see if the current is already open and
  // focuses if it is
  event.waitUntil(
    clients
      .matchAll({
        type: "window",
      })
      .then((clientList) => {
        for (const client of clientList) {
          if (client.url === "/" && "focus" in client) return client.focus();
        }
        if (clients.openWindow) return clients.openWindow("/");
      }),
  );
});
```

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

| Specification |
| --- |
| Notifications API Standard # ref-for-dom-notificationevent-notification |

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

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
NotificationEvent: NotificationEvent() constructor
==================================================

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

Syntax
------


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

### Parameters

`type`

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


`options`

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

`notification`

A `Notification` object to be used as the notification the event is dispatched on.

`action` Optional

An action associated with the notification. It defaults to `""`.


### Return value

A new `NotificationEvent()` object.

Examples
--------


```js
const n = new Notification("Hello");
const myNotificationEvent = new NotificationEvent(type, { notification: n });
```

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

| Specification |
| --- |
| Notifications API Standard # dom-notificationevent-notificationevent |

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

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
NotificationEvent: action property
==================================

The **`action`** read-only property of the `NotificationEvent` interface returns the string ID of the notification button the user clicked. This value returns an empty string if the user clicked the notification somewhere other than an action button, or the notification does not have a button. The notification id is set during the creation of the Notification via the actions array attribute and can't be modified unless the notification is replaced.

Value
-----

A string.

Examples
--------


```js
self.registration.showNotification("New articles available", {
  actions: [{ action: "get", title: "Get now." }],
});

self.addEventListener(
  "notificationclick",
  (event) => {
    event.notification.close();
    if (event.action === "get") {
      synchronizeReader();
    } else {
      clients.openWindow("/reader");
    }
  },
  false,
);
```

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

| Specification |
| --- |
| Notifications API Standard # dom-notification-actions |

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

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
LayoutShift: hadRecentInput property
====================================

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

The **`hadRecentInput`** read-only property of the `LayoutShift` interface returns `true` if `lastInputTime` is less than 500 milliseconds in the past.

Layout shifts are only a problem if the user is not expecting them, so layout shifts that are the result of user interactions (such as a user expanding a UI element) are often not considered in layout shift metrics. The `hadRecentInput` property allows you to exclude these shifts.

Value
-----

A boolean returning `true` if `lastInputTime` is less than 500 milliseconds in the past; `false` otherwise.

Examples
--------

### Ignoring recent user input for layout shift scores

The following example shows how the `hadRecentInput` property is used to only count layout shifts without recent user input.


```js
const observer = new PerformanceObserver((list) => {
  for (const entry of list.getEntries()) {
    // Count layout shifts without recent user input only
    if (!entry.hadRecentInput) {
      console.log("LayoutShift value:", entry.value);
      if (entry.sources) {
        for (const { node, currentRect, previousRect } of entry.sources)
          console.log("LayoutShift source:", node, {
            currentRect,
            previousRect,
          });
      }
    }
  }
});

observer.observe({ type: "layout-shift", buffered: true });
```

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

| Specification |
| --- |
| Layout Instability # dom-layoutshift-hadrecentinput |

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

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

See also
--------

* `LayoutShift.lastInputTime`
LayoutShift: sources property
=============================

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

The **`sources`** read-only property of the `LayoutShift` interface returns an array of `LayoutShiftAttribution` objects that indicate the DOM elements that moved during the layout shift.

Value
-----

An `Array` of `LayoutShiftAttribution` objects. This array will not contain more than five sources. If there are more than five elements impacted by the layout shift, the five most impactful elements are reported.

Examples
--------

### Logging layout shift sources


```js
const observer = new PerformanceObserver((list) => {
  list.getEntries().forEach((entry) => {
    entry.sources.forEach((source) => {
      console.log(source);
    });
  });
});

observer.observe({ type: "layout-shift", buffered: true });
```

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

| Specification |
| --- |
| Layout Instability # dom-layoutshift-sources |

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

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

See also
--------

* `LayoutShiftAttribution`
LayoutShift: toJSON() method
============================

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

The **`toJSON()`** method of the `LayoutShift` interface is a serializer; it returns a JSON representation of the `LayoutShift` object.

Syntax
------


```js
toJSON()
```

### Parameters

None.

### Return value

A `JSON` object that is the serialization of the `LayoutShift` object.

Examples
--------

### Using the toJSON method

In this example, calling `entry.toJSON()` returns a JSON representation of the `LayoutShift` object.


```js
const observer = new PerformanceObserver((list) => {
  list.getEntries().forEach((entry) => {
    console.log(entry.toJSON());
  });
});

observer.observe({ type: "layout-shift", buffered: true });
```


This would log a JSON object like so:


```json
{
  "name": "",
  "entryType": "layout-shift",
  "startTime": 246.39999999850988,
  "duration": 0,
  "value": 0.0071167845054842215,
  "hadRecentInput": false,
  "lastInputTime": 0,
  "sources": [
    {
      "previousRect": {
        "x": 917,
        "y": 708,
        "width": 706,
        "height": 248,
        "top": 708,
        "right": 1623,
        "bottom": 956,
        "left": 917
      },
      "currentRect": {
        "x": 693,
        "y": 708,
        "width": 1154,
        "height": 472,
        "top": 708,
        "right": 1847,
        "bottom": 1180,
        "left": 693
      }
    }
  ]
}
```


To get a JSON string, you can use `JSON.stringify(entry)` directly; it will call `toJSON()` automatically.

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

| Specification |
| --- |
| Layout Instability # dom-layoutshift-tojson |

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

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

See also
--------

* `JSON`
LayoutShift: lastInputTime property
===================================

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

The **`lastInputTime`** read-only property of the `LayoutShift` interface returns the time of the most recent excluding input or `0` if no excluding input has occurred.

Layout shifts are only bad if the user wasn't expecting them. Many layout shift metrics (like Cumulative Layout Shift (CLS)) exclude shifts that occurred soon after certain user interactions. These interactions are called *excluding inputs*. Excluding inputs are:

* Any events which signal a user's active interaction with the document: (`mousedown`, `keydown`, and `pointerdown`)
* Any events which directly changes the size of the viewport.
* `change` events.

The `mousemove` and `pointermove` events are **not** excluding inputs.

Value
-----

A `DOMHighResTimeStamp` indicating the most recent excluding input time or `0` if no excluding input has occurred.

Examples
--------

### Logging last input times

Log excluding input times if excluding input has occurred.


```js
const observer = new PerformanceObserver((list) => {
  list.getEntries().forEach((entry) => {
    if (entry.lastInputTime) {
      console.log(entry.lastInputTime);
    }
  });
});

observer.observe({ type: "layout-shift", buffered: true });
```

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

| Specification |
| --- |
| Layout Instability # dom-layoutshift-lastinputtime |

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

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

See also
--------

* `LayoutShift.hadRecentInput`
LayoutShift: value property
===========================

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

The **`value`** read-only property of the `LayoutShift` interface returns the layout shift score calculated as the impact fraction (fraction of the viewport that was shifted) multiplied by the distance fraction (distance moved as a fraction of viewport).

Value
-----

A number between `0.0` and `1.0` indicating the layout shift score.

It is calculated as the impact fraction (fraction of the viewport that was shifted) multiplied by the distance fraction (distance moved as a fraction of viewport).
```

layout shift score = impact fraction * distance fraction
```


For more details, see Layout shift score on web.dev.

Examples
--------

### Logging the entry's layout shift score

The following example shows how use the `value` property to log the layout shift score.


```js
const observer = new PerformanceObserver((list) => {
  for (const entry of list.getEntries()) {
    // Count layout shifts without recent user input only
    if (!entry.hadRecentInput) {
      console.log("Entry's layout shift score:", entry.value);
    }
  }
});

observer.observe({ type: "layout-shift", buffered: true });
```

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

| Specification |
| --- |
| Layout Instability # dom-layoutshift-value |

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

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
SensorErrorEvent: SensorErrorEvent() constructor
================================================

 The **`SensorErrorEvent`** constructor
 creates a new `SensorErrorEvent` object which provides information about
 errors thrown by any of the interfaces based on `Sensor`.

Syntax
------


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

### Parameters

`type`

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


`options`

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

`error`

A `DOMException` object describing the error.


### Return value

A new `SensorErrorEvent` object.

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

| Specification |
| --- |
| Generic Sensor API # dom-sensorerrorevent-sensorerrorevent |

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

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
SensorErrorEvent: error property
================================

 The **`error`** read-only property of
 the `SensorErrorEvent` interface returns the `DOMException`
 object passed in the event's constructor.

Value
-----

A `DOMException`.

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

| Specification |
| --- |
| Generic Sensor API # dom-sensorerrorevent-error |

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

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

This tutorial describes how to use the `<canvas>` element to draw WebGL graphics, starting with the basics. The examples provided should give you some clear ideas of what you can do with WebGL and will provide code snippets that may get you started in building your own content.

WebGL enables web content to use an API based on OpenGL ES 2.0 to perform 3D rendering in an HTML `<canvas>` in browsers that support it without the use of plug-ins. WebGL programs consist of control code written in JavaScript and special effects code (shader code) that is executed on a computer's Graphics Processing Unit (GPU). WebGL elements can be mixed with other HTML elements and composited with other parts of the page or page background.

Before you start
----------------

Using the `<canvas>` element is not very difficult, but you do need a basic understanding of HTML and JavaScript. The `<canvas>` element and WebGL are not supported in some older browsers, but are supported in recent versions of all major browsers. In order to draw graphics on the canvas we use a JavaScript context object, which creates graphics on the fly.

In this tutorial
----------------

Getting started with WebGL

How to set up a WebGL context.

Adding 2D content to a WebGL context

How to render simple flat shapes using WebGL.

Using shaders to apply color in WebGL

Demonstrates how to add color to shapes using shaders.

Animating objects with WebGL

Shows how to rotate and translate objects to create simple animations.

Creating 3D objects using WebGL

Shows how to create and animate a 3D object (in this case, a cube).

Using textures in WebGL

Demonstrates how to map textures onto the faces of an object.

Lighting in WebGL

How to simulate lighting effects in your WebGL context.

Animating textures in WebGL

Shows how to animate textures; in this case, by mapping an Ogg video onto the faces of a rotating cube.
Data in WebGL
=============

Shader programs have access to three kinds of data storage, each of which has a specific use case. Each kind of variable is accessible by one or both types of shader program (depending on the data store type) and possibly by the site's JavaScript code, depending on the specific type of variable.

GLSL data types
---------------

See Data Types in the GLSL documentation.

GLSL variables
--------------

There are three kinds of "variable" or data storage available in GLSL, each of which with its own purpose and use cases: **attributes**, **varyings**, and **uniforms**.

### Attributes

**Attributes** are GLSL variables which are only available to the vertex shader (as variables) and the JavaScript code. Attributes are typically used to store color information, texture coordinates, and any other data calculated or retrieved that needs to be shared between the JavaScript code and the vertex shader.


```js
// init colors
const vertexColors = [
  vec4(0.0, 0.0, 0.0, 1.0), // black
  vec4(1.0, 0.0, 0.0, 1.0), // red
  vec4(1.0, 1.0, 0.0, 1.0), // yellow
  vec4(0.0, 1.0, 0.0, 1.0), // green
  vec4(0.0, 0.0, 0.0, 1.0), // black
  vec4(1.0, 0.0, 0.0, 1.0), // red
  vec4(1.0, 1.0, 0.0, 1.0), // yellow
  vec4(0.0, 1.0, 0.0, 1.0), // green
];
const cBuffer = gl.createBuffer();
```



```js
// continued
// create buffer to store colors and reference it to "vColor" which is in GLSL
gl.bindBuffer(gl.ARRAY\_BUFFER, cBuffer);
gl.bufferData(gl.ARRAY\_BUFFER, flatten(vertexColors), gl.STATIC\_DRAW);

const vColor = gl.getAttribLocation(program, "vColor");
gl.vertexAttribPointer(vColor, 4, gl.FLOAT, false, 0, 0);
gl.enableVertexAttribArray(vColor);
```



```cpp
//glsl
attribute  vec4 vColor;

void main()
{
  fColor = vColor;
}
```

### Varyings

**Varyings** are variables that are declared by the vertex shader and used to pass data from the vertex shader to the fragment shader. This is commonly used to share a vertex's normal vector after it has been computed by the vertex shader.

<<how to use>>

### Uniforms

**Uniforms** are set by the JavaScript code and are available to both the vertex and fragment shaders. They're used to provide values that will be the same for everything drawn in the frame, such as lighting positions and magnitudes, global transformation and perspective details, and so forth.

<<add details>>

Buffers
-------

<<add information>>

Textures
--------

<<add information>>