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/web_audio_api
data/mdn-content/files/en-us/web/api/web_audio_api/basic_concepts_behind_web_audio_api/pannernode_en.svg
<svg xmlns="http://www.w3.org/2000/svg" width="798.989" height="339.657"><linearGradient id="a" gradientUnits="userSpaceOnUse" x1="350.572" y1="166.922" x2="364.528" y2="101.264"><stop offset="0"/><stop offset=".047" stop-color="#4c4c4e" stop-opacity=".968"/><stop offset=".119" stop-color="#76777a" stop-opacity=".917"/><stop offset=".195" stop-color="#97999c" stop-opacity=".865"/><stop offset=".272" stop-color="#b5b7b9" stop-opacity=".811"/><stop offset=".353" stop-color="#cfd0d2" stop-opacity=".755"/><stop offset=".436" stop-color="#e2e3e4" stop-opacity=".697"/><stop offset=".525" stop-color="#f1f1f2" stop-opacity=".636"/><stop offset=".622" stop-color="#fafafa" stop-opacity=".568"/><stop offset=".742" stop-color="#fff" stop-opacity=".485"/><stop offset="1" stop-color="#828486" stop-opacity="0"/></linearGradient><path fill="url(#a)" stroke="#000" stroke-miterlimit="10" d="M191.465 132h317.667s18.667 4 9 26.333c0 0-15 28-42.667 34 0 0-8-.333-24-4 0 0-249.667-53.666-260-56.333z"/><path fill="none" stroke="#000" stroke-miterlimit="10" d="M191.465 132l363.333 37.828M32.131 206l144.667-66.333M131.131 231l60.334-97.667"/><circle fill="#010101" stroke="#719FD0" cx="192.465" cy="132" r="4.667"/><path fill="none" stroke="#797A7D" stroke-miterlimit="10" d="M31.84 178.292v28m-.542 0h32.666m-32.124 0l19.666-19.959"/><path fill="#010101" d="M136.265 233.093l-13.96 11.078 4.397-17.16zm32.069-96.371l17.678-2.262-12.638 12.414z"/><path fill="#797A7D" d="M28.536 178.292l3.363-9.833 3.246 9.807zm34.916 24.696l9.833 3.364-9.807 3.245zm-14.807-18.467l9.065-5.081-4.126 9.472z"/><path fill="#010101" d="M556.342 163.985l16.157 7.522-17.312 3.753z"/><text transform="translate(25.798 219.5)" fill="#797A7D" font-family="'ArialMT'" font-size="12">0</text><path fill="none" stroke="#719FD0" d="M97.798 88.5l18.5 71.5m365-101l-32.906 82.5m-280.469 42.25L211.298 271m319.183-96.246l14.611 56.468"/><g font-family="'ArialMT'" font-size="12"><text transform="translate(161.298 288.25)">Velocity vector indicating how the source is moving</text><text transform="translate(387.894 50.25)">Cone in which the sound can be listened to</text><text transform="translate(390.894 250.75)">Direction vector indicating where the PannerNode is pointing to</text><text transform="translate(20.145 77)">Positioning vector placing the source in the space</text></g></svg>
0
data/mdn-content/files/en-us/web/api/web_audio_api
data/mdn-content/files/en-us/web/api/web_audio_api/basic_concepts_behind_web_audio_api/fttaudiodata_en.svg
<svg xmlns="http://www.w3.org/2000/svg" width="692.929" height="206.323"><path fill="none" stroke="#010101" d="M25.556 31.667v59.458"/><path fill="#010101" d="M19.722 32.667l5.834-16.839 5.5 16.839zm210.915 51.914l16.839 5.834-16.839 5.5z"/><path fill="none" stroke="#010101" stroke-miterlimit="10" d="M25.722 53.167h36.667s4.167-14.333 9-11c0 0 2.333.417 7.333 14 0 0 2.917 10.583 8 8.167 0 0 3.333-.417 6.667-14.167 0 0 3.333-11.917 8.5-7.333 0 0 2.667 1.833 6.5 13.333 0 0 4 12 8.5 7.5 0 0 3.333-2.666 6.167-13.5 0 0 3.167-12.667 9-7.667 0 0 2.292.562 5.667 13.5 0 0 4.167 13.083 9.5 7.667 0 0 2.188-1.729 5-13.5 0 0 3.25-12.667 8.5-7.667 0 0 2.938 3.25 6.667 13.667 0 0 5.021 12.333 8.833 7.667 0 0 3.812-4.646 4.667-10.561h30"/><text transform="translate(252.055 94.834)" font-family="'ArialMT'" font-size="14">t</text><text transform="translate(23.222 106.333)"><tspan x="0" y="0" font-family="'ArialMT'" font-size="14">0</tspan><tspan x="7.786" y="0" font-family="'ArialMT'" font-size="14" letter-spacing="24"> </tspan><tspan x="36" y="0" font-family="'ArialMT'" font-size="14">1</tspan><tspan x="43.786" y="0" font-family="'ArialMT'" font-size="14" letter-spacing="24"> </tspan><tspan x="72" y="0" font-family="'ArialMT'" font-size="14">2</tspan><tspan x="79.786" y="0" font-family="'ArialMT'" font-size="14" letter-spacing="24"> </tspan><tspan x="108" y="0" font-family="'ArialMT'" font-size="14">3</tspan><tspan x="115.787" y="0" font-family="'ArialMT'" font-size="14" letter-spacing="24"> </tspan><tspan x="144" y="0" font-family="'ArialMT'" font-size="14">4</tspan></text><path fill="none" stroke="#010101" stroke-miterlimit="10" d="M25.556 90.667h205.081"/><path fill="none" stroke="#010101" d="M431.556 31.667v59.458"/><path fill="#010101" d="M425.722 32.667l5.834-16.839 5.5 16.839zm210.914 51.914l16.84 5.834-16.84 5.5z"/><path fill="none" stroke="#010101" stroke-miterlimit="10" d="M431.722 53.167h36.666s4.167-14.333 9-11c0 0 2.334.417 7.334 14 0 0 2.916 10.583 8 8.167 0 0 3.334-.417 6.666-14.167 0 0 3.334-11.917 8.5-7.333 0 0 2.667 1.833 6.5 13.333 0 0 4 12 8.5 7.5 0 0 3.334-2.666 6.168-13.5 0 0 3.166-12.667 9-7.667 0 0 2.291.562 5.666 13.5 0 0 4.167 13.083 9.5 7.667 0 0 2.188-1.729 5-13.5 0 0 3.25-12.667 8.5-7.667 0 0 2.938 3.25 6.667 13.667 0 0 5.021 12.333 8.833 7.667 0 0 3.812-4.646 4.667-10.561h30"/><text transform="translate(658.055 94.834)" font-family="'ArialMT'" font-size="14">t</text><text transform="translate(429.222 106.333)"><tspan x="0" y="0" font-family="'ArialMT'" font-size="14">0</tspan><tspan x="7.786" y="0" font-family="'ArialMT'" font-size="14" letter-spacing="24"> </tspan><tspan x="36" y="0" font-family="'ArialMT'" font-size="14">1</tspan><tspan x="43.786" y="0" font-family="'ArialMT'" font-size="14" letter-spacing="24"> </tspan><tspan x="72" y="0" font-family="'ArialMT'" font-size="14">2</tspan><tspan x="79.786" y="0" font-family="'ArialMT'" font-size="14" letter-spacing="24"> </tspan><tspan x="108" y="0" font-family="'ArialMT'" font-size="14">3</tspan><tspan x="115.787" y="0" font-family="'ArialMT'" font-size="14" letter-spacing="24"> </tspan><tspan x="144" y="0" font-family="'ArialMT'" font-size="14">4</tspan></text><path fill="none" stroke="#010101" stroke-miterlimit="10" d="M431.556 90.667h205.08"/><path fill="#010101" d="M401.636 47.489l16.84 5.834-16.84 5.5z"/><path fill="none" stroke="#010101" stroke-miterlimit="10" d="M273.555 53.576h128.081"/><path fill="#010101" d="M347.889 148.454l-5.834 16.84-5.5-16.84z"/><path fill="#719FD0" stroke="#010101" d="M299.222 35h86v96.5h-86z"/><text transform="translate(304.223 56.823)" font-family="'ArialMT'" font-size="11">AnalyserNode</text><path fill="none" stroke="#010101" stroke-miterlimit="10" d="M341.803 118v30.454"/><text transform="translate(331.889 106.333)" font-family="'Arial-BoldMT'" font-size="11">FFT</text><path fill="none" stroke="#2C2C76" stroke-miterlimit="10" d="M321.889 86.667h41l-8 29.333h-25.333z"/><g font-family="'ArialMT'" font-size="11"><text transform="translate(484.89 131.5)">unchanged output</text><text transform="translate(302.223 176.167)">frequency data</text></g></svg>
0
data/mdn-content/files/en-us/web/api/web_audio_api
data/mdn-content/files/en-us/web/api/web_audio_api/controlling_multiple_parameters_with_constantsourcenode/index.md
--- title: Controlling multiple parameters with ConstantSourceNode slug: Web/API/Web_Audio_API/Controlling_multiple_parameters_with_ConstantSourceNode page-type: guide --- {{DefaultAPISidebar("Web Audio API")}} This article demonstrates how to use a {{domxref("ConstantSourceNode")}} to link multiple parameters together so they share the same value, which can be changed by setting the value of the {{domxref("ConstantSourceNode.offset")}} parameter. You may sometimes want multiple audio parameters to be linked so they share the same value while being changed somehow. For example, perhaps you have a set of oscillators, two of which need to share the same configurable volume, or you have a filter applied to specific inputs but not all of them. You could use a loop and change the value of each affected {{domxref("AudioParam")}} one at a time. Still, there are two drawbacks to doing it that way: first, that's extra code that, as you're about to see, you don't have to write; and second, that loop uses valuable CPU time on your thread (likely the main thread), and there's a way to offload all that work to the audio rendering thread, which is optimized for this kind of work and may run at a more appropriate priority level than your code. The solution is simple, and it involves using an audio node type that, at first glance, doesn't look all that useful: {{domxref("ConstantSourceNode")}}. ## The technique Using a `ConstantSourceNode` is an effortless way to do something that sounds like it might be hard. You need to create a {{domxref("ConstantSourceNode")}} and connect it to all of the {{domxref("AudioParam")}}s whose values should be linked to always match each other. Since `ConstantSourceNode`'s {{domxref("ConstantSourceNode.offset", "offset")}} value is sent straight through to all of its outputs, it acts as a splitter for that value, sending it to each connected parameter. The diagram below shows how this works; an input value, `N`, is set as the value of the {{domxref("ConstantSourceNode.offset")}} property. The `ConstantSourceNode` can have as many outputs as necessary; in this case, we've connected it to three nodes: two {{domxref("GainNode")}}s and a {{domxref("StereoPannerNode")}}. So `N` becomes the value of the specified parameter ({{domxref("GainNode.gain", "gain")}} for the {{domxref("GainNode")}}s and pan for the {{domxref("StereoPannerNode")}}. ![Diagram in SVG showing how ConstantSourceNode can be used to split an input parameter to share it with multiple nodes.](customsourcenode-as-splitter.svg) As a result, every time you change `N` (the value of the input {{domxref("AudioParam")}}, the values of the two `GainNode.gain` properties and the value of the `StereoPannerNode` 's `pan` properties are all set to `N` as well. ## Example Let's take a look at this technique in action. In this simple example, we create three {{domxref("OscillatorNode")}} objects. Two of them have adjustable gain, controlled using a shared input control. The other oscillator has a fixed volume. ### HTML The HTML content for this example is primarily a checkbox, shaped as an actual button, to toggle the oscillator tones on and off and an {{HTMLElement("input")}} element of type `range` to control the volume of two of the three oscillators. ```html <div class="controls"> <input type="checkbox" id="playButton"> <label for="playButton">Activate: </label> <label for="volumeControl">Volume: </label> <input type="range" min="0.0" max="1.0" step="0.01" value="0.8" name="volume" id="volumeControl"> </div> </div> <p>Toggle the checkbox above to start and stop the tones, and use the volume control to change the volume of the notes E and G in the chord.</p> ``` ```css hidden .controls { width: 400px; position: relative; vertical-align: middle; height: 44px; } #playButton:checked + label::after { content: "⏸"; } #playButton:not(checked) + label::after { content: "▶️"; } #playButton + label::after { cursor: pointer; } #playButton { vertical-align: middle; display: none; } #volumeControl { vertical-align: bottom; } label { vertical-align: middle; } ``` ### JavaScript Now let's look at the JavaScript code, a piece at a time. #### Setting up Let's start by looking at the global variable initialization. ```js // Useful UI elements const playButton = document.querySelector("#playButton"); const volumeControl = document.querySelector("#volumeControl"); // The audio context and the node will be initialized after the first request let context = null; let oscNode1 = null; let oscNode2 = null; let oscNode3 = null; let constantNode = null; let gainNode1 = null; let gainNode2 = null; let gainNode3 = null; ``` These variables are: - `context` - : The {{domxref("AudioContext")}} in which all the audio nodes live; it will be initialized during after a user-action. - `playButton` and `volumeControl` - : References to the play button and volume control elements. - `oscNode1`, `oscNode2`, and `oscNode3` - : The three {{domxref("OscillatorNode")}}s used to generate the chord. - `gainNode1`, `gainNode2`, and `gainNode3` - : The three {{domxref("GainNode")}} instances which provide the volume levels for each of the three oscillators. `gainNode2` and `gainNode3` will be linked together to have the same, adjustable, value using the {{domxref("ConstantSourceNode")}}. - `constantNode` - : The {{domxref("ConstantSourceNode")}} used to control the values of `gainNode2` and `gainNode3` together. Now let's look at the `setup()` function, called when the user toggles the play button for the first time; it handles all the initialization tasks to set up the audio graph. ```js function setup() { context = new AudioContext(); gainNode1 = new GainNode(context, { gain: 0.5, }); gainNode2 = new GainNode(context, { gain: gainNode1.gain.value, }); gainNode3 = new GainNode(context, { gain: gainNode1.gain.value, }); volumeControl.value = gainNode1.gain.value; constantNode = new ConstantSourceNode(context, { offset: volumeControl.value, }); constantNode.connect(gainNode2.gain); constantNode.connect(gainNode3.gain); constantNode.start(); gainNode1.connect(context.destination); gainNode2.connect(context.destination); gainNode3.connect(context.destination); // All is set up. We can hook the volume control. volumeControl.addEventListener("input", changeVolume, false); } ``` First, we get access to the window's {{domxref("AudioContext")}}, stashing the reference in `context`. Then we get references to the control widgets, setting `playButton` to reference the play button and `volumeControl` to reference the slider control that the user will use to adjust the gain on the linked pair of oscillators. Next, the {{domxref("GainNode")}} `gainNode1` is created to handle the volume for the non-linked oscillator (`oscNode1`). We set that gain to 0.5. We also create `gainNode2` and `gainNode3`, set their values to match `gainNode1`, then set the value of the volume slider to the same value, so it stays synchronized with the gain level it controls. Once all the gain nodes are created, we create the {{domxref("ConstantSourceNode")}}, `constantNode`. We connect its output to the `gain` {{domxref("AudioParam")}} on both `gainNode2` and `gainNode3`, and we start the constant node running by calling its {{domxref("AudioScheduledSourceNode/start", "start()")}} method; now it's sending the value 0.5 to the two gain nodes' values, and any change to {{domxref("ConstantSourceNode.offset", "constantNode.offset")}} will automatically set the gain of both `gainNode2` and `gainNode3` (affecting their audio inputs as expected). Finally, we connect all the gain nodes to the {{domxref("AudioContext")}}'s {{domxref("BaseAudioContext/destination", "destination")}}, so that any sound delivered to the gain nodes will reach the output, whether that output be speakers, headphones, a recording stream, or any other destination type. Then we assign a handler for the volume slider's {{domxref("Element/input_event", "input")}} event (see [Controlling the linked oscillators](#controlling_the_linked_oscillators) to see the very short `changeVolume()` method). Right after declaring the `setup()` function, we add a handler to the play checkbox's {{domxref("HTMLElement/change_event", "change")}} event (see [Toggling the oscillators on and off](#toggling_the_oscillators_on_and_off) for more on the `togglePlay()` method), and the stage is set. Let's see how the action plays out. ```js playButton.addEventListener("change", togglePlay, false); ``` #### Toggling the oscillators on and off Because {{domxref("OscillatorNode")}} doesn't support the notion of being in a paused state, we have to simulate it by terminating the oscillators and starting them again when the user clicks on the play checkbox again to toggle them back on. Let's look at the code. ```js function togglePlay(event) { if (!playButton.checked) { stopOscillators(); } else { // If it is the first start, initialize the audio graph if (!context) { setup(); } startOscillators(); } } ``` If the `playButton` widget is checked, we're already playing the oscillators, and we call `stopOscillators()` to shut down the oscillators. See [Stopping the oscillators](#stopping_the_oscillators) below for that code. If the `playButton` widget is checked, indicating that we're currently paused, we call `startOscillators()` to start the oscillators playing their tones. Below, we describe that code under [Starting the oscillators](#starting_the_oscillators). #### Controlling the linked oscillators The `changeVolume()` function, the event handler for the slider control for the gain on the linked oscillator pair, looks like this: ```js function changeVolume(event) { constantNode.offset.value = volumeControl.value; } ``` That simple function controls the gain on both nodes. All we have to do is set the value of the {{domxref("ConstantSourceNode")}}'s {{domxref("ConstantSourceNode.offset", "offset")}} parameter. That value becomes the node's constant output value, fed to all its outputs, `gainNode2` and `gainNode3`. While this is an elementary example, imagine having a 32 oscillator synthesizer with multiple linked parameters in play across many patched nodes. Shortening the number of operations to adjust them all will prove invaluable for both code size and performance. #### Starting the oscillators When the user clicks the play/pause toggle button while the oscillators aren't playing, the `startOscillators()` function gets called. ```js function startOscillators() { oscNode1 = new OscillatorNode(context, { type: "sine", frequency: 261.625565300598634, // middle C$ }); oscNode1.connect(gainNode1); oscNode2 = new OscillatorNode(context, { type: "sine", frequency: 329.627556912869929, // E }); oscNode2.connect(gainNode2); oscNode3 = new OscillatorNode(context, { type: "sine", frequency: 391.995435981749294, // G }); oscNode3.connect(gainNode3); oscNode1.start(); oscNode2.start(); oscNode3.start(); } ``` Each of the three oscillators is set up the same way, creating the {{domxref("OscillatorNode")}} by calling the {{domxref("OscillatorNode/OscillatorNode", "OscillatorNode()")}} constructor with two options: 1. Set the oscillator's `type` to `"sine"` to use a sine wave as the audio waveform. 2. Set the oscillator's `frequency` to the desired value; in this case, `oscNode1` is set to a middle C, while `oscNode2` and `oscNode3` round out the chord by playing the E and G notes. Then, we connect the new oscillator to the corresponding gain node. Once all three oscillators have been created, they're started by calling each one's {{domxref("AudioScheduledSourceNode.start", "ConstantSourceNode.start()")}} method in turn. #### Stopping the oscillators Stopping the oscillators when the user toggles the play state to pause the tones is as simple as stopping each node. ```js function stopOscillators() { oscNode1.stop(); oscNode2.stop(); oscNode3.stop(); } ``` Each node is stopped by calling its {{domxref("AudioScheduledSourceNode.stop", "ConstantSourceNode.stop()")}} method. ### Result {{ EmbedLiveSample('Example', 600, 120) }} ## 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) - [Simple synth keyboard](/en-US/docs/Web/API/Web_Audio_API/Simple_synth) (example) - {{domxref("OscillatorNode")}} - {{domxref("ConstantSourceNode")}}
0
data/mdn-content/files/en-us/web/api/web_audio_api
data/mdn-content/files/en-us/web/api/web_audio_api/controlling_multiple_parameters_with_constantsourcenode/customsourcenode-as-splitter.svg
<svg xmlns="http://www.w3.org/2000/svg" viewBox="7 7 580 346" width="580pt" height="346pt"><defs><marker orient="auto" overflow="visible" markerUnits="strokeWidth" id="a" viewBox="-1 -3 7 6" markerWidth="7" markerHeight="6" color="#000"><path d="M4.8 0 0-1.8v3.6z" fill="currentColor" stroke="currentColor"/></marker></defs><g fill="none"><path fill="#867fff" d="M207 99h180v45H207z"/><path stroke="#000" stroke-linecap="round" stroke-linejoin="round" d="M207 99h180v45H207z"/><text transform="translate(212 113)" fill="#000"><tspan font-family="Courier" font-size="14" font-weight="500" x="9.388" y="14" textLength="151.225">ConstantSourceNode</tspan></text><path fill="#867fff" d="M9 216h180v45H9z"/><path stroke="#000" stroke-linecap="round" stroke-linejoin="round" d="M9 216h180v45H9z"/><text transform="translate(14 230)" fill="#000"><tspan font-family="Courier" font-size="14" font-weight="500" x="51.395" y="14" textLength="67.211">GainNode</tspan></text><path fill="#867fff" d="M405 216h180v45H405z"/><path stroke="#000" stroke-linecap="round" stroke-linejoin="round" d="M405 216h180v45H405z"/><text transform="translate(410 230)" fill="#000"><tspan font-family="Courier" font-size="14" font-weight="500" x="51.395" y="14" textLength="67.211">GainNode</tspan></text><path fill="#867fff" d="M207 216h180v45H207z"/><path stroke="#000" stroke-linecap="round" stroke-linejoin="round" d="M207 216h180v45H207z"/><text transform="translate(212 230)" fill="#000"><tspan font-family="Courier" font-size="14" font-weight="500" x="17.789" y="14" textLength="134.422">StereoPannerNode</tspan></text><path d="M252 144v27H99v32.1M297 144v59.1m45-59.1v27h153v32.1" marker-end="url(#a)" stroke="#000" stroke-linecap="round" stroke-linejoin="round" stroke-width="2"/><text transform="translate(55.876 192.447)" fill="#000"><tspan font-family="Courier" font-size="14" font-weight="500" x=".197" y="14" textLength="33.605">gain</tspan></text><text transform="translate(258.64 192.854)" fill="#000"><tspan font-family="Courier" font-size="14" font-weight="500" x=".398" y="14" textLength="25.204">pan</tspan></text><text transform="translate(504.37 193.347)" fill="#000"><tspan font-family="Courier" font-size="14" font-weight="500" x=".197" y="14" textLength="33.605">gain</tspan></text><path marker-end="url(#a)" stroke="#000" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M297 54v32.1"/><path d="M243 9h144l-36 45H207z" fill="#fff"/><path d="M243 9h144l-36 45H207z" stroke="#000" stroke-linecap="round" stroke-linejoin="round"/><text transform="translate(248 22)" fill="#000"><tspan font-family="Arial" font-size="16" font-weight="500" x="17.734" y="15" textLength="52.93">input = </tspan><tspan font-family="Courier" font-size="16" font-style="italic" font-weight="500" x="70.664" y="15" textLength="9.602">N</tspan></text><path d="M243 306h144l-36 45H207z" fill="#fff"/><path d="M243 306h144l-36 45H207z" stroke="#000" stroke-linecap="round" stroke-linejoin="round"/><text transform="translate(248 319)" fill="#000"><tspan font-family="Arial" font-size="16" font-weight="500" x="12.84" y="15" textLength="62.719">output = </tspan><tspan font-family="Courier" font-size="16" font-style="italic" font-weight="500" x="75.559" y="15" textLength="9.602">N</tspan></text><path marker-end="url(#a)" stroke="#000" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="m296.5 261 .357 32.101"/><path d="M441 306h144l-36 45H405z" fill="#fff"/><path d="M441 306h144l-36 45H405z" stroke="#000" stroke-linecap="round" stroke-linejoin="round"/><text transform="translate(446 319)" fill="#000"><tspan font-family="Arial" font-size="16" font-weight="500" x="12.84" y="15" textLength="62.719">output = </tspan><tspan font-family="Courier" font-size="16" font-style="italic" font-weight="500" x="75.559" y="15" textLength="9.602">N</tspan></text><path marker-end="url(#a)" stroke="#000" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M495 261v32.1"/><path d="M45 306h144l-36 45H9z" fill="#fff"/><path d="M45 306h144l-36 45H9z" stroke="#000" stroke-linecap="round" stroke-linejoin="round"/><text transform="translate(50 319)" fill="#000"><tspan font-family="Arial" font-size="16" font-weight="500" x="12.84" y="15" textLength="62.719">output = </tspan><tspan font-family="Courier" font-size="16" font-style="italic" font-weight="500" x="75.559" y="15" textLength="9.602">N</tspan></text><path marker-end="url(#a)" stroke="#000" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M99 261v32.1"/></g></svg>
0
data/mdn-content/files/en-us/web/api/web_audio_api
data/mdn-content/files/en-us/web/api/web_audio_api/simple_synth/index.md
--- title: "Example and tutorial: Simple synth keyboard" slug: Web/API/Web_Audio_API/Simple_synth page-type: guide --- {{DefaultAPISidebar("Web Audio API")}} This article presents the code and working demo of a video keyboard you can play using the mouse. The keyboard allows you to switch among the standard waveforms as well as one custom waveform, and you can control the main gain using a volume slider beneath the keyboard. This example makes use of the following Web API interfaces: {{domxref("AudioContext")}}, {{domxref("OscillatorNode")}}, {{domxref("PeriodicWave")}}, and {{domxref("GainNode")}}. Because {{domxref("OscillatorNode")}} is based on {{domxref("AudioScheduledSourceNode")}}, this is to some extent an example for that as well. ## The video keyboard ### HTML There are three primary components to the display for our virtual keyboard. The first is the musical keyboard itself. We draw this in a pair of nested {{HTMLElement("div")}} elements so that we can make the keyboard horizontally scrollable if all the keys don't fit on the screen, without having them wrap around. #### The keyboard First, we create space to build the keyboard into. We will be programmatically constructing the keyboard, because doing so gives us the flexibility to configure each key as we determine the appropriate data for the corresponding note. In our case, we get each key's frequency from a table, but it could be calculated algorithmically as well. ```html <div class="container"> <div class="keyboard"></div> </div> ``` The {{HTMLElement("div")}} named `"container"` is the scrollable box that lets the keyboard be scrolled horizontally if it's too wide for the available space. The keys themselves will be inserted into the block of class `"keyboard"`. #### The settings bar Beneath the keyboard, we'll put some controls for configuring the layer. For now, we will have two controls: one to set the main volume and another to select what periodic waveform to use when generating notes. ##### The volume control First we create the `<div>` to contain the settings bar, so it can be styled as needed. Then we establish a box that will be presented on the left side of the bar and place a label and an {{HTMLElement("input")}} element of type `"range"`. The range element will typically be presented as a slider control; we configure it to allow any value between 0.0 and 1.0, stepping by 0.01 each position. ```html <div class="settingsBar"> <div class="left"> <span>Volume: </span> <input type="range" min="0.0" max="1.0" step="0.01" value="0.5" list="volumes" name="volume" /> <datalist id="volumes"> <option value="0.0" label="Mute"></option> <option value="1.0" label="100%"></option> </datalist> </div> </div> ``` We specify a default value of 0.5, and we provide a {{HTMLElement("datalist")}} element which is connected to the range using the [`name`](/en-US/docs/Web/HTML/Global_attributes#name) attribute to find an option list whose ID matches; in this case, the data set is named `"volume"`. This lets us provide a set of common values and special strings which the browser may optionally choose to display in some fashion; we provide names for the values 0.0 ("Mute") and 1.0 ("100%"). ##### The waveform picker On the right side of the settings bar, we place a label and a {{HTMLElement("select")}} element named `"waveform"` whose options correspond to the available waveforms. ```html <div class="right"> <span>Current waveform: </span> <select name="waveform"> <option value="sine">Sine</option> <option value="square" selected>Square</option> <option value="sawtooth">Sawtooth</option> <option value="triangle">Triangle</option> <option value="custom">Custom</option> </select> </div> </div> ``` ### CSS ```css .container { overflow-x: scroll; overflow-y: hidden; width: 660px; height: 110px; white-space: nowrap; margin: 10px; } .keyboard { width: auto; padding: 0; margin: 0; } .key { cursor: pointer; font: 16px "Open Sans", "Lucida Grande", "Arial", sans-serif; border: 1px solid black; border-radius: 5px; width: 20px; height: 80px; text-align: center; box-shadow: 2px 2px darkgray; display: inline-block; position: relative; margin-right: 3px; user-select: none; -moz-user-select: none; -webkit-user-select: none; -ms-user-select: none; } .key div { position: absolute; bottom: 0; text-align: center; width: 100%; pointer-events: none; } .key div sub { font-size: 10px; pointer-events: none; } .key:hover { background-color: #eef; } .key:active, .active { background-color: #000; color: #fff; } .octave { display: inline-block; padding: 0 6px 0 0; } .settingsBar { padding-top: 8px; font: 14px "Open Sans", "Lucida Grande", "Arial", sans-serif; position: relative; vertical-align: middle; width: 100%; height: 30px; } .left { width: 50%; position: absolute; left: 0; display: table-cell; vertical-align: middle; } .left span, .left input { vertical-align: middle; } .right { width: 50%; position: absolute; right: 0; display: table-cell; vertical-align: middle; } .right span { vertical-align: middle; } .right input { vertical-align: baseline; } ``` ### JavaScript The JavaScript code begins by initializing a number of variables. ```js const audioContext = new AudioContext(); const oscList = []; let mainGainNode = null; ``` 1. `audioContext` is set to reference the global {{domxref("AudioContext")}} object (or `webkitAudioContext` if necessary). 2. `oscList` is set up to be ready to contain a list of all currently-playing oscillators. It starts off empty, since there are none playing yet. 3. `mainGainNode` is set to null; during the setup process, it will be configured to contain a {{domxref("GainNode")}} which all playing oscillators will connect to and play through to allow the overall volume to be controlled using a single slider control. ```js const keyboard = document.querySelector(".keyboard"); const wavePicker = document.querySelector("select[name='waveform']"); const volumeControl = document.querySelector("input[name='volume']"); ``` References to elements we'll need access to are obtained: - `keyboard` is the container element into which the keys will be placed. - `wavePicker` is the {{HTMLElement("select")}} element used to choose the waveform to use for the notes. - `volumeControl` is the {{HTMLElement("input")}} element (of type `"range"`) used to control the main audio volume. ```js let noteFreq = null; let customWaveform = null; let sineTerms = null; let cosineTerms = null; ``` Finally, global variables that will be used when constructing waveforms are created: - `noteFreq` will be an array of arrays; each array represents one octave, each of which contains one entry for each note in that octave. The value for each is the frequency, in Hertz, of the note's tone. - `customWaveform` will be set up as a {{domxref("PeriodicWave")}} describing the waveform to use when the user selects "Custom" from the waveform picker. - `sineTerms` and `cosineTerms` will be used to store the data for generating the waveform; each will contain an array that's generated when the user chooses "Custom". ### Creating the note table The `createNoteTable()` function builds the array `noteFreq` to contain an array of objects representing each octave. Each octave, in turn, has one named property for each note in that octave; the property's name is the note's name (such as "C#" to represent C-sharp), and the value is the frequency, in Hertz, of that note. ```js function createNoteTable() { const noteFreq = []; for (let i=0; i< 9; i++) { noteFreq[i] = []; } noteFreq[0]["A"] = 27.500000000000000; noteFreq[0]["A#"] = 29.135235094880619; noteFreq[0]["B"] = 30.867706328507756; noteFreq[1]["C"] = 32.703195662574829; noteFreq[1]["C#"] = 34.647828872109012; noteFreq[1]["D"] = 36.708095989675945; noteFreq[1]["D#"] = 38.890872965260113; noteFreq[1]["E"] = 41.203444614108741; noteFreq[1]["F"] = 43.653528929125485; noteFreq[1]["F#"] = 46.249302838954299; noteFreq[1]["G"] = 48.999429497718661; noteFreq[1]["G#"] = 51.913087197493142; noteFreq[1]["A"] = 55.000000000000000; noteFreq[1]["A#"] = 58.270470189761239; noteFreq[1]["B"] = 61.735412657015513; // … ``` Several octaves not shown for brevity. ```js hidden noteFreq[2]["C"] = 65.406391325149658; noteFreq[2]["C#"] = 69.295657744218024; noteFreq[2]["D"] = 73.41619197935189; noteFreq[2]["D#"] = 77.781745930520227; noteFreq[2]["E"] = 82.406889228217482; noteFreq[2]["F"] = 87.307057858250971; noteFreq[2]["F#"] = 92.498605677908599; noteFreq[2]["G"] = 97.998858995437323; noteFreq[2]["G#"] = 103.826174394986284; noteFreq[2]["A"] = 110.0; noteFreq[2]["A#"] = 116.540940379522479; noteFreq[2]["B"] = 123.470825314031027; noteFreq[3]["C"] = 130.812782650299317; noteFreq[3]["C#"] = 138.591315488436048; noteFreq[3]["D"] = 146.83238395870378; noteFreq[3]["D#"] = 155.563491861040455; noteFreq[3]["E"] = 164.813778456434964; noteFreq[3]["F"] = 174.614115716501942; noteFreq[3]["F#"] = 184.997211355817199; noteFreq[3]["G"] = 195.997717990874647; noteFreq[3]["G#"] = 207.652348789972569; noteFreq[3]["A"] = 220.0; noteFreq[3]["A#"] = 233.081880759044958; noteFreq[3]["B"] = 246.941650628062055; noteFreq[4]["C"] = 261.625565300598634; noteFreq[4]["C#"] = 277.182630976872096; noteFreq[4]["D"] = 293.66476791740756; noteFreq[4]["D#"] = 311.12698372208091; noteFreq[4]["E"] = 329.627556912869929; noteFreq[4]["F"] = 349.228231433003884; noteFreq[4]["F#"] = 369.994422711634398; noteFreq[4]["G"] = 391.995435981749294; noteFreq[4]["G#"] = 415.304697579945138; noteFreq[4]["A"] = 440.0; noteFreq[4]["A#"] = 466.163761518089916; noteFreq[4]["B"] = 493.883301256124111; noteFreq[5]["C"] = 523.251130601197269; noteFreq[5]["C#"] = 554.365261953744192; noteFreq[5]["D"] = 587.32953583481512; noteFreq[5]["D#"] = 622.253967444161821; noteFreq[5]["E"] = 659.255113825739859; noteFreq[5]["F"] = 698.456462866007768; noteFreq[5]["F#"] = 739.988845423268797; noteFreq[5]["G"] = 783.990871963498588; noteFreq[5]["G#"] = 830.609395159890277; noteFreq[5]["A"] = 880.0; noteFreq[5]["A#"] = 932.327523036179832; noteFreq[5]["B"] = 987.766602512248223; noteFreq[6]["C"] = 1046.502261202394538; noteFreq[6]["C#"] = 1108.730523907488384; noteFreq[6]["D"] = 1174.659071669630241; noteFreq[6]["D#"] = 1244.507934888323642; noteFreq[6]["E"] = 1318.510227651479718; noteFreq[6]["F"] = 1396.912925732015537; noteFreq[6]["F#"] = 1479.977690846537595; noteFreq[6]["G"] = 1567.981743926997176; noteFreq[6]["G#"] = 1661.218790319780554; noteFreq[6]["A"] = 1760.0; noteFreq[6]["A#"] = 1864.655046072359665; noteFreq[6]["B"] = 1975.533205024496447; ``` ```js noteFreq[7]["C"] = 2093.004522404789077; noteFreq[7]["C#"] = 2217.461047814976769; noteFreq[7]["D"] = 2349.318143339260482; noteFreq[7]["D#"] = 2489.015869776647285; noteFreq[7]["E"] = 2637.020455302959437; noteFreq[7]["F"] = 2793.825851464031075; noteFreq[7]["F#"] = 2959.955381693075191; noteFreq[7]["G"] = 3135.963487853994352; noteFreq[7]["G#"] = 3322.437580639561108; noteFreq[7]["A"] = 3520.000000000000000; noteFreq[7]["A#"] = 3729.310092144719331; noteFreq[7]["B"] = 3951.066410048992894; noteFreq[8]["C"] = 4186.009044809578154; return noteFreq; } ``` The result is an array, `noteFreq`, with an object for each octave. Each octave object has named properties in it where the property name is the name of the note (such as "C#" to represent C-sharp) and the property's value is the note's frequency in Hertz. In part, the resulting object looks like this: <table class="standard-table"> <tbody> <tr> <th scope="row">Octave</th> <td colspan="8">Notes</td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <th scope="row">0</th> <td>"A" ⇒ 27.5</td> <td>"A#" ⇒ 29.14</td> <td>"B" ⇒ 30.87</td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <th scope="row">1</th> <td>"C" ⇒ 32.70</td> <td>"C#" ⇒ 34.65</td> <td>"D" ⇒ 36.71</td> <td>"D#" ⇒ 38.89</td> <td>"E" ⇒ 41.20</td> <td>"F" ⇒ 43.65</td> <td>"F#" ⇒ 46.25</td> <td>"G" ⇒ 49</td> <td>"G#" ⇒ 51.9</td> <td>"A" ⇒ 55</td> <td>"A#" ⇒ 58.27</td> <td>"B" ⇒ 61.74</td> </tr> <tr> <th scope="row">2</th> <td colspan="12">. . .</td> </tr> </tbody> </table> With this table in place, we can find out the frequency for a given note in a particular octave quite easily. If we want the frequency for the note G# in octave 1, we use `noteFreq[1]["G#"]` and get the value 51.9 as a result. > **Note:** The values in the example table above have been rounded to two decimal places. ```js hidden if (!Object.entries) { Object.entries = function entries(O) { return reduce( keys(O), (e, k) => concat( e, typeof k === "string" && isEnumerable(O, k) ? [[k, O[k]]] : [], ), [], ); }; } ``` ### Building the keyboard The `setup()` function is responsible for building the keyboard and preparing the app to play music. ```js function setup() { noteFreq = createNoteTable(); volumeControl.addEventListener("change", changeVolume, false); mainGainNode = audioContext.createGain(); mainGainNode.connect(audioContext.destination); mainGainNode.gain.value = volumeControl.value; // Create the keys; skip any that are sharp or flat; for // our purposes we don't need them. Each octave is inserted // into a <div> of class "octave". noteFreq.forEach((keys, idx) => { const keyList = Object.entries(keys); const octaveElem = document.createElement("div"); octaveElem.className = "octave"; keyList.forEach((key) => { if (key[0].length === 1) { octaveElem.appendChild(createKey(key[0], idx, key[1])); } }); keyboard.appendChild(octaveElem); }); document .querySelector("div[data-note='B'][data-octave='5']") .scrollIntoView(false); sineTerms = new Float32Array([0, 0, 1, 0, 1]); cosineTerms = new Float32Array(sineTerms.length); customWaveform = audioContext.createPeriodicWave(cosineTerms, sineTerms); for (let i = 0; i < 9; i++) { oscList[i] = {}; } } setup(); ``` 1. The table which maps note names and octaves to their frequencies is created by calling `createNoteTable()`. 2. An event handler is established (by calling our old friend {{domxref("EventTarget.addEventListener", "addEventListener()")}} to handle {{domxref("HTMLElement/change_event", "change")}} events on the main gain control. This will update the main gain node's volume to the new value of the control. 3. Next, we iterate over each octave in the note frequencies table. For each octave, we use {{jsxref("Object.entries()")}} to get a list of the notes in that octave. 4. Create a {{HTMLElement("div")}} to contain that octave's notes (so we can have a small bit of space drawn between octaves), and set its class name to "octave" 5. For each key in the octave, we check to see if the note's name has more than one character. We skip these, because we're leaving out the sharp notes in this example. If the note's name is only one character, then we call `createKey()`, specifying the note string, octave, and frequency. The returned element is appended to the octave element created in step 4. 6. When each octave element has been built, it's appended to the keyboard. 7. Once the keyboard has been constructed, we scroll the note "B" in octave 5 into view; this has the effect of ensuring that middle-C is visible along with its surrounding keys. 8. Then a new custom waveform is built using {{domxref("BaseAudioContext.createPeriodicWave()")}}. This waveform will be used any time the user selects "Custom" from the waveform picker control. 9. Finally, the oscillator list is initialized to ensure that it's ready to receive information identifying which oscillators are associated with which keys. #### Creating a key The `createKey()` function is called once for each key that we want to present in the virtual keyboard. It creates the elements that comprise the key and its label, adds some data attributes to the element for later use, and assigns event handlers for the events we care about. ```js function createKey(note, octave, freq) { const keyElement = document.createElement("div"); const labelElement = document.createElement("div"); keyElement.className = "key"; keyElement.dataset["octave"] = octave; keyElement.dataset["note"] = note; keyElement.dataset["frequency"] = freq; labelElement.innerHTML = `${note}<sub>${octave}</sub>`; keyElement.appendChild(labelElement); keyElement.addEventListener("mousedown", notePressed, false); keyElement.addEventListener("mouseup", noteReleased, false); keyElement.addEventListener("mouseover", notePressed, false); keyElement.addEventListener("mouseleave", noteReleased, false); return keyElement; } ``` After creating the elements that will represent the key and its label, we configure the key's element by setting its class to "key" (which establishes its appearance). Then we add [`data-*`](/en-US/docs/Web/HTML/Global_attributes#data-*) attributes which contain the key's octave (attribute `data-octave`), string representing the note to play (attribute `data-note`), and frequency (attribute `data-frequency`) in Hertz. This will let us easily fetch that information as needed when handling events. ### Making music #### Playing a tone The `playTone()` function's job is to play a tone at the given frequency. This will be used by the handler for events triggering keys on the keyboard to start playing the appropriate notes. ```js function playTone(freq) { const osc = audioContext.createOscillator(); osc.connect(mainGainNode); const type = wavePicker.options[wavePicker.selectedIndex].value; if (type === "custom") { osc.setPeriodicWave(customWaveform); } else { osc.type = type; } osc.frequency.value = freq; osc.start(); return osc; } ``` `playTone()` begins by creating a new {{domxref("OscillatorNode")}} by calling the {{domxref("BaseAudioContext.createOscillator()")}} method. We then connect it to the main gain node by calling the new oscillator's {{domxref("AudioNode/connect", "connect()")}} method;, which tells the oscillator where to send its output to. By doing this, changing the gain of the main gain node will affect the volume of all tones being generated. Then we get the type of waveform to use by checking the value of the waveform picker control in the settings bar. If the user has it set to `"custom"`, we call {{domxref("OscillatorNode.setPeriodicWave()")}} to configure the oscillator to use our custom waveform. Doing this automatically sets the oscillator's {{domxref("OscillatorNode.type", "type")}} to `custom`. If any other waveform type is selected in the wave picker, we set the oscillator's type to the value of the picker; that value will be one of `sine`, `square`, `triangle`, and `sawtooth`. The oscillator's frequency is set to the value specified in the `freq` parameter by setting the value of the {{domxref("OscillatorNode.frequency")}} {{domxref("AudioParam")}} object. Then, at last, the oscillator is started up so that it begins to produce sound by calling the oscillator's inherited {{domxref("AudioScheduledSourceNode.start()")}} method. #### Playing a note When the {{domxref("Element/mousedown_event", "mousedown")}} or {{domxref("Element/mouseover_event", "mouseover")}} event occurs on a key, we want to start playing the corresponding note. The `notePressed()` function is used as the event handler for these events. ```js function notePressed(event) { if (event.buttons & 1) { const dataset = event.target.dataset; if (!dataset["pressed"] && dataset["octave"]) { const octave = Number(dataset["octave"]); oscList[octave][dataset["note"]] = playTone(dataset["frequency"]); dataset["pressed"] = "yes"; } } } ``` We start by checking whether the primary mouse button is pressed, for two reasons. First, we want to only allow the primary mouse button to trigger notes playing. Second, and more importantly, we are using this to handle {{domxref("Element/mouseover_event", "mouseover")}} for cases where the user is dragging from note to note, and we only want to start playing the note if the mouse is pressed when it enters the element. If the mouse button is in fact down, we get the pressed key's [`dataset`](/en-US/docs/Web/HTML/Global_attributes#dataset) attribute; this makes it easy to access the custom data attributes on the element. We look for a `data-pressed` attribute; if there isn't one (which indicates that the note isn't already playing), we call `playTone()` to start playing the note, passing in the value of the element's `data-frequency` attribute. The returned oscillator is stored into `oscList` for future reference, and `data-pressed` is set to `yes` to indicate that the note is playing so we don't start it again next time this is called. #### Stopping a tone The `noteReleased()` function is the event handler called when the user releases the mouse button or moves the mouse out of the key that's currently playing. ```js function noteReleased(event) { const dataset = event.target.dataset; if (dataset && dataset["pressed"]) { const octave = Number(dataset["octave"]); if (oscList[octave] && oscList[octave][dataset["note"]]) { oscList[octave][dataset["note"]].stop(); delete oscList[octave][dataset["note"]]; delete dataset["pressed"]; } } } ``` `noteReleased()` uses the `data-octave` and `data-note` custom attributes to look up the key's oscillator, then calls the oscillator's inherited {{domxref("AudioScheduledSourceNode.stop", "stop()")}} method to stop playing the note. Finally, the `oscList` entry for the note is cleared and the `data-pressed` attribute is removed from the key element (as identified by {{domxref("event.target")}}), to indicate that the note is not currently playing. #### Changing the main volume The volume slider in the settings bar provides a simple interface to change the gain value on the main gain node, thereby changing the loudness of all playing notes. The `changeVolume()` method is the handler for the {{domxref("HTMLElement/change_event", "change")}} event on the slider. ```js function changeVolume(event) { mainGainNode.gain.value = volumeControl.value; } ``` This sets the value of the main gain node's `gain` {{domxref("AudioParam")}} to the slider's new value. #### Keyboard support The code below adds [`keydown`](/en-US/docs/Web/API/Element/keydown_event) and [`keyup`](/en-US/docs/Web/API/Element/keyup_event) event listeners to handle keyboard input. The `keydown` event handler calls `notePressed()` to start playing the note corresponding to the key that was pressed, and the `keyup` event handler calls `noteReleased()` to stop playing the note corresponding to the key that was released. ```js-nolint const synthKeys = document.querySelectorAll(".key"); const keyCodes = [ "Space", "ShiftLeft", "KeyZ", "KeyX", "KeyC", "KeyV", "KeyB", "KeyN", "KeyM", "Comma", "Period", "Slash", "ShiftRight", "KeyA", "KeyS", "KeyD", "KeyF", "KeyG", "KeyH", "KeyJ", "KeyK", "KeyL", "Semicolon", "Quote", "Enter", "Tab", "KeyQ", "KeyW", "KeyE", "KeyR", "KeyT", "KeyY", "KeyU", "KeyI", "KeyO", "KeyP", "BracketLeft", "BracketRight", "Digit1", "Digit2", "Digit3", "Digit4", "Digit5", "Digit6", "Digit7", "Digit8", "Digit9", "Digit0", "Minus", "Equal", "Backspace", "Escape", ]; function keyNote(event) { const elKey = synthKeys[keyCodes.indexOf(event.code)]; if (elKey) { if (event.type === "keydown") { elKey.tabIndex = -1; elKey.focus(); elKey.classList.add("active"); notePressed({ buttons: 1, target: elKey }); } else { elKey.classList.remove("active"); noteReleased({ buttons: 1, target: elKey }); } event.preventDefault(); } } addEventListener("keydown", keyNote); addEventListener("keyup", keyNote); ``` ### Result Put all together, the result is a simple but working point-and-click musical keyboard: {{ EmbedLiveSample('The_video_keyboard', 680, 200) }} ## See also - [Web Audio API](/en-US/docs/Web/API/Web_Audio_API) - {{domxref("OscillatorNode")}} - {{domxref("GainNode")}} - {{domxref("AudioContext")}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/filesystemdirectoryhandle/index.md
--- title: FileSystemDirectoryHandle slug: Web/API/FileSystemDirectoryHandle page-type: web-api-interface browser-compat: api.FileSystemDirectoryHandle --- {{securecontext_header}}{{APIRef("File System API")}} The **`FileSystemDirectoryHandle`** interface of the {{domxref("File System API", "File System API", "", "nocode")}} provides a handle to a file system directory. The interface can be accessed via the {{domxref('window.showDirectoryPicker()')}}, {{domxref('StorageManager.getDirectory()')}}, {{domxref('DataTransferItem.getAsFileSystemHandle()')}}, and {{domxref('FileSystemDirectoryHandle.getDirectoryHandle()')}} methods. {{InheritanceDiagram}} ## Instance properties _Inherits properties from its parent, {{DOMxRef("FileSystemHandle")}}._ ## Instance methods _Inherits methods from its parent, {{DOMxRef("FileSystemHandle")}}._ Regular methods: - {{domxref('FileSystemDirectoryHandle.getDirectoryHandle()')}} - : Returns a {{jsxref('Promise')}} fulfilled with a {{domxref('FileSystemDirectoryHandle')}} for a subdirectory with the specified name within the directory handle on which the method is called. - {{domxref('FileSystemDirectoryHandle.getFileHandle()')}} - : Returns a {{jsxref('Promise')}} fulfilled with a {{domxref('FileSystemFileHandle')}} for a file with the specified name, within the directory the method is called. - {{domxref('FileSystemDirectoryHandle.removeEntry()')}} - : Attempts to asynchronously remove an entry if the directory handle contains a file or directory called the name specified. - {{domxref('FileSystemDirectoryHandle.resolve()')}} - : Returns a {{jsxref('Promise')}} fulfilled with an {{jsxref('Array')}} of directory names from the parent handle to the specified child entry, with the name of the child entry as the last array item. [Asynchronous iterator](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_async_iterator_and_async_iterable_protocols) methods: - {{domxref('FileSystemDirectoryHandle.entries()')}} - : Returns a new _async iterator_ of a given object's own enumerable property `[key, value]` pairs. - {{domxref('FileSystemDirectoryHandle.keys()')}} - : Returns a new _async iterator_ containing the keys for each item in `FileSystemDirectoryHandle`. - {{domxref('FileSystemDirectoryHandle.values()')}} - : Returns a new _async iterator_ containing the values for each index in the `FileSystemDirectoryHandle` object. - [`FileSystemDirectoryHandle[@@asyncIterator]()`](/en-US/docs/Web/API/FileSystemDirectoryHandle/entries) - : Returns the `entries` function by default. ## Examples ### Return directory handle The following example returns a directory handle with the specified name; if the directory does not already exist it is created. ```js const dirName = "directoryToGetName"; // assuming we have a directory handle: 'currentDirHandle' const subDir = currentDirHandle.getDirectoryHandle(dirName, { create: true }); ``` ### Return file path The following asynchronous function uses `resolve()` to find the path to a chosen file, relative to a specified directory handle. ```js async function returnPathDirectories(directoryHandle) { // Get a file handle by showing a file picker: const handle = await self.showOpenFilePicker(); if (!handle) { // User cancelled, or otherwise failed to open a file. return; } // Check if handle exists inside our directory handle const relativePaths = await directoryHandle.resolve(handle); if (relativePath === null) { // Not inside directory handle } else { // relativePath is an array of names, giving the relative path for (const name of relativePaths) { // log each entry console.log(name); } } } ``` ### Return handles for all files in a directory The following example scans recursively through a directory to return {{domxref('FileSystemFileHandle')}} objects for each file in that directory: ```js async function* getFilesRecursively(entry) { if (entry.kind === "file") { const file = await entry.getFile(); if (file !== null) { file.relativePath = getRelativePath(entry); yield file; } } else if (entry.kind === "directory") { for await (const handle of entry.values()) { yield* getFilesRecursively(handle); } } } for await (const fileHandle of getFilesRecursively(directoryHandle)) { console.log(fileHandle); } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [File System API](/en-US/docs/Web/API/File_System_API) - [The File System Access API: simplifying access to local files](https://developer.chrome.com/docs/capabilities/web-apis/file-system-access)
0
data/mdn-content/files/en-us/web/api/filesystemdirectoryhandle
data/mdn-content/files/en-us/web/api/filesystemdirectoryhandle/removeentry/index.md
--- title: "FileSystemDirectoryHandle: removeEntry() method" short-title: removeEntry() slug: Web/API/FileSystemDirectoryHandle/removeEntry page-type: web-api-instance-method browser-compat: api.FileSystemDirectoryHandle.removeEntry --- {{securecontext_header}}{{APIRef("File System API")}} The **`removeEntry()`** method of the {{domxref("FileSystemDirectoryHandle")}} interface attempts to remove an entry if the directory handle contains a file or directory called the name specified. ## Syntax ```js-nolint removeEntry(name) removeEntry(name, options) ``` ### Parameters - `name` - : A string representing the {{domxref('FileSystemHandle.name')}} of the entry you wish to remove. - `options` {{optional_inline}} - : An optional object containing options, which are as follows: - `recursive` {{optional_inline}} - : A boolean value, which defaults to `false`. When set to `true` entries will be removed recursively. ### Return value A {{jsxref('Promise')}} which resolves with `undefined`. ### Exceptions - {{jsxref("TypeError")}} - : Thrown if the name is not a valid string or contains characters not allowed on the file system. - `NotAllowedError` {{domxref("DOMException")}} - : Thrown if the {{domxref('PermissionStatus.state')}} for the handle is not `'granted'` in `readwrite` mode. - `InvalidModificationError` {{domxref("DOMException")}} - : Thrown if `recursive` is set to false and the entry to be removed has children. - `NotFoundError` {{domxref("DOMException")}} - : Thrown if the current entry is not found or if the entry of the specific name is not found or matched. ## Examples The following example removes an entry within the directory handle. ```js const entryName = "entryToRemove"; // assuming we have a directory handle: 'currentDirHandle' currentDirHandle.removeEntry(entryName).then(() => { // code to run if removing was successful }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [File System API](/en-US/docs/Web/API/File_System_API) - [The File System Access API: simplifying access to local files](https://developer.chrome.com/docs/capabilities/web-apis/file-system-access)
0
data/mdn-content/files/en-us/web/api/filesystemdirectoryhandle
data/mdn-content/files/en-us/web/api/filesystemdirectoryhandle/keys/index.md
--- title: "FileSystemDirectoryHandle: keys() method" short-title: keys() slug: Web/API/FileSystemDirectoryHandle/keys page-type: web-api-instance-method browser-compat: api.FileSystemDirectoryHandle.keys --- {{securecontext_header}}{{APIRef("File System API")}} The **`keys()`** method of the {{domxref("FileSystemDirectoryHandle")}} interface returns a new asynchronous iterator for the iteration of the key of the entries within the `FileSystemDirectoryHandle` on which this method is called. ## Syntax ```js-nolint FileSystemDirectoryHandle.keys() ``` ### Parameters None. ### Return value A new asynchronous iterator containing the keys of each entry within the `FileSystemDirectoryHandle`. ### Exceptions - `NotAllowedError` {{domxref("DOMException")}} - : Thrown if the {{domxref('PermissionStatus.state')}} for the handle is not `'granted'` in `read` mode. - `NotFoundError` {{domxref("DOMException")}} - : Thrown if the current entry is not found. ## Examples Use the `for await...of` loop can simplify the iteration process. ```js const dirHandle = await window.showDirectoryPicker(); for await (const key of dirHandle.keys()) { console.log(key); } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [File System API](/en-US/docs/Web/API/File_System_API) - [The File System Access API: simplifying access to local files](https://developer.chrome.com/docs/capabilities/web-apis/file-system-access)
0
data/mdn-content/files/en-us/web/api/filesystemdirectoryhandle
data/mdn-content/files/en-us/web/api/filesystemdirectoryhandle/getfilehandle/index.md
--- title: "FileSystemDirectoryHandle: getFileHandle() method" short-title: getFileHandle() slug: Web/API/FileSystemDirectoryHandle/getFileHandle page-type: web-api-instance-method browser-compat: api.FileSystemDirectoryHandle.getFileHandle --- {{securecontext_header}}{{APIRef("File System API")}} The **`getFileHandle()`** method of the {{domxref("FileSystemDirectoryHandle")}} interface returns a {{domxref('FileSystemFileHandle')}} for a file with the specified name, within the directory the method is called. ## Syntax ```js-nolint getFileHandle(name) getFileHandle(name, options) ``` ### Parameters - `name` - : A string representing the {{domxref('FileSystemHandle.name')}} of the file you wish to retrieve. - `options` {{optional_inline}} - : An object with the following properties: - `create` {{optional_inline}} - : A {{jsxref('Boolean')}}. Default `false`. When set to `true` if the file is not found, one with the specified name will be created and returned. ### Return value A {{jsxref('Promise')}} which resolves with a {{domxref('FileSystemFileHandle')}}. ### Exceptions - `NotAllowedError` {{domxref("DOMException")}} - : Thrown if the {{domxref('PermissionStatus.state')}} for the handle is not `'granted'` in `readwrite` mode if the `create` option is set to `true` or in `read` mode if the `create` option is set to `false`. - {{jsxref("TypeError")}} - : Thrown if the name specified is not a valid string or contains characters that would interfere with the native file system. - `TypeMismatchError` {{domxref("DOMException")}} - : Thrown if the named entry is a directory and not a file. - `NotFoundError` {{domxref("DOMException")}} - : Thrown if the current entry is not found or if the file doesn't exist and the `create` option is set to `false`. ## Examples The following example returns a file handle with the specified name, if the file does not exist it is created. ```js const fileName = "fileToGetName"; // assuming we have a directory handle: 'currentDirHandle' const fileHandle = currentDirHandle.getFileHandle(fileName, { create: true }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [File System API](/en-US/docs/Web/API/File_System_API) - [The File System Access API: simplifying access to local files](https://developer.chrome.com/docs/capabilities/web-apis/file-system-access)
0
data/mdn-content/files/en-us/web/api/filesystemdirectoryhandle
data/mdn-content/files/en-us/web/api/filesystemdirectoryhandle/resolve/index.md
--- title: "FileSystemDirectoryHandle: resolve() method" short-title: resolve() slug: Web/API/FileSystemDirectoryHandle/resolve page-type: web-api-instance-method browser-compat: api.FileSystemDirectoryHandle.resolve --- {{securecontext_header}}{{APIRef("File System API")}} The **`resolve()`** method of the {{domxref("FileSystemDirectoryHandle")}} interface returns an {{jsxref('Array')}} of directory names from the parent handle to the specified child entry, with the name of the child entry as the last array item. ## Syntax ```js-nolint resolve(possibleDescendant) ``` ### Parameters - `possibleDescendant` - : The {{domxref('FileSystemHandle')}} from which to return the relative path. ### Return value A {{jsxref('Promise')}} which resolves with an {{jsxref('Array')}} of strings, or `null` if `possibleDescendant` is not a descendant of this {{domxref('FileSystemDirectoryHandle')}}. ### Exceptions No exceptions are thrown. ## Examples The following asynchronous function uses `resolve()` to find the path to a chosen file, relative to a specified directory handle. ```js async function returnPathDirectories(directoryHandle) { // Get a file handle by showing a file picker: const [handle] = await self.showOpenFilePicker(); if (!handle) { // User cancelled, or otherwise failed to open a file. return; } // Check if handle exists inside our directory handle const relativePaths = await directoryHandle.resolve(handle); if (relativePaths === null) { // Not inside directory handle } else { // relativePath is an array of names, giving the relative path for (const name of relativePaths) { // log each entry console.log(name); } } } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [File System API](/en-US/docs/Web/API/File_System_API) - [The File System Access API: simplifying access to local files](https://developer.chrome.com/docs/capabilities/web-apis/file-system-access)
0
data/mdn-content/files/en-us/web/api/filesystemdirectoryhandle
data/mdn-content/files/en-us/web/api/filesystemdirectoryhandle/getdirectoryhandle/index.md
--- title: "FileSystemDirectoryHandle: getDirectoryHandle() method" short-title: getDirectoryHandle() slug: Web/API/FileSystemDirectoryHandle/getDirectoryHandle page-type: web-api-instance-method browser-compat: api.FileSystemDirectoryHandle.getDirectoryHandle --- {{securecontext_header}}{{APIRef("File System API")}} The **`getDirectoryHandle()`** method of the {{domxref("FileSystemDirectoryHandle")}} interface returns a {{domxref('FileSystemDirectoryHandle')}} for a subdirectory with the specified name within the directory handle on which the method is called. ## Syntax ```js-nolint getDirectoryHandle(name) getDirectoryHandle(name, options) ``` ### Parameters - `name` - : A string representing the {{domxref('FileSystemHandle.name')}} of the subdirectory you wish to retrieve. - `options` {{optional_inline}} - : An optional object containing options for the retrieved subdirectory. Options are as follows: - `create` {{optional_inline}} - : A boolean value, which defaults to `false`. When set to `true` if the directory is not found, one with the specified name will be created and returned. ### Return value A {{jsxref('Promise')}} which resolves with a {{domxref('FileSystemDirectoryHandle')}}. ### Exceptions - `NotAllowedError` {{domxref("DOMException")}} - : Thrown if the {{domxref('PermissionStatus.state')}} for the handle is not `'granted'` in `readwrite` mode if the `create` option is set to `true` or in `read` mode if the `create` option is set to `false`. - {{jsxref("TypeError")}} - : Thrown if the name specified is not a valid string or contains characters that would interfere with the native file system. - `TypeMismatchError` {{domxref("DOMException")}} - : Thrown if the returned entry is a file and not a directory. - `NotFoundError` {{domxref("DOMException")}} - : Thrown if the current entry is not found or if the target directory doesn't exist and the `create` option is set to `false`. ## Examples The following example returns a directory handle with the specified name, if the directory does not exist it is created. ```js const dirName = "directoryToGetName"; // assuming we have a directory handle: 'currentDirHandle' const subDir = currentDirHandle.getDirectoryHandle(dirName, { create: true }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [File System API](/en-US/docs/Web/API/File_System_API) - [The File System Access API: simplifying access to local files](https://developer.chrome.com/docs/capabilities/web-apis/file-system-access)
0
data/mdn-content/files/en-us/web/api/filesystemdirectoryhandle
data/mdn-content/files/en-us/web/api/filesystemdirectoryhandle/values/index.md
--- title: "FileSystemDirectoryHandle: values() method" short-title: values() slug: Web/API/FileSystemDirectoryHandle/values page-type: web-api-instance-method browser-compat: api.FileSystemDirectoryHandle.values --- {{securecontext_header}}{{APIRef("File System API")}} The **`values()`** method of the {{domxref("FileSystemDirectoryHandle")}} interface returns a new asynchronous iterator for the iteration of the value of the entries within the `FileSystemDirectoryHandle` on which this method is called. ## Syntax ```js-nolint values() ``` ### Parameters None. ### Return value A new asynchronous iterator containing the handles of each entry within the `FileSystemDirectoryHandle`. ### Exceptions - `NotAllowedError` {{domxref("DOMException")}} - : Thrown if the {{domxref('PermissionStatus.state')}} for the handle is not `'granted'` in `read` mode. - `NotFoundError` {{domxref("DOMException")}} - : Thrown if the current entry is not found. ## Examples Use the `for await...of` loop can simplify the iteration process. ```js const dirHandle = await window.showDirectoryPicker(); for await (const value of dirHandle.values()) { console.log(value); } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [File System API](/en-US/docs/Web/API/File_System_API) - [The File System Access API: simplifying access to local files](https://developer.chrome.com/docs/capabilities/web-apis/file-system-access)
0
data/mdn-content/files/en-us/web/api/filesystemdirectoryhandle
data/mdn-content/files/en-us/web/api/filesystemdirectoryhandle/entries/index.md
--- title: "FileSystemDirectoryHandle: entries() method" short-title: entries() slug: Web/API/FileSystemDirectoryHandle/entries page-type: web-api-instance-method browser-compat: api.FileSystemDirectoryHandle.entries --- {{securecontext_header}}{{APIRef("File System API")}} The **`entries()`** method of the {{domxref("FileSystemDirectoryHandle")}} interface returns a new asynchronous iterator for the iteration of the key-value pairs of the entries within the `FileSystemDirectoryHandle` on which this method is called. The key-value pairs are in the form of an array like `[key, value]`. ## Syntax ```js-nolint entries() ``` ### Parameters None. ### Return value A new asynchronous iterator containing the key-value pairs of each entry within the `FileSystemDirectoryHandle`. ### Exceptions - `NotAllowedError` {{domxref("DOMException")}} - : Thrown if the {{domxref('PermissionStatus.state')}} for the handle is not `'granted'` in `read` mode. - `NotFoundError` {{domxref("DOMException")}} - : Thrown if the current entry is not found. ## Examples Use the `for await...of` loop can simplify the iteration process. ```js const dirHandle = await window.showDirectoryPicker(); for await (const [key, value] of dirHandle.entries()) { console.log({ key, value }); } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [File System API](/en-US/docs/Web/API/File_System_API) - [The File System Access API: simplifying access to local files](https://developer.chrome.com/docs/capabilities/web-apis/file-system-access)
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/animationtimeline/index.md
--- title: AnimationTimeline slug: Web/API/AnimationTimeline page-type: web-api-interface browser-compat: api.AnimationTimeline --- {{ APIRef("Web Animations") }} The `AnimationTimeline` interface of the [Web Animations API](/en-US/docs/Web/API/Web_Animations_API) represents the timeline of an animation. This interface exists to define timeline features, inherited by other timeline types: - {{domxref("DocumentTimeline")}} - {{domxref("ScrollTimeline")}} - {{domxref("ViewTimeline")}} ## Instance properties - {{domxref("AnimationTimeline.currentTime", "currentTime")}} {{ReadOnlyInline}} - : Returns the time value in milliseconds for this timeline or `null` if this timeline is inactive. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("DocumentTimeline")}}, {{domxref("ScrollTimeline")}}, {{domxref("ViewTimeline")}} - {{domxref("Document.timeline")}} - [Web Animations API](/en-US/docs/Web/API/Web_Animations_API) - [CSS scroll-driven animations](/en-US/docs/Web/CSS/CSS_scroll-driven_animations)
0
data/mdn-content/files/en-us/web/api/animationtimeline
data/mdn-content/files/en-us/web/api/animationtimeline/currenttime/index.md
--- title: "AnimationTimeline: currentTime property" short-title: currentTime slug: Web/API/AnimationTimeline/currentTime page-type: web-api-instance-property browser-compat: api.AnimationTimeline.currentTime --- {{ APIRef("Web Animations") }} The **`currentTime`** read-only property of the [Web Animations API](/en-US/docs/Web/API/Web_Animations_API)'s {{domxref("AnimationTimeline")}} interface returns the timeline's current time in milliseconds, or `null` if the timeline is inactive. ## Value A number representing the timeline's current time in milliseconds, or `null` if the timeline is inactive. ## Reduced time precision To offer protection against timing attacks and [fingerprinting](/en-US/docs/Glossary/Fingerprinting), the precision of `animationTimeline.currentTime` might get rounded depending on browser settings. In Firefox, the `privacy.reduceTimerPrecision` preference is enabled by default and defaults to 20us in Firefox 59; in 60 it will be 2ms. ```js // reduced time precision (2ms) in Firefox 60 animationTimeline.currentTime; // 23.404 // 24.192 // 25.514 // … // reduced time precision with `privacy.resistFingerprinting` enabled animationTimeline.currentTime; // 49.8 // 50.6 // 51.7 // … ``` In Firefox, you can also enable `privacy.resistFingerprinting`; the precision will be 100ms or the value of `privacy.resistFingerprinting.reduceTimerPrecision.microseconds`, whichever is larger. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Web Animations API](/en-US/docs/Web/API/Web_Animations_API) - {{domxref("AnimationTimeline")}} - {{domxref("DocumentTimeline")}} inherits this property - {{domxref("Document.timeline")}} returns a timeline object which inherits this property
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/btoa/index.md
--- title: btoa() global function short-title: btoa() slug: Web/API/btoa page-type: web-api-global-function browser-compat: api.btoa --- {{APIRef("HTML DOM")}}{{AvailableInWorkers}} The **`btoa()`** method creates a {{glossary("Base64")}}-encoded {{Glossary("ASCII")}} string from a _binary string_ (i.e., a string in which each character in the string is treated as a byte of binary data). You can use this method to encode data which may otherwise cause communication problems, transmit it, then use the {{domxref("atob", "atob()")}} method to decode the data again. For example, you can encode control characters such as ASCII values 0 through 31. ## Syntax ```js-nolint btoa(stringToEncode) ``` ### Parameters - `stringToEncode` - : The _binary string_ to encode. ### Return value An ASCII string containing the Base64 representation of `stringToEncode`. ### Exceptions - `InvalidCharacterError` {{domxref("DOMException")}} - : The string contained a character that did not fit in a single byte. See "Unicode strings" below for more detail. ## Examples ```js const encodedData = btoa("Hello, world"); // encode a string const decodedData = atob(encodedData); // decode the string ``` ## Unicode strings Base64, by design, expects binary data as its input. In terms of JavaScript strings, this means strings in which the code point of each character occupies only one byte. So if you pass a string into `btoa()` containing characters that occupy more than one byte, you will get an error, because this is not considered binary data: ```js const ok = "a"; console.log(ok.codePointAt(0).toString(16)); // 61: occupies < 1 byte const notOK = "✓"; console.log(notOK.codePointAt(0).toString(16)); // 2713: occupies > 1 byte console.log(btoa(ok)); // YQ== console.log(btoa(notOK)); // error ``` For how to work around this limitation when dealing with arbitrary Unicode text, see [The "Unicode Problem"](/en-US/docs/Glossary/Base64#the_unicode_problem) section of the {{Glossary("Base64")}} glossary entry. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [A polyfill of `btoa`](https://github.com/zloirock/core-js#base64-utility-methods) is available in [`core-js`](https://github.com/zloirock/core-js) - [`data` URLs](/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URLs) - {{domxref("atob","atob()")}} - {{Glossary("Base64")}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/htmldlistelement/index.md
--- title: HTMLDListElement slug: Web/API/HTMLDListElement page-type: web-api-interface browser-compat: api.HTMLDListElement --- {{ApiRef("HTML DOM")}} The **`HTMLDListElement`** interface provides special properties (beyond those of the regular {{domxref("HTMLElement")}} interface it also has available to it by inheritance) for manipulating definition list ({{HtmlElement("dl")}}) elements. {{InheritanceDiagram}} ## Instance properties _Inherits properties from its parent, {{domxref("HTMLElement")}}._ - {{domxref("HTMLDListElement.compact")}} {{deprecated_inline}} - : A boolean value indicating that spacing between list items should be reduced. ## Instance methods _No specific methods; inherits methods from its parent, {{domxref("HTMLElement")}}._ ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The HTML element implementing this interface: {{ HTMLElement("dl") }}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/htmlformcontrolscollection/index.md
--- title: HTMLFormControlsCollection slug: Web/API/HTMLFormControlsCollection page-type: web-api-interface browser-compat: api.HTMLFormControlsCollection --- {{APIRef("HTML DOM")}} The **`HTMLFormControlsCollection`** interface represents a _collection_ of HTML _form control elements_, returned by the {{domxref("HTMLFormElement")}} interface's {{domxref("HTMLFormElement.elements", "elements")}} property. This interface replaces one method from {{domxref("HTMLCollection")}}, on which it is based. {{InheritanceDiagram}} ## Instance properties _This interface inherits the properties of its parent, {{domxref("HTMLCollection")}}._ ## Instance methods _This interface inherits the methods of its parent, {{domxref("HTMLCollection")}}._ - {{domxref("HTMLFormControlsCollection.namedItem()")}} - : Returns the {{domxref("RadioNodeList")}} or the {{domxref("Element")}} in the collection whose `name` or `id` matches the specified name, or `null` if no nodes match. Note that this version of `namedItem()` hides the one inherited from {{domxref("HTMLCollection")}}. Like that method, using the JavaScript array bracket syntax with a {{jsxref("String")}}, as in `collection["value"]`, is equivalent to `collection.namedItem("value")`. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("HTMLCollection")}}, {{domxref("RadioNodeList")}}, {{domxref("HTMLOptionsCollection")}}
0
data/mdn-content/files/en-us/web/api/htmlformcontrolscollection
data/mdn-content/files/en-us/web/api/htmlformcontrolscollection/nameditem/index.md
--- title: "HTMLFormControlsCollection: namedItem() method" short-title: namedItem() slug: Web/API/HTMLFormControlsCollection/namedItem page-type: web-api-instance-method browser-compat: api.HTMLFormControlsCollection.namedItem --- {{APIRef("HTML DOM")}} The **`HTMLFormControlsCollection.namedItem()`** method returns the {{domxref("RadioNodeList")}} or the {{domxref("Element")}} in the collection whose `name` or `id` match the specified name, or `null` if no node matches. Note that this version of `namedItem()` hides the one inherited from {{domxref("HTMLCollection")}}. Like that one, in JavaScript, using the array bracket syntax with a {{jsxref("String")}}, like `collection["value"]` is equivalent to `collection.namedItem("value")`. ## Syntax ```js-nolint namedItem(name) [name] ``` ### Parameters - `name` - : A string which will be used to match against the `name` or `id` attributes of the controls in this `HTMLFormControlsCollection` object. ### Return value - A {{domxref("RadioNodeList")}}, {{domxref("Element")}}, or [`null`](/en-US/docs/Web/JavaScript/Reference/Operators/null). ## Examples ### Using namedItem() #### HTML ```html <form> <label for="notes">Notes:</label> <input id="notes" name="my-form-control" type="text" /> <label for="start">Start date:</label> <input id="start" name="my-form-control" type="date" /> </form> <div id="output"></div> ``` ```css hidden div { margin: 1rem 0; } ``` #### JavaScript ```js const form = document.querySelector("form"); const items = form.elements.namedItem("my-form-control"); const output = document.querySelector("#output"); const itemIDs = Array.from(items) .map((item) => `"${item.id}"`) .join(", "); output.textContent = `My items: ${itemIDs}`; ``` #### Result {{EmbedLiveSample("Using namedItem()")}} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("HTMLCollection.namedItem")}} that it replaces
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/dommatrix/index.md
--- title: DOMMatrix (WebKitCSSMatrix) slug: Web/API/DOMMatrix page-type: web-api-interface browser-compat: api.DOMMatrix --- {{APIRef("Geometry Interfaces")}} The **`DOMMatrix`** interface represents 4×4 matrices, suitable for 2D and 3D operations including rotation and translation. It is a mutable version of the {{domxref("DOMMatrixReadOnly")}} interface. **`WebKitCSSMatrix`** and **`SVGMatrix`** are aliases to **`DOMMatrix`**. This interface should be available inside [web workers](/en-US/docs/Web/API/Web_Workers_API), though some implementations don't allow it yet. {{InheritanceDiagram}} ## Constructor - {{domxref("DOMMatrix.DOMMatrix","DOMMatrix()")}} - : Creates and returns a new `DOMMatrix` object. ## Instance properties _This interface inherits properties from {{domxref("DOMMatrixReadOnly")}}, though some of these properties are altered to be mutable._ - `is2D` {{ReadOnlyInline}} - : A Boolean flag whose value is `true` if the matrix was initialized as a 2D matrix. If `false`, the matrix is 3D. - `isIdentity` {{ReadOnlyInline}} - : A Boolean whose value is `true` if the matrix is the [identity matrix](https://en.wikipedia.org/wiki/Identity_matrix). The identity matrix is one in which every value is `0` _except_ those on the main diagonal from top-left to bottom-right corner (in other words, where the offsets in each direction are equal). - `m11`, `m12`, `m13`, `m14`, `m21`, `m22`, `m23`, `m24`, `m31`, `m32`, `m33`, `m34`, `m41`, `m42`, `m43`, `m44` - : Double-precision floating-point values representing each component of a 4×4 matrix, where `m11` through `m14` are the first column, `m21` through `m24` are the second column, and so forth. - `a`, `b`, `c`, `d`, `e`, `f` - : Double-precision floating-point values representing the components of a 4×4 matrix which are required in order to perform 2D rotations and translations. These are aliases for specific components of a 4×4 matrix, as shown below. | `2D` | `3D equivalent` | | ---- | --------------- | | `a` | `m11` | | `b` | `m12` | | `c` | `m21` | | `d` | `m22` | | `e` | `m41` | | `f` | `m42` | ## Instance methods _This interface includes the following methods, as well as the methods it inherits from {{domxref("DOMMatrixReadOnly")}}._ - {{domxref("DOMMatrix.invertSelf()")}} - : Modifies the matrix by inverting it. If the matrix can't be inverted, its components are all set to `NaN`, and {{domxref("DOMMatrix.is2D", "is2D")}} returns `false`. - {{domxref("DOMMatrix.multiplySelf()")}} - : Modifies the matrix by post-multiplying it with the specified `DOMMatrix`. This is equivalent to the dot product `A⋅B`, where matrix `A` is the source matrix and `B` is the matrix given as an input to the method. Returns itself. - {{domxref("DOMMatrix.preMultiplySelf()")}} - : Modifies the matrix by pre-multiplying it with the specified `DOMMatrix`. This is equivalent to the dot product `B⋅A`, where matrix `A` is the source matrix and `B` is the matrix given as an input to the method. Returns itself. - {{domxref("DOMMatrix.translateSelf()")}} - : Modifies the matrix by applying the specified vector. The default vector is `[0, 0, 0]`. Returns itself. - {{domxref("DOMMatrix.scaleNonUniformSelf()")}} {{deprecated_inline}} - : Modifies the matrix by applying the specified scaling on the X, Y, and Z axes, centered at the given origin. By default, the Y and Z axes' scaling factors are both `1`, but the scaling factor for X must be specified. The default origin is `(0, 0, 0)`. Returns itself. - {{domxref("DOMMatrix.scaleSelf()")}} - : Modifies the matrix by applying the specified scaling factors, with the center located at the specified origin. Also returns itself. By default, the scaling factor is `1` for all three axes, and the origin is `(0, 0, 0)`. Returns itself. - {{domxref("DOMMatrix.scale3dSelf()")}} - : Modifies the matrix by applying the specified scaling factor to all three axes, centered on the given origin. Returns itself. - {{domxref("DOMMatrix.rotateSelf()")}} - : Modifies the matrix by rotating itself around each axis by the specified number of degrees. Returns itself. - {{domxref("DOMMatrix.rotateAxisAngleSelf()")}} - : Modifies the matrix by rotating it by the specified angle around the given vector. Returns itself. - {{domxref("DOMMatrix.rotateFromVectorSelf()")}} - : Modifies the matrix by rotating it by the angle between the specified vector and `(1, 0)`. Returns itself. - {{domxref("DOMMatrix.setMatrixValue()")}} - : Replaces the contents of the matrix with the matrix described by the specified transform or transforms. Returns itself. - {{domxref("DOMMatrix.skewXSelf()")}} - : Modifies the matrix by applying the specified skew transformation along the X-axis. Returns itself. - {{domxref("DOMMatrix.skewYSelf()")}} - : Modifies the matrix by applying the specified skew transformation along the Y-axis. Returns itself. ## Static methods _This interface inherits methods from {{domxref("DOMMatrixReadOnly")}}._ - {{domxref("DOMMatrix.fromFloat32Array", "fromFloat32Array()")}} - : Creates a new mutable `DOMMatrix` object given an array of single-precision (32-bit) floating-point values. If the array has six values, the result is a 2D matrix; if the array has 16 values, the result is a 3D matrix. Otherwise, a {{jsxref("TypeError")}} exception is thrown. - {{domxref("DOMMatrix.fromFloat64Array", "fromFloat64Array()")}} - : Creates a new mutable `DOMMatrix` object given an array of double-precision (64-bit) floating-point values. If the array has six values, the result is a 2D matrix; if the array has 16 values, the result is a 3D matrix. Otherwise, a {{jsxref("TypeError")}} exception is thrown. - {{domxref("DOMMatrix.fromMatrix", "fromMatrix()")}} - : Creates a new mutable `DOMMatrix` object given an existing matrix or a {{domxref("DOMMatrixInit")}} dictionary which provides the values for its properties. ## Usage notes The matrix defined by the `DOMMatrix` interface is comprised of four rows of four columns each. While it's beyond the scope of this article to explain the mathematics involved, this 4×4 size is enough to describe any transformation you might apply to either 2D or 3D geometries. Here are the positions of the 16 elements (m_11 through m_44) which comprise the 4×4 abstract matrix: <math display="block"><semantics><mrow><mo>[</mo><mtable rowspacing="0.5ex"><mtr><mtd><msub><mi>m</mi><mn>11</mn></msub></mtd><mtd><msub><mi>m</mi><mn>21</mn></msub></mtd><mtd><msub><mi>m</mi><mn>31</mn></msub></mtd><mtd><msub><mi>m</mi><mn>41</mn></msub></mtd></mtr><mtr><mtd><msub><mi>m</mi><mn>12</mn></msub></mtd><mtd><msub><mi>m</mi><mn>22</mn></msub></mtd><mtd><msub><mi>m</mi><mn>32</mn></msub></mtd><mtd><msub><mi>m</mi><mn>42</mn></msub></mtd></mtr><mtr><mtd><msub><mi>m</mi><mn>13</mn></msub></mtd><mtd><msub><mi>m</mi><mn>23</mn></msub></mtd><mtd><msub><mi>m</mi><mn>33</mn></msub></mtd><mtd><msub><mi>m</mi><mn>43</mn></msub></mtd></mtr><mtr><mtd><msub><mi>m</mi><mn>14</mn></msub></mtd><mtd><msub><mi>m</mi><mn>24</mn></msub></mtd><mtd><msub><mi>m</mi><mn>34</mn></msub></mtd><mtd><msub><mi>m</mi><mn>44</mn></msub></mtd></mtr></mtable><mo>]</mo></mrow><annotation encoding="TeX">\left [ \begin{matrix} m_{11} &#x26; m_{21} &#x26; m_{31} &#x26; m_{41} \\ m_{12} &#x26; m_{22} &#x26; m_{32} &#x26; m_{42} \\ m_{13} &#x26; m_{23} &#x26; m_{33} &#x26; m_{43} \\ m_{14} &#x26; m_{24} &#x26; m_{34} &#x26; m_{44} \end{matrix} \right ]</annotation></semantics></math> The `DOMMatrix` interface is designed with the intent that it will be used for all matrices within markup. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - Its non-modifiable counterpart, {{domxref("DOMMatrixReadOnly")}}
0
data/mdn-content/files/en-us/web/api/dommatrix
data/mdn-content/files/en-us/web/api/dommatrix/dommatrix/index.md
--- title: "DOMMatrix: DOMMatrix() constructor" short-title: DOMMatrix() slug: Web/API/DOMMatrix/DOMMatrix page-type: web-api-constructor browser-compat: api.DOMMatrix.DOMMatrix --- {{APIRef("Geometry Interfaces")}} The **`DOMMatrix`** constructor creates a new {{domxref("DOMMatrix")}} object which represents 4x4 matrices, suitable for 2D and 3D operations. ## Syntax ```js-nolint new DOMMatrix() new DOMMatrix(init) ``` ### Parameters - `init` {{optional_inline}} - : An array of numbers specifying the matrix you want to create, or a CSS transform string. In case an array of numbers is passed, the behavior depends on the length of the array: - for a 6-element array of components in the form `[a, b, c, d, e, f]`, a 2D matrix is created, initialized with the provided components. - for a 16-element array of components (in the column-major order) in the form `[m11, m12, m13, …, m42, m43, m44]`, a 3D matrix is created, initialized with the provided components. ## Examples This example creates a DOMMatrix to use as an argument for calling {{domxref("Point.matrixTransform()")}}. ```js const point = new DOMPoint(5, 4); const scaleX = 2; const scaleY = 3; const translateX = 12; const translateY = 8; const angle = Math.PI / 2; const matrix = new DOMMatrix([ Math.cos(angle) * scaleX, Math.sin(angle) * scaleX, -Math.sin(angle) * scaleY, Math.cos(angle) * scaleY, translateX, translateY, ]); const transformedPoint = point.matrixTransform(matrix); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/midioutput/index.md
--- title: MIDIOutput slug: Web/API/MIDIOutput page-type: web-api-interface browser-compat: api.MIDIOutput --- {{securecontext_header}}{{APIRef("Web MIDI API")}} The **`MIDIOutput`** interface of the {{domxref('Web MIDI API','','',' ')}} provides methods to add messages to the queue of an output device, and to clear the queue of messages. {{InheritanceDiagram}} ## Instance properties _This interface doesn't implement any specific properties, but inherits properties from {{domxref("MIDIPort")}}._ ## Instance methods _This interface also inherits methods from {{domxref("MIDIPort")}}._ - {{domxref("MIDIoutput.send()")}} - : Queues a message to be sent to the MIDI port. - {{domxref("MIDIOutput.clear()")}} - : Clears any pending send data from the queue. ## Examples The following example sends a middle C immediately on MIDI channel 1. ```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); // sends the message. } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/midioutput
data/mdn-content/files/en-us/web/api/midioutput/send/index.md
--- title: "MIDIOutput: send() method" short-title: send() slug: Web/API/MIDIOutput/send page-type: web-api-instance-method browser-compat: api.MIDIOutput.send --- {{securecontext_header}}{{APIRef("Web MIDI API")}} The **`send()`** method of the {{domxref("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-nolint send(data) send(data, timestamp) ``` ### Parameters - `data` - : A sequence of one or more [valid MIDI messages](https://www.midi.org/midi-articles/about-midi-part-3-midi-messages). Each entry represents a single byte of data. - `timestamp` {{optional_inline}} - : A {{domxref("DOMHighResTimestamp")}} with the time in milliseconds when the message should be sent (relative to {{domxref("Performance.timeOrigin")}}). ### Return value None ({{jsxref("undefined")}}). ### Exceptions - {{jsxref("TypeError")}} - : Thrown if `data` is not a valid sequence, or does not contain a valid MIDI message. - `InvalidAccessError` {{domxref("DOMException")}} - : Thrown if `data` is a system exclusive message, and the {{domxref("MIDIAccess")}} did not enable exclusive access. - `InvalidStateError` {{domxref("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 {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/midioutput
data/mdn-content/files/en-us/web/api/midioutput/clear/index.md
--- title: "MIDIOutput: clear() method" short-title: clear() slug: Web/API/MIDIOutput/clear page-type: web-api-instance-method browser-compat: api.MIDIOutput.clear --- {{securecontext_header}}{{APIRef("Web MIDI API")}} The **`clear()`** method of the {{domxref("MIDIOutput")}} interface clears the queue of messages being sent to the output device. ## Syntax ```js-nolint clear() ``` ### Parameters None. ### Return value None ({{jsxref("undefined")}}). ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/webgl_compressed_texture_pvrtc/index.md
--- title: WEBGL_compressed_texture_pvrtc extension short-title: WEBGL_compressed_texture_pvrtc slug: Web/API/WEBGL_compressed_texture_pvrtc page-type: webgl-extension browser-compat: api.WEBGL_compressed_texture_pvrtc --- {{APIRef("WebGL")}} The **`WEBGL_compressed_texture_pvrtc`** extension is part of the [WebGL API](/en-US/docs/Web/API/WebGL_API) and exposes four [PVRTC compressed texture formats](https://en.wikipedia.org/wiki/PVRTC). Compressed textures reduce the amount of memory needed to store a texture on the GPU, allowing for higher resolution textures or more of the same resolution textures. 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). > **Note:** PVRTC is typically only available on mobile devices with PowerVR chipsets. > It is used in all generations of the iPhone, iPod Touch and iPad and supported on certain Android devices that use a PowerVR GPU. > > This extension is available to both, {{domxref("WebGLRenderingContext", "WebGL1", "", 1)}} and {{domxref("WebGL2RenderingContext", "WebGL2", "", 1)}} contexts. > **Note:** On iOS devices, this extension is named `WEBKIT_WEBGL_compressed_texture_pvrtc`. ## Constants The compressed texture formats are exposed by four constants and can be used in two functions: {{domxref("WebGLRenderingContext.compressedTexImage2D", "compressedTexImage2D()")}} (where the `height` and `width` parameters must be powers of 2) and {{domxref("WebGLRenderingContext.compressedTexSubImage2D", "compressedTexSubImage2D()")}} (where the height and width parameters must equal the current values of the existing texture and the `xoffset` and `yoffset` parameters must be 0). - `ext.COMPRESSED_RGB_PVRTC_4BPPV1_IMG` - : RGB compression in 4-bit mode. One block for each 4×4 pixels. - `ext.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG` - : RGBA compression in 4-bit mode. One block for each 4×4 pixels. - `ext.COMPRESSED_RGB_PVRTC_2BPPV1_IMG` - : RGB compression in 2-bit mode. One block for each 8×4 pixels. - `ext.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG` - : RGBA compression in 2-bit mode. One block for each 8×4 pixels. ## Examples ```js const ext = gl.getExtension("WEBGL_compressed_texture_pvrtc"); const texture = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, texture); gl.compressedTexImage2D( gl.TEXTURE_2D, 0, ext.COMPRESSED_RGB_PVRTC_4BPPV1_IMG, 512, 512, 0, textureData, ); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [PVRTC Texture Compression – Wikipedia](https://en.wikipedia.org/wiki/PVRTC) - {{domxref("WebGLRenderingContext.getExtension()")}} - {{domxref("WebGLRenderingContext.compressedTexImage2D()")}} - {{domxref("WebGLRenderingContext.compressedTexSubImage2D()")}} - {{domxref("WebGLRenderingContext.getParameter()")}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/highlight/index.md
--- title: Highlight slug: Web/API/Highlight page-type: web-api-interface browser-compat: api.Highlight --- {{APIRef("CSS Custom Highlight API")}} The **`Highlight`** interface of the [CSS Custom Highlight API](/en-US/docs/Web/API/CSS_Custom_Highlight_API) is used to represent a collection of {{domxref("Range")}} instances to be styled using the API. To style arbitrary ranges in a page, instantiate a new `Highlight` object, add one or more `Range` objects to it, and register it using the {{domxref("HighlightRegistry")}}. A `Highlight` instance is a [`Set`-like object](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set#set-like_browser_apis) that can hold one or more `Range` objects. {{InheritanceDiagram}} ## Constructor - {{domxref("Highlight.Highlight()", "Highlight()")}} - : Returns a newly created `Highlight` object. ## Instance properties _The `Highlight` interface doesn't inherit any properties._ - {{domxref("Highlight.priority")}} - : A number that indicates the priority of this `Highlight` object. When multiple highlights overlap, the browser uses this priority to decide how to style the overlapping parts. - {{domxref("Highlight.size")}} {{ReadOnlyInline}} - : Returns the number of ranges in the `Highlight` object. - {{domxref("Highlight.type")}} - : An enumerated {{jsxref("String")}} used to specify the semantic meaning of the highlight. This allows assistive technologies to include this meaning when exposing the highlight to users. ## Instance methods _The `Highlight` interface doesn't inherit any methods_. - {{domxref("Highlight.add()")}} - : Add a new range to this highlight. - {{domxref("Highlight.clear()")}} - : Remove all ranges from this highlight. - {{domxref("Highlight.delete()")}} - : Remove a range from this highlight. - {{domxref("Highlight.entries()")}} - : Returns a new iterator object that contains each range in the highlight object, in insertion order. - {{domxref("Highlight.forEach()")}} - : Calls the given callback once for each range in the highlight object, in insertion order. - {{domxref("Highlight.has()")}} - : Returns a boolean asserting whether a range is present the highlight object or not. - {{domxref("Highlight.keys()")}} - : An alias for {{domxref("Highlight.values()")}}. - {{domxref("Highlight.values()")}} - : Returns a new iterator object that yields the ranges in the highlight object in insertion order. ## Examples The following example demonstrates how to create ranges, instantiate a new `Highlight` object for them, and register it to be styled on the page: ```js const parentNode = document.getElementById("foo"); // Create a couple of ranges. const range1 = new Range(); range1.setStart(parentNode, 10); range1.setEnd(parentNode, 20); const range2 = new Range(); range2.setStart(parentNode, 40); range2.setEnd(parentNode, 60); // Create a custom highlight for these ranges. const highlight = new Highlight(range1, range2); // Register the ranges in the HighlightRegistry. CSS.highlights.set("my-custom-highlight", highlight); ``` The following CSS code snippet demonstrates how to style the registered custom highlight by using the {{cssxref("::highlight")}} pseudo-element: ```css ::highlight(my-custom-highlight) { background-color: peachpuff; } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("css_custom_highlight_api", "The CSS Custom Highlight API", "", "nocode")}} - [CSS Custom Highlight API: The Future of Highlighting Text Ranges on the Web](https://css-tricks.com/css-custom-highlight-api-early-look/)
0
data/mdn-content/files/en-us/web/api/highlight
data/mdn-content/files/en-us/web/api/highlight/add/index.md
--- title: "Highlight: add() method" short-title: add() slug: Web/API/Highlight/add page-type: web-api-instance-method browser-compat: api.Highlight.add spec-urls: https://tc39.es/ecma262/multipage/keyed-collections.html#sec-set.prototype.add --- {{APIRef("CSS Custom Highlight API")}} The **`add()`** method of the {{domxref("Highlight")}} interface adds a new {{domxref("Range")}} object to a highlight, to be styled using the {{domxref("css_custom_highlight_api", "CSS Custom Highlight API", "", "nocode")}}. `Highlight` is a {{jsxref("Set")}}-like object, so this is similar to using {{jsxref("Set.add()")}}. ## Syntax ```js-nolint add(range) ``` ### Parameters - `range` - : A {{domxref("Range")}} object to add to the `Highlight`. ### Return value The `Highlight` object, with the added range. ## Examples The code snippet below shows how to add two ranges to a new highlight object: ```js const highlight = new Highlight(); const range1 = new Range(); const range2 = new Range(); highlight.add(range1).add(range2); console.log(highlight.size); // 2 ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("css_custom_highlight_api", "The CSS Custom Highlight API", "", "nocode")}} - [CSS Custom Highlight API: The Future of Highlighting Text Ranges on the Web](https://css-tricks.com/css-custom-highlight-api-early-look/)
0
data/mdn-content/files/en-us/web/api/highlight
data/mdn-content/files/en-us/web/api/highlight/has/index.md
--- title: "Highlight: has() method" short-title: has() slug: Web/API/Highlight/has page-type: web-api-instance-method browser-compat: api.Highlight.has spec-urls: https://tc39.es/ecma262/multipage/keyed-collections.html#sec-set.prototype.has --- {{APIRef("CSS Custom Highlight API")}} The **`has()`** method of the {{domxref("Highlight")}} interface returns a boolean indicating whether a {{domxref("Range")}} object exists in a `Highlight` object or not. `Highlight` is a {{jsxref("Set")}}-like object, so this is similar to using {{jsxref("Set.has()")}}. ## Syntax ```js-nolint has(range) ``` ### Parameters - `range` - : The `Range` object to test for presence in the `Highlight` object. ### Return value Returns `true` if the specified range exists in the `Highlight` object; otherwise `false`. ## Examples The code snippet below creates two ranges, and a highlight object that contains one of them. The code then uses the `has()` method to check whether each range exists in the highlight: ```js const range1 = new Range(); const range2 = new Range(); const myHighlight = new Highlight(range1); myHighlight.has(range1); // true myHighlight.has(range2); // false ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("css_custom_highlight_api", "The CSS Custom Highlight API", "", "nocode")}} - [CSS Custom Highlight API: The Future of Highlighting Text Ranges on the Web](https://css-tricks.com/css-custom-highlight-api-early-look/)
0
data/mdn-content/files/en-us/web/api/highlight
data/mdn-content/files/en-us/web/api/highlight/keys/index.md
--- title: "Highlight: keys() method" short-title: keys() slug: Web/API/Highlight/keys page-type: web-api-instance-method browser-compat: api.Highlight.keys spec-urls: https://tc39.es/ecma262/multipage/keyed-collections.html#sec-set.prototype.keys --- {{APIRef("CSS Custom Highlight API")}} The **`keys()`** method of the {{domxref("Highlight")}} interface is an alias for the {{domxref("Highlight.values()", "values()")}} method. `Highlight` is a {{jsxref("Set")}}-like object, so this is similar to using {{jsxref("Set.keys()")}}. ## Syntax ```js-nolint keys() ``` ### Return value A new iterator object containing each `Range` object in the given `Highlight`, in insertion order. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("css_custom_highlight_api", "The CSS Custom Highlight API", "", "nocode")}} - [CSS Custom Highlight API: The Future of Highlighting Text Ranges on the Web](https://css-tricks.com/css-custom-highlight-api-early-look/)
0
data/mdn-content/files/en-us/web/api/highlight
data/mdn-content/files/en-us/web/api/highlight/clear/index.md
--- title: "Highlight: clear() method" short-title: clear() slug: Web/API/Highlight/clear page-type: web-api-instance-method browser-compat: api.Highlight.clear spec-urls: https://tc39.es/ecma262/multipage/keyed-collections.html#sec-set.prototype.clear --- {{APIRef("CSS Custom Highlight API")}} The **`clear()`** method of the {{domxref("Highlight")}} interface removes all the {{domxref("Range")}} objects from a `Highlight` object. `Highlight` is a {{jsxref("Set")}}-like object, so this is similar to using {{jsxref("Set.clear()")}}. ## Syntax ```js-nolint clear() ``` ### Return value None ({{jsxref("undefined")}}). ## Examples The code snippet below shows how to create a new highlight with two ranges, and then clear it: ```js const highlight = new Highlight(range1, range2); console.log(highlight.size); // 2 highlight.clear(); console.log(highlight.size); // 0 ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("css_custom_highlight_api", "The CSS Custom Highlight API", "", "nocode")}} - [CSS Custom Highlight API: The Future of Highlighting Text Ranges on the Web](https://css-tricks.com/css-custom-highlight-api-early-look/)
0
data/mdn-content/files/en-us/web/api/highlight
data/mdn-content/files/en-us/web/api/highlight/size/index.md
--- title: "Highlight: size property" short-title: size slug: Web/API/Highlight/size page-type: web-api-instance-property browser-compat: api.Highlight.size spec-urls: https://tc39.es/ecma262/multipage/keyed-collections.html#sec-get-set.prototype.size --- {{APIRef("CSS Custom Highlight API")}} The **`size`** property returns the number of {{domxref("Range")}} objects in a {{domxref("Highlight")}} object. ## Value The value of `size` is a read-only integer representing how many entries the highlight object has. ## Examples ### Using size ```js const highlight = new Highlight(); highlight.add(range1); highlight.add(range2); highlight.add(range3); console.log(highlight.size); // 3 ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("css_custom_highlight_api", "The CSS Custom Highlight API", "", "nocode")}} - [CSS Custom Highlight API: The Future of Highlighting Text Ranges on the Web](https://css-tricks.com/css-custom-highlight-api-early-look/)
0
data/mdn-content/files/en-us/web/api/highlight
data/mdn-content/files/en-us/web/api/highlight/values/index.md
--- title: "Highlight: values() method" short-title: values() slug: Web/API/Highlight/values page-type: web-api-instance-method browser-compat: api.Highlight.values spec-urls: https://tc39.es/ecma262/multipage/keyed-collections.html#sec-set.prototype.values --- {{APIRef("CSS Custom Highlight API")}} The **`values()`** method of the {{domxref("Highlight")}} interface returns a new [Iterator](/en-US/docs/Web/JavaScript/Guide/Iterators_and_generators) object that contains the values for each `Range` object in the `Highlight` object in insertion order. > **Note:** The **`keys()`** method is an alias for this method. It behaves exactly the same and returns **values** of `Highlight` elements. `Highlight` is a {{jsxref("Set")}}-like object, so this is similar to using {{jsxref("Set.values()")}}. ## Syntax ```js-nolint values() ``` ### Return value A new iterator object containing each `Range` object in the given `Highlight`, in insertion order. ## Examples The following code snippet shows how to create a new `Highlight` object with three `Range` objects, and use the iterator returned by the `values()` method to log the three ranges: ```js const myHighlight = new Highlight(); myHighlight.add(new Range()); myHighlight.add(new Range()); myHighlight.add(new Range()); const iter = myHighlight.values(); for (value of iter) { console.log(value); // Range } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("css_custom_highlight_api", "The CSS Custom Highlight API", "", "nocode")}} - [CSS Custom Highlight API: The Future of Highlighting Text Ranges on the Web](https://css-tricks.com/css-custom-highlight-api-early-look/)
0
data/mdn-content/files/en-us/web/api/highlight
data/mdn-content/files/en-us/web/api/highlight/delete/index.md
--- title: "Highlight: delete() method" short-title: delete() slug: Web/API/Highlight/delete page-type: web-api-instance-method browser-compat: api.Highlight.delete spec-urls: https://tc39.es/ecma262/multipage/keyed-collections.html#sec-set.prototype.delete --- {{APIRef("CSS Custom Highlight API")}} The **`delete()`** method of the {{domxref("Highlight")}} interface removes a specified {{domxref("Range")}} object from a `Highlight` object. `Highlight` is a {{jsxref("Set")}}-like object, so this is similar to using {{jsxref("Set.delete()")}}. ## Syntax ```js-nolint delete(range) ``` ### Parameters - `range` - : The {{domxref("Range")}} object to remove from the `Highlight`. ### Return value Returns `true` if `range` was already in `Highlight`; otherwise `false`. ## Examples The code snippet below shows how to create a new highlight with two ranges, and then delete one of them: ```js const range1 = new Range(); const range2 = new Range(); const highlight = new Highlight(range1, range2); console.log(highlight.size); // 2 highlight.delete(range1); console.log(highlight.size); // 1 ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("css_custom_highlight_api", "The CSS Custom Highlight API", "", "nocode")}} - [CSS Custom Highlight API: The Future of Highlighting Text Ranges on the Web](https://css-tricks.com/css-custom-highlight-api-early-look/)
0
data/mdn-content/files/en-us/web/api/highlight
data/mdn-content/files/en-us/web/api/highlight/type/index.md
--- title: "Highlight: type property" short-title: type slug: Web/API/Highlight/type page-type: web-api-instance-property browser-compat: api.Highlight.type --- {{APIRef("CSS Custom Highlight API")}} The `type` property of the {{domxref("Highlight")}} interface is an enumerated {{jsxref("String")}} used to specify the meaning of the highlight. This allows assistive technologies, such as screen readers, to include this meaning when exposing the highlight to users. By default, a highlight object will have its type set to `highlight`, but you can change it to `spelling-error` or `grammar-error`. ## Value The possible values of the `type` enumerated value are: - `highlight` - : This is the default highlight type. It does not have any specific meaning. - `spelling-error` - : Use this type when the highlight is used to emphasize misspelled content. - `grammar-error` - : Use this type when the highlight is used to emphasize content that is grammatically incorrect. ## Examples ```js const spellErrorRange = new Range(); spellErrorRange.setStart(textNode, 10); spellErrorRange.setEnd(textNode, 20); const spellErrorsHighlight = new Highlight(spellErrorRange); spellErrorsHighlight.type = "spelling-error"; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("css_custom_highlight_api", "The CSS Custom Highlight API", "", "nocode")}} - [CSS Custom Highlight API: The Future of Highlighting Text Ranges on the Web](https://css-tricks.com/css-custom-highlight-api-early-look/)
0
data/mdn-content/files/en-us/web/api/highlight
data/mdn-content/files/en-us/web/api/highlight/priority/index.md
--- title: "Highlight: priority property" short-title: priority slug: Web/API/Highlight/priority page-type: web-api-instance-property browser-compat: api.Highlight.priority --- {{APIRef("CSS Custom Highlight API")}} It is possible to create {{domxref("Range")}} objects that overlap in a document. When overlapping ranges are used by multiple different {{domxref("Highlight")}} objects, and when those highlights are styled using {{cssxref("::highlight")}} pseudo-elements, this may lead to conflicting styles. If two text ranges overlap and are both highlighted using the {{domxref("css_custom_highlight_api", "CSS Custom Highlight API", "", "nocode")}}, and if they're both styled using the `color` CSS property, the browser needs to decide which color should be used for styling the text in the overlapping part. By default, all highlights have the same priority and the browser chooses the most recently registered highlight to style the overlapping parts. The `priority` property of the {{domxref("Highlight")}} interface is a {{jsxref("Number")}} used to change this default behavior and determine which highlight's styles should be used to resolve style conflicts in overlapping parts. Note that all the styles of a highlight are applied and the browser only needs to resolve conflicts when the same CSS properties are used by multiple overlapping highlights. The highlight style conflict resolution also does not depend on the order in which the {{cssxref("::highlight")}} pseudo-elements rules appear in the source, or whether or not CSS properties are marked as `!important`. ## Value An integer. ## Examples ### Default priority #### HTML ```html <p>Time is an illusion. Lunchtime doubly so.</p> ``` #### CSS ```css ::highlight(highlight-2) { color: blue; } ::highlight(highlight-1) { color: white; background: orange; } ``` #### JavaScript ```js const text = document.querySelector("p").firstChild; // Create two overlapping highlights const range1 = new Range(); range1.setStart(text, 5); range1.setEnd(text, 25); const range2 = new Range(); range2.setStart(text, 15); range2.setEnd(text, 35); const highlight1 = new Highlight(range1); const highlight2 = new Highlight(range2); CSS.highlights.set("highlight-1", highlight1); CSS.highlights.set("highlight-2", highlight2); ``` #### Result As seen below, by default, the part of the text node where the two registered highlights overlap is displayed in blue because `highlight-2` is registered after `highlight-1`. The background color defined by `highlight-1` includes the entire `range1` range because it does not conflict with another background color. {{EmbedLiveSample("Default priority")}} ### Setting priority #### HTML ```html <button id="prioritize-1" type="button">Prioritize 1</button> <button id="prioritize-2" type="button">Prioritize 2</button> <button id="reset" type="button">Reset</button> <p>Time is an illusion. Lunchtime doubly so.</p> ``` #### CSS ```css ::highlight(highlight-1) { background-color: blue; color: white; } ::highlight(highlight-2) { background-color: orange; } ``` #### JavaScript ```js const text = document.querySelector("p").firstChild; // Create two overlapping highlights const range1 = new Range(); range1.setStart(text, 5); range1.setEnd(text, 25); const range2 = new Range(); range2.setStart(text, 15); range2.setEnd(text, 35); const highlight1 = new Highlight(range1); const highlight2 = new Highlight(range2); CSS.highlights.set("highlight-1", highlight1); CSS.highlights.set("highlight-2", highlight2); // Add buttons to change the highlight priority. const prioritize1 = document.querySelector("#prioritize-1"); const prioritize2 = document.querySelector("#prioritize-2"); const reset = document.querySelector("#reset"); prioritize1.addEventListener("click", () => { highlight1.priority = 1; highlight2.priority = 0; }); prioritize2.addEventListener("click", () => { highlight1.priority = 0; highlight2.priority = 1; }); reset.addEventListener("click", () => { highlight1.priority = 0; highlight2.priority = 0; }); ``` #### Result As seen below, by default, the part of the text node where the two registered highlights overlap is displayed in blue because `highlight-2` is registered after `highlight-1`. {{EmbedLiveSample("Setting priority")}} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("css_custom_highlight_api", "The CSS Custom Highlight API", "", "nocode")}} - [CSS Custom Highlight API: The Future of Highlighting Text Ranges on the Web](https://css-tricks.com/css-custom-highlight-api-early-look/)
0
data/mdn-content/files/en-us/web/api/highlight
data/mdn-content/files/en-us/web/api/highlight/highlight/index.md
--- title: "Highlight: Highlight() constructor" short-title: Highlight() slug: Web/API/Highlight/Highlight page-type: web-api-constructor browser-compat: api.Highlight.Highlight --- {{APIRef("CSS Custom Highlight API")}} The **`Highlight()`** constructor returns a newly created {{domxref("Highlight")}} object which can hold a collection of {{domxref("Range")}} objects to be styled using the {{domxref("css_custom_highlight_api", "CSS Custom Highlight API", "", "nocode")}}. ## Syntax ```js-nolint new Highlight() new Highlight(range) new Highlight(range1, range2, /* …, */ rangeN) ``` ### Parameters - `range1, /* …, */ rangeN` {{optional_inline}} - : One ore more initial {{domxref("Range")}} objects to add in the new highlight. ### Return value A new `Highlight` object. ## Examples The example code below demonstrates how to create an empty highlight object, and then add ranges to it: ```js const highlight = new Highlight(); highlight.add(range1); highlight.add(range2); ``` The example code below demonstrates how to create a new highlight object and add ranges to it during instantiation: ```js const highlight = new Highlight(range1, range2); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("css_custom_highlight_api", "The CSS Custom Highlight API", "", "nocode")}} - [CSS Custom Highlight API: The Future of Highlighting Text Ranges on the Web](https://css-tricks.com/css-custom-highlight-api-early-look/)
0
data/mdn-content/files/en-us/web/api/highlight
data/mdn-content/files/en-us/web/api/highlight/foreach/index.md
--- title: "Highlight: forEach() method" short-title: forEach() slug: Web/API/Highlight/forEach page-type: web-api-instance-method browser-compat: api.Highlight.forEach spec-urls: https://tc39.es/ecma262/multipage/keyed-collections.html#sec-set.prototype.foreach --- {{APIRef("CSS Custom Highlight API")}} The **`forEach()`** method of the {{domxref("Highlight")}} interface executes a provided function once for each {{domxref("Range")}} object in the `Highlight` object, in insertion order. `Highlight` is a {{jsxref("Set")}}-like object, so this is similar to using {{jsxref("Set.forEach()")}}. ## Syntax ```js-nolint forEach(callbackFn) forEach(callbackFn, thisArg) ``` ### Parameters - `callback` - : Function to execute for each `Range` object, taking three arguments: - `range`, `key` - : The current `Range` object being processed in the `Highlight`. As there are no keys in `Highlight`, the `range` is passed for both arguments. - `highlight` - : The `Highlight` object which `forEach()` was called upon. - `thisArg` - : Value to use as `this` when executing `callbackFn`. ### Return value None ({{jsxref("undefined")}}). ## Examples The code snippet below shows how create a new highlight with two ranges, and then log the ranges by using the `forEach()` method: ```js function logRanges(range, key, highlight) { console.log(`Highlight object ${highlight} contains range ${range}`); } const text = new Text("Time is an illusion. Lunchtime doubly so."); const range1 = document.createRange(); range1.setStart(text, 0); range1.setEnd(text, 4); const range2 = document.createRange(); range2.setStart(text, 21); range2.setEnd(text, 30); const myHighlight = new Highlight(); myHighlight.add(range1); myHighlight.add(range2); myHighlight.forEach(logRanges); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("css_custom_highlight_api", "The CSS Custom Highlight API", "", "nocode")}} - [CSS Custom Highlight API: The Future of Highlighting Text Ranges on the Web](https://css-tricks.com/css-custom-highlight-api-early-look/)
0
data/mdn-content/files/en-us/web/api/highlight
data/mdn-content/files/en-us/web/api/highlight/entries/index.md
--- title: "Highlight: entries() method" short-title: entries() slug: Web/API/Highlight/entries page-type: web-api-instance-method browser-compat: api.Highlight.entries spec-urls: https://tc39.es/ecma262/multipage/keyed-collections.html#sec-set.prototype.entries --- {{APIRef("CSS Custom Highlight API")}} The **`entries()`** method of the {{domxref("Highlight")}} interface returns a new [Iterator](/en-US/docs/Web/JavaScript/Guide/Iterators_and_generators) object that contains an array of `[range, range]` for each {{domxref("Range")}} object in the `Highlight` object, in insertion order. `Highlight` is a {{jsxref("Set")}}-like object, so this is similar to using {{jsxref("Set.entries()")}}. ## Syntax ```js-nolint entries() ``` ### Return value A new iterator object that contains an array of `[range, range]` for each `Range` object in the given `Highlight`, in insertion order. ## Examples The code snippet below shows how create a new highlight with two ranges, and then log the ranges by using the iterator returned by the `entries()` method: ```js const text = new Text("Time is an illusion. Lunchtime doubly so."); const range1 = document.createRange(); range1.setStart(text, 0); range1.setEnd(text, 4); const range2 = document.createRange(); range2.setStart(text, 21); range2.setEnd(text, 30); const myHighlight = new Highlight(); myHighlight.add(range1); myHighlight.add(range2); const iter = myHighlight.entries(); console.log(iter.next().value); // [Range, Range] console.log(iter.next().value); // [Range, Range] ``` The following code example shows how to iterate over the ranges in a highlight by using a [`for...of`](/en-US/docs/Web/JavaScript/Reference/Statements/for...of) loop: ```js const text = new Text("Time is an illusion. Lunchtime doubly so."); const range1 = document.createRange(); range1.setStart(text, 0); range1.setEnd(text, 4); const range2 = document.createRange(); range2.setStart(text, 21); range2.setEnd(text, 30); const highlight = new Highlight(); highlight.add(range1); highlight.add(range2); for (const [range] of highlight.entries()) { console.log(range.toString()); // Time // Lunchtime } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("css_custom_highlight_api", "The CSS Custom Highlight API", "", "nocode")}} - [CSS Custom Highlight API: The Future of Highlighting Text Ranges on the Web](https://css-tricks.com/css-custom-highlight-api-early-look/)
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/vrdisplay/index.md
--- title: VRDisplay slug: Web/API/VRDisplay page-type: web-api-interface status: - deprecated - non-standard browser-compat: api.VRDisplay --- {{APIRef("WebVR API")}}{{Deprecated_Header}}{{Non-standard_Header}} The **`VRDisplay`** interface of the [WebVR API](/en-US/docs/Web/API/WebVR_API) represents any VR device supported by this API. It includes generic information such as device IDs and descriptions, as well as methods for starting to present a VR scene, retrieving eye parameters and display capabilities, and other important functionality. > **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/). An array of all connected VR Devices can be returned by invoking the {{domxref("Navigator.getVRDisplays()")}} method. ## Instance properties - {{domxref("VRDisplay.capabilities")}} {{ReadOnlyInline}} {{Deprecated_Inline}} {{Non-standard_Inline}} - : Returns a {{domxref("VRDisplayCapabilities")}} object that indicates the various capabilities of the `VRDisplay`. - {{domxref("VRDisplay.depthFar")}} {{Deprecated_Inline}} {{Non-standard_Inline}} - : Gets and sets the z-depth defining the far plane of the [eye view frustum](https://en.wikipedia.org/wiki/Viewing_frustum), i.e. the furthest viewable boundary of the scene. - {{domxref("VRDisplay.depthNear")}} {{Deprecated_Inline}} {{Non-standard_Inline}} - : Gets and sets the z-depth defining the near plane of the [eye view frustum](https://en.wikipedia.org/wiki/Viewing_frustum), i.e. the nearest viewable boundary of the scene. - {{domxref("VRDisplay.displayId")}} {{ReadOnlyInline}} {{Deprecated_Inline}} {{Non-standard_Inline}} - : Returns an identifier for this particular VRDisplay, which is also used as an association point in the [Gamepad API](/en-US/docs/Web/API/Gamepad_API) (see {{domxref("Gamepad.displayId")}}). - {{domxref("VRDisplay.displayName")}} {{ReadOnlyInline}} {{Deprecated_Inline}} {{Non-standard_Inline}} - : Returns a human-readable name to identify the `VRDisplay`. - {{domxref("VRDisplay.isConnected")}} {{ReadOnlyInline}} {{Deprecated_Inline}} {{Non-standard_Inline}} - : Returns a boolean value indicating whether the `VRDisplay` is connected to the computer. - {{domxref("VRDisplay.isPresenting")}} {{ReadOnlyInline}} {{Deprecated_Inline}} {{Non-standard_Inline}} - : Returns a boolean value indicating whether the `VRDisplay` is currently having content presented through it. - {{domxref("VRDisplay.stageParameters")}} {{ReadOnlyInline}} {{Deprecated_Inline}} {{Non-standard_Inline}} - : Returns a {{domxref("VRStageParameters")}} object containing room-scale parameters, if the `VRDisplay` is capable of supporting room-scale experiences. ## Instance methods - {{domxref("VRDisplay.getEyeParameters()")}} {{Deprecated_Inline}} {{Non-standard_Inline}} - : Returns the {{domxref("VREyeParameters")}} object containing the eye parameters for the specified eye. - {{domxref("VRDisplay.getFrameData()")}} {{Deprecated_Inline}} {{Non-standard_Inline}} - : Accepts a {{domxref("VRFrameData")}} object and populates it with the information required to render the current frame. - {{domxref("VRDisplay.getImmediatePose()")}} {{Deprecated_Inline}} {{Non-standard_Inline}} - : Returns a {{domxref("VRPose")}} object defining the current pose of the `VRDisplay`, with no prediction applied. This is no longer needed, and has been removed from the spec. - {{domxref("VRDisplay.getLayers()")}} {{Deprecated_Inline}} {{Non-standard_Inline}} - : Returns the layers currently being presented by the `VRDisplay`. - {{domxref("VRDisplay.getPose()")}} {{Deprecated_Inline}} {{Non-standard_Inline}} - : Returns a {{domxref("VRPose")}} object defining the future predicted pose of the `VRDisplay` as it will be when the current frame is actually presented. **This method is deprecated — instead, you should use {{domxref("VRDisplay.getFrameData()")}}, which also provides a {{domxref("VRPose")}} object.** - {{domxref("VRDisplay.resetPose()")}} {{Deprecated_Inline}} {{Non-standard_Inline}} - : Resets the pose for this `VRDisplay`, treating its current {{domxref("VRPose.position")}} and {{domxref("VRPose.orientation")}} as the "origin/zero" values. - {{domxref("VRDisplay.cancelAnimationFrame()")}} {{Deprecated_Inline}} {{Non-standard_Inline}} - : A special implementation of {{domxref("Window.cancelAnimationFrame")}} that allows callbacks registered with {{domxref("VRDisplay.requestAnimationFrame()")}} to be unregistered. - {{domxref("VRDisplay.requestAnimationFrame()")}} {{Deprecated_Inline}} {{Non-standard_Inline}} - : A special implementation of {{domxref("Window.requestAnimationFrame")}} containing a callback function that will be called every time a new frame of the `VRDisplay` presentation is rendered. - {{domxref("VRDisplay.requestPresent()")}} {{Deprecated_Inline}} {{Non-standard_Inline}} - : Starts the `VRDisplay` presenting a scene. - {{domxref("VRDisplay.exitPresent()")}} {{Deprecated_Inline}} {{Non-standard_Inline}} - : Stops the `VRDisplay` presenting a scene. - {{domxref("VRDisplay.submitFrame()")}} {{Deprecated_Inline}} {{Non-standard_Inline}} - : Captures the current state of the {{domxref("VRLayerInit")}} currently being presented and displays it on the `VRDisplay`. ## Examples ```js if (navigator.getVRDisplays) { console.log("WebVR 1.1 supported"); // Then get the displays attached to the computer navigator.getVRDisplays().then((displays) => { // If a display is available, use it to present the scene if (displays.length > 0) { vrDisplay = displays[0]; // Now we have our VRDisplay object and can do what we want with it } }); } ``` > **Note:** You can see this complete code at [raw-webgl-example](https://github.com/mdn/webvr-tests/blob/main/webvr/raw-webgl-example/webgl-demo.js). ## Specifications This interface was part of the old [WebVR API](https://immersive-web.github.io/webvr/spec/1.1/#interface-vrdisplay) 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/vrdisplay
data/mdn-content/files/en-us/web/api/vrdisplay/isconnected/index.md
--- title: "VRDisplay: isConnected property" short-title: isConnected slug: Web/API/VRDisplay/isConnected page-type: web-api-instance-property status: - deprecated - non-standard browser-compat: api.VRDisplay.isConnected --- {{APIRef("WebVR API")}}{{Deprecated_Header}}{{Non-standard_Header}} The **`isConnected`** read-only property of the {{domxref("VRDisplay")}} interface returns a boolean value indicating whether the `VRDisplay` is connected to the computer. > **Note:** This property was part of the old [WebVR API](https://immersive-web.github.io/webvr/spec/1.1/). It has been superseded by the [WebXR Device API](https://immersive-web.github.io/webxr/). ## Value A boolean value; `true` means the display is connected; `false` means it isn't. ## Examples ```js navigator.getVRDisplays().then((displays) => { // If a display is available, use it to present the scene if (displays.length > 0) { vrDisplay = displays[0]; // Starting the presentation when the button is clicked: It can only be called in response to a user gesture btn.addEventListener("click", () => { // Only request presentation if the display is still connected. if (vrDisplay.isConnected) { vrDisplay.requestPresent([{ source: canvas }]).then(() => { // start rendering the app, etc. }); } else { console.log("Connection to display lost"); } }); } }); ``` ## Specifications This property was part of the old [WebVR API](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/vrdisplay
data/mdn-content/files/en-us/web/api/vrdisplay/submitframe/index.md
--- title: "VRDisplay: submitFrame() method" short-title: submitFrame() slug: Web/API/VRDisplay/submitFrame page-type: web-api-instance-method status: - deprecated - non-standard browser-compat: api.VRDisplay.submitFrame --- {{APIRef("WebVR API")}}{{Deprecated_Header}}{{Non-standard_Header}} The **`submitFrame()`** method of the {{domxref("VRDisplay")}} interface captures the current state of the {{domxref("VRLayerInit")}} currently being presented and displays it on the `VRDisplay`. > **Note:** This method 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 frame should subsequently be rendered using the {{domxref("VRPose")}} and matrices provided by the last call to {{domxref("VRDisplay.getFrameData()", "getFrameData()")}}. ## Syntax ```js-nolint submitFrame() ``` ### Parameters None. ### Return value None ({{jsxref("undefined")}}). ## Examples ```js const frameData = new VRFrameData(); let vrDisplay; navigator.getVRDisplays().then((displays) => { vrDisplay = displays[0]; console.log("Display found"); // Starting the presentation when the button is clicked: It can only be called in response to a user gesture btn.addEventListener("click", () => { vrDisplay.requestPresent([{ source: canvas }]).then(() => { drawVRScene(); }); }); }); // WebVR: Draw the scene for the WebVR display. function drawVRScene() { // WebVR: Request the next frame of the animation vrSceneFrame = vrDisplay.requestAnimationFrame(drawVRScene); // Populate frameData with the data of the next frame to display vrDisplay.getFrameData(frameData); // You can get the position, orientation, etc. of the display from the current frame's pose const curFramePose = frameData.pose; const curPos = curFramePose.position; const curOrient = curFramePose.orientation; // Clear the canvas before we start drawing on it. gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); // WebVR: Create the required projection and view matrix locations needed // for passing into the uniformMatrix4fv methods below const projectionMatrixLocation = gl.getUniformLocation( shaderProgram, "projMatrix", ); const viewMatrixLocation = gl.getUniformLocation(shaderProgram, "viewMatrix"); // WebVR: Render the left eye's view to the left half of the canvas gl.viewport(0, 0, canvas.width * 0.5, canvas.height); gl.uniformMatrix4fv( projectionMatrixLocation, false, frameData.leftProjectionMatrix, ); gl.uniformMatrix4fv(viewMatrixLocation, false, frameData.leftViewMatrix); drawGeometry(); // WebVR: Render the right eye's view to the right half of the canvas gl.viewport(canvas.width * 0.5, 0, canvas.width * 0.5, canvas.height); gl.uniformMatrix4fv( projectionMatrixLocation, false, frameData.rightProjectionMatrix, ); gl.uniformMatrix4fv(viewMatrixLocation, false, frameData.rightViewMatrix); drawGeometry(); function drawGeometry() { // draw the view for each eye } // … // WebVR: Indicate that we are ready to present the rendered frame to the VR display vrDisplay.submitFrame(); } ``` > **Note:** You can see this complete code at [raw-webgl-example](https://github.com/mdn/webvr-tests/blob/main/webvr/raw-webgl-example/webgl-demo.js). ## Specifications This method 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/vrdisplay
data/mdn-content/files/en-us/web/api/vrdisplay/displayname/index.md
--- title: "VRDisplay: displayName property" short-title: displayName slug: Web/API/VRDisplay/displayName page-type: web-api-instance-property status: - deprecated - non-standard browser-compat: api.VRDisplay.displayName --- {{APIRef("WebVR API")}}{{Deprecated_Header}}{{Non-standard_Header}} The **`displayName`** read-only property of the {{domxref("VRDisplay")}} interface returns a human-readable name to identify the `VRDisplay`. > **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/). This will generally be something like "Oculus VR HMD (HMD)" or "Oculus VR HMD (Sensor)". ## Value A string containing the human-readable name of the specific VR display. ## Examples See [`VRDisplayCapabilities`](/en-US/docs/Web/API/VRDisplayCapabilities#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/vrdisplay
data/mdn-content/files/en-us/web/api/vrdisplay/requestpresent/index.md
--- title: "VRDisplay: requestPresent() method" short-title: requestPresent() slug: Web/API/VRDisplay/requestPresent page-type: web-api-instance-method status: - deprecated - non-standard browser-compat: api.VRDisplay.requestPresent --- {{APIRef("WebVR API")}}{{Deprecated_Header}}{{Non-standard_Header}} The **`requestPresent()`** method of the {{domxref("VRDisplay")}} interface starts the `VRDisplay` presenting a scene. > **Note:** This method 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/). ## Syntax ```js-nolint requestPresent(layers) ``` ### Parameters - `layers` - : An array of {{domxref("VRLayerInit")}} objects representing the scene you want to present. At the moment, this can be a minimum of 0 and a maximum of 1. ### Return value A promise that resolves once the presentation has begun. There are a number of rules surrounding the promise's fulfillment or rejection: - If {{domxref("VRDisplayCapabilities.canPresent")}} is false, or if the VRLayer array contains more than {{domxref("VRDisplayCapabilities.maxLayers")}} layers, the promise will be rejected. - If the {{domxref("VRDisplay")}} is already presenting when `requestPresent()` is called, the `VRDisplay` will update the `VRLayer` array being presented. - If a call to `requestPresent()` is rejected while the `VRDisplay` is already presenting it will end its presentation. - If `requestPresent()` is called outside of an engagement gesture the promise will be rejected unless the `VRDisplay` was already presenting. This engagement gesture is also sufficient to allow [`requestPointerLock()`](/en-US/docs/Web/API/Element/requestPointerLock) calls until presentation has ended. ## Examples ```js if (navigator.getVRDisplays) { console.log("WebVR 1.1 supported"); // Then get the displays attached to the computer navigator.getVRDisplays().then((displays) => { // If a display is available, use it to present the scene if (displays.length > 0) { vrDisplay = displays[0]; console.log("Display found"); // Starting the presentation when the button is clicked: It can only be called in response to a user gesture btn.addEventListener("click", () => { if (btn.textContent === "Start VR display") { vrDisplay.requestPresent([{ source: canvas }]).then(() => { console.log("Presenting to WebVR display"); // Set the canvas size to the size of the vrDisplay viewport const leftEye = vrDisplay.getEyeParameters("left"); const rightEye = vrDisplay.getEyeParameters("right"); canvas.width = Math.max(leftEye.renderWidth, rightEye.renderWidth) * 2; canvas.height = Math.max( leftEye.renderHeight, rightEye.renderHeight, ); // stop the normal presentation, and start the vr presentation window.cancelAnimationFrame(normalSceneFrame); drawVRScene(); btn.textContent = "Exit VR display"; }); } else { vrDisplay.exitPresent(); console.log("Stopped presenting to WebVR display"); btn.textContent = "Start VR display"; // Stop the VR presentation, and start the normal presentation vrDisplay.cancelAnimationFrame(vrSceneFrame); drawScene(); } }); } }); } ``` > **Note:** You can see this complete code at [raw-webgl-example](https://github.com/mdn/webvr-tests/blob/main/webvr/raw-webgl-example/webgl-demo.js). ## Specifications This method 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/vrdisplay
data/mdn-content/files/en-us/web/api/vrdisplay/ispresenting/index.md
--- title: "VRDisplay: isPresenting property" short-title: isPresenting slug: Web/API/VRDisplay/isPresenting page-type: web-api-instance-property status: - deprecated - non-standard browser-compat: api.VRDisplay.isPresenting --- {{APIRef("WebVR API")}}{{Deprecated_Header}}{{Non-standard_Header}} The **`isPresenting`** read-only property of the {{domxref("VRDisplay")}} interface returns a boolean value indicating whether the `VRDisplay` is currently having content presented through it. > **Note:** This property was part of the old [WebVR API](https://immersive-web.github.io/webvr/spec/1.1/). It has been superseded by the [WebXR Device API](https://immersive-web.github.io/webxr/). ## Value A boolean value; `true` means the display is presenting; `false` means it isn't. ## Examples ```js function onVRExitPresent() { // No sense in exiting presentation if we're not actually presenting. // (This may happen if we get an event like vrdisplaydeactivate when // we weren't presenting.) if (!vrDisplay.isPresenting) return; vrDisplay.exitPresent().then( () => { // Nothing to do because we're handling things in onVRPresentChange. }, (err) => { let errMsg = "exitPresent failed."; if (err && err.message) { errMsg += `<br/>${err.message}`; } VRSamplesUtil.addError(errMsg, 2000); }, ); } ``` > **Note:** Code snippet taken from [Google's VR Presentation demo](https://github.com/toji/webvr.info/blob/master/samples/03-vr-presentation.html). ## 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/vrdisplay
data/mdn-content/files/en-us/web/api/vrdisplay/stageparameters/index.md
--- title: "VRDisplay: stageParameters property" short-title: stageParameters slug: Web/API/VRDisplay/stageParameters page-type: web-api-instance-property status: - deprecated - non-standard browser-compat: api.VRDisplay.stageParameters --- {{APIRef("WebVR API")}}{{Deprecated_Header}}{{Non-standard_Header}} The **`stageParameters`** read-only property of the {{domxref("VRDisplay")}} interface returns a {{domxref("VRStageParameters")}} object containing room-scale parameters, if the `VRDisplay` is capable of supporting room-scale experiences. > **Note:** This property was part of the old [WebVR API](https://immersive-web.github.io/webvr/spec/1.1/). It has been superseded by the [WebXR Device API](https://immersive-web.github.io/webxr/). ## Value {{domxref("VRStageParameters")}} object containing the `VRDisplay`'s room-scale parameters, or `null` if the `VRDisplay` is not capable of supporting room-scale experiences. ## Examples See [`VRStageParameters`](/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/vrdisplay
data/mdn-content/files/en-us/web/api/vrdisplay/displayid/index.md
--- title: "VRDisplay: displayId property" short-title: displayId slug: Web/API/VRDisplay/displayId page-type: web-api-instance-property status: - deprecated - non-standard browser-compat: api.VRDisplay.displayId --- {{APIRef("WebVR API")}}{{Deprecated_Header}}{{Non-standard_Header}} The **`displayId`** read-only property of the {{domxref("VRDisplay")}} interface returns an identifier for this particular `VRDisplay`, which is also used as an association point in the [Gamepad API](/en-US/docs/Web/API/Gamepad_API) (see {{domxref("Gamepad.displayId")}}). > **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/). ## Value A number representing the ID of the specific `VRDisplay`. ## Examples See [`VRDisplayCapabilities`](/en-US/docs/Web/API/VRDisplayCapabilities#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/vrdisplay
data/mdn-content/files/en-us/web/api/vrdisplay/getimmediatepose/index.md
--- title: "VRDisplay: getImmediatePose() method" short-title: getImmediatePose() slug: Web/API/VRDisplay/getImmediatePose page-type: web-api-instance-method status: - deprecated - non-standard browser-compat: api.VRDisplay.getImmediatePose --- {{Deprecated_Header}}{{APIRef("WebVR API")}}{{Non-standard_Header}} The **`getImmediatePose()`** method of the {{domxref("VRDisplay")}} interface returns a {{domxref("VRPose")}} object defining the current pose of the `VRDisplay`, with no prediction applied. > **Note:** This method 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/). ## Syntax ```js-nolint getImmediatePose() ``` ### Parameters None. ### Return value A {{domxref("VRPose")}} object. ## Specifications This method 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/vrdisplay
data/mdn-content/files/en-us/web/api/vrdisplay/exitpresent/index.md
--- title: "VRDisplay: exitPresent() method" short-title: exitPresent() slug: Web/API/VRDisplay/exitPresent page-type: web-api-instance-method status: - deprecated - non-standard browser-compat: api.VRDisplay.exitPresent --- {{APIRef("WebVR API")}}{{Deprecated_Header}}{{Non-standard_Header}} The **`exitPresent()`** method of the {{domxref("VRDisplay")}} interface stops the `VRDisplay` presenting a scene. > **Note:** This method 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/). ## Syntax ```js-nolint exitPresent() ``` ### Parameters None. ### Return value A promise that resolves once the presentation has ended. If the `VRDisplay` is not presenting when `exitPresent()` is called, the promise will reject. ## Examples ```js if (navigator.getVRDisplays) { console.log("WebVR 1.1 supported"); // Then get the displays attached to the computer navigator.getVRDisplays().then((displays) => { // If a display is available, use it to present the scene if (displays.length > 0) { vrDisplay = displays[0]; console.log("Display found"); // Starting the presentation when the button is clicked: It can only be called in response to a user gesture btn.addEventListener("click", () => { if (btn.textContent === "Start VR display") { vrDisplay.requestPresent([{ source: canvas }]).then(() => { console.log("Presenting to WebVR display"); // Set the canvas size to the size of the vrDisplay viewport const leftEye = vrDisplay.getEyeParameters("left"); const rightEye = vrDisplay.getEyeParameters("right"); canvas.width = Math.max(leftEye.renderWidth, rightEye.renderWidth) * 2; canvas.height = Math.max( leftEye.renderHeight, rightEye.renderHeight, ); // stop the normal presentation, and start the vr presentation window.cancelAnimationFrame(normalSceneFrame); drawVRScene(); btn.textContent = "Exit VR display"; }); } else { vrDisplay.exitPresent(); console.log("Stopped presenting to WebVR display"); btn.textContent = "Start VR display"; // Stop the VR presentation, and start the normal presentation vrDisplay.cancelAnimationFrame(vrSceneFrame); drawScene(); } }); } }); } ``` > **Note:** You can see this complete code at [raw-webgl-example](https://github.com/mdn/webvr-tests/blob/main/webvr/raw-webgl-example/webgl-demo.js). ## Specifications This method 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/vrdisplay
data/mdn-content/files/en-us/web/api/vrdisplay/getframedata/index.md
--- title: "VRDisplay: getFrameData() method" short-title: getFrameData() slug: Web/API/VRDisplay/getFrameData page-type: web-api-instance-method status: - deprecated - non-standard browser-compat: api.VRDisplay.getFrameData --- {{APIRef("WebVR API")}}{{Deprecated_Header}}{{Non-standard_Header}} The **`getFrameData()`** method of the {{domxref("VRDisplay")}} interface accepts a {{domxref("VRFrameData")}} object and populates it with the information required to render the current frame. > **Note:** This method 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 includes the {{domxref("VRPose")}} and view and projection matrices for the current frame. ## Syntax ```js-nolint getFrameData(frameData) ``` ### Parameters - `frameData` - : The {{domxref("VRFrameData")}} object you want to populate. ### Return value A boolean value — a value of `true` is returned if the {{domxref("VRFrameData")}} object was successfully populated, or `false` if it wasn't. ## Examples ```js const frameData = new VRFrameData(); let vrDisplay; navigator.getVRDisplays().then((displays) => { vrDisplay = displays[0]; console.log("Display found"); // Starting the presentation when the button is clicked: It can only be called in response to a user gesture btn.addEventListener("click", () => { vrDisplay.requestPresent([{ source: canvas }]).then(() => { drawVRScene(); }); }); }); // WebVR: Draw the scene for the WebVR display. function drawVRScene() { // WebVR: Request the next frame of the animation vrSceneFrame = vrDisplay.requestAnimationFrame(drawVRScene); // Populate frameData with the data of the next frame to display vrDisplay.getFrameData(frameData); // You can get the position, orientation, etc. of the display from the current frame's pose // curFramePose is a VRPose object const curFramePose = frameData.pose; const curPos = curFramePose.position; const curOrient = curFramePose.orientation; // Clear the canvas before we start drawing on it. gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); // WebVR: Create the required projection and view matrix locations needed // for passing into the uniformMatrix4fv methods below const projectionMatrixLocation = gl.getUniformLocation( shaderProgram, "projMatrix", ); const viewMatrixLocation = gl.getUniformLocation(shaderProgram, "viewMatrix"); // WebVR: Render the left eye's view to the left half of the canvas gl.viewport(0, 0, canvas.width * 0.5, canvas.height); gl.uniformMatrix4fv( projectionMatrixLocation, false, frameData.leftProjectionMatrix, ); gl.uniformMatrix4fv(viewMatrixLocation, false, frameData.leftViewMatrix); drawGeometry(); // WebVR: Render the right eye's view to the right half of the canvas gl.viewport(canvas.width * 0.5, 0, canvas.width * 0.5, canvas.height); gl.uniformMatrix4fv( projectionMatrixLocation, false, frameData.rightProjectionMatrix, ); gl.uniformMatrix4fv(viewMatrixLocation, false, frameData.rightViewMatrix); drawGeometry(); function drawGeometry() { // draw the view for each eye } // … // WebVR: Indicate that we are ready to present the rendered frame to the VR display vrDisplay.submitFrame(); } ``` > **Note:** You can see this complete code at [raw-webgl-example](https://github.com/mdn/webvr-tests/blob/main/webvr/raw-webgl-example/webgl-demo.js). ## Specifications This method 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/vrdisplay
data/mdn-content/files/en-us/web/api/vrdisplay/cancelanimationframe/index.md
--- title: "VRDisplay: cancelAnimationFrame() method" short-title: cancelAnimationFrame() slug: Web/API/VRDisplay/cancelAnimationFrame page-type: web-api-instance-method status: - deprecated - non-standard browser-compat: api.VRDisplay.cancelAnimationFrame --- {{APIRef("WebVR API")}}{{Deprecated_Header}}{{Non-standard_Header}} The **`cancelAnimationFrame()`** method of the {{domxref("VRDisplay")}} interface is a special implementation of {{domxref("Window.cancelAnimationFrame")}} that unregisters callbacks registered with {{domxref("VRDisplay.requestAnimationFrame()")}}. > **Note:** This method 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/). ## Syntax ```js-nolint cancelAnimationFrame(handle) ``` ### Parameters - `handle` - : The handle returned by the {{domxref("VRDisplay.requestAnimationFrame()")}} call that you want to unregister. ### Return value None ({{jsxref("undefined")}}). ## Examples ```js canvas.width = window.innerWidth; canvas.height = window.innerHeight; drawScene(); // WebVR: Check to see if WebVR is supported if (navigator.getVRDisplays) { console.log("WebVR 1.1 supported"); // Then get the displays attached to the computer navigator.getVRDisplays().then((displays) => { // If a display is available, use it to present the scene if (displays.length > 0) { vrDisplay = displays[0]; console.log("Display found"); // Starting the presentation when the button is clicked: It can only be called in response to a user gesture btn.addEventListener("click", () => { if (btn.textContent === "Start VR display") { vrDisplay.requestPresent([{ source: canvas }]).then(() => { console.log("Presenting to WebVR display"); // Set the canvas size to the size of the vrDisplay viewport const leftEye = vrDisplay.getEyeParameters("left"); const rightEye = vrDisplay.getEyeParameters("right"); canvas.width = Math.max(leftEye.renderWidth, rightEye.renderWidth) * 2; canvas.height = Math.max( leftEye.renderHeight, rightEye.renderHeight, ); // stop the normal presentation, and start the vr presentation window.cancelAnimationFrame(normalSceneFrame); drawVRScene(); btn.textContent = "Exit VR display"; }); } else { vrDisplay.exitPresent(); console.log("Stopped presenting to WebVR display"); btn.textContent = "Start VR display"; // Stop the VR presentation, and start the normal presentation vrDisplay.cancelAnimationFrame(vrSceneFrame); drawScene(); } }); } }); } else { info.textContent = "WebVR API not supported by this browser."; } function drawVRScene() { // WebVR: Request the next frame of the animation vrSceneFrame = vrDisplay.requestAnimationFrame(drawVRScene); // … } ``` > **Note:** You can see this complete code at [raw-webgl-example](https://github.com/mdn/webvr-tests/blob/main/webvr/raw-webgl-example/webgl-demo.js). ## Specifications This method 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/vrdisplay
data/mdn-content/files/en-us/web/api/vrdisplay/requestanimationframe/index.md
--- title: "VRDisplay: requestAnimationFrame() method" short-title: requestAnimationFrame() slug: Web/API/VRDisplay/requestAnimationFrame page-type: web-api-instance-method status: - deprecated - non-standard browser-compat: api.VRDisplay.requestAnimationFrame --- {{APIRef("WebVR API")}}{{Deprecated_Header}}{{Non-standard_Header}} The **`requestAnimationFrame()`** method of the {{domxref("VRDisplay")}} interface is a special implementation of {{domxref("Window.requestAnimationFrame")}} containing a callback function that will be called every time a new frame of the `VRDisplay` presentation is rendered: > **Note:** This method was part of the old [WebVR API](https://immersive-web.github.io/webvr/spec/1.1/). It has been superseded by the [WebXR Device API](https://immersive-web.github.io/webxr/). - When the `VRDisplay` is not presenting a scene, this is functionally equivalent to {{domxref("Window.requestAnimationFrame")}}. - When the `VRDisplay` is presenting, the callback is called at its native refresh rate. ## Syntax ```js-nolint requestAnimationFrame(callback) ``` ### Parameters - `callback` - : A callback function that will be called every time a new frame of the `VRDisplay` presentation is rendered. ### Return value A long representing the handle of the `requestAnimationFrame()` call. This can then be passed to a {{domxref("VRDisplay.cancelAnimationFrame()")}} call to unregister the callback. ## Examples ```js const frameData = new VRFrameData(); let vrDisplay; navigator.getVRDisplays().then((displays) => { vrDisplay = displays[0]; console.log("Display found"); // Starting the presentation when the button is clicked: It can only be called in response to a user gesture btn.addEventListener("click", () => { vrDisplay.requestPresent([{ source: canvas }]).then(() => { drawVRScene(); }); }); }); // WebVR: Draw the scene for the WebVR display. function drawVRScene() { // WebVR: Request the next frame of the animation vrSceneFrame = vrDisplay.requestAnimationFrame(drawVRScene); // Populate frameData with the data of the next frame to display vrDisplay.getFrameData(frameData); // You can get the position, orientation, etc. of the display from the current frame's pose const curFramePose = frameData.pose; const curPos = curFramePose.position; const curOrient = curFramePose.orientation; // Clear the canvas before we start drawing on it. gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); // WebVR: Create the required projection and view matrix locations needed // for passing into the uniformMatrix4fv methods below const projectionMatrixLocation = gl.getUniformLocation( shaderProgram, "projMatrix", ); const viewMatrixLocation = gl.getUniformLocation(shaderProgram, "viewMatrix"); // WebVR: Render the left eye's view to the left half of the canvas gl.viewport(0, 0, canvas.width * 0.5, canvas.height); gl.uniformMatrix4fv( projectionMatrixLocation, false, frameData.leftProjectionMatrix, ); gl.uniformMatrix4fv(viewMatrixLocation, false, frameData.leftViewMatrix); drawGeometry(); // WebVR: Render the right eye's view to the right half of the canvas gl.viewport(canvas.width * 0.5, 0, canvas.width * 0.5, canvas.height); gl.uniformMatrix4fv( projectionMatrixLocation, false, frameData.rightProjectionMatrix, ); gl.uniformMatrix4fv(viewMatrixLocation, false, frameData.rightViewMatrix); drawGeometry(); function drawGeometry() { // draw the view for each eye } // … // WebVR: Indicate that we are ready to present the rendered frame to the VR display vrDisplay.submitFrame(); } ``` > **Note:** You can see this complete code at [raw-webgl-example](https://github.com/mdn/webvr-tests/blob/main/webvr/raw-webgl-example/webgl-demo.js). ## Specifications This method 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/vrdisplay
data/mdn-content/files/en-us/web/api/vrdisplay/getpose/index.md
--- title: "VRDisplay: getPose() method" short-title: getPose() slug: Web/API/VRDisplay/getPose page-type: web-api-instance-method status: - deprecated - non-standard browser-compat: api.VRDisplay.getPose --- {{APIRef("WebVR API")}}{{Deprecated_Header}}{{Non-standard_Header}} The **`getPose()`** method of the {{domxref("VRDisplay")}} interface returns a {{domxref("VRPose")}} object defining the future predicted pose of the `VRDisplay` as it will be when the current frame is actually presented. > **Note:** This method was part of the old [WebVR API](https://immersive-web.github.io/webvr/spec/1.1/). It has been superseded by the [WebXR Device API](https://immersive-web.github.io/webxr/). > > It was even deprecated there — instead, you should use {{domxref("VRDisplay.getFrameData()")}}, which also provides a {{domxref("VRPose")}} object. ## Syntax ```js-nolint getPose() ``` ### Parameters None. ### Return value A {{domxref("VRPose")}} object. ## Examples Once we have a reference to a {{domxref("VRDisplay")}} object, we can retrieve the {{domxref("VRPose")}} representing the current pose of the display. ```js if (navigator.getVRDisplays) { console.log("WebVR 1.1 supported"); // Then get the displays attached to the computer navigator.getVRDisplays().then((displays) => { // If a display is available, use it to present the scene if (displays.length > 0) { vrDisplay = displays[0]; console.log("Display found"); // Return the current VRPose object for the display const pose = vrDisplay.getPose(); // … } }); } ``` It is however recommended that you use the non-deprecated {{domxref("VRFrameData.pose", "pose")}} property of the {{domxref("VRFrameData")}} object (retrieved via {{domxref("VRDisplay.getFrameData()")}}) to retrieve the current pose for each frame before it is submitted to the display to be presented. This happens on each iteration of the rendering loop for your app, so you can be sure the pose data is current. ## Specifications This method was part of the old [WebVR API](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/vrdisplay
data/mdn-content/files/en-us/web/api/vrdisplay/getlayers/index.md
--- title: "VRDisplay: getLayers() method" short-title: getLayers() slug: Web/API/VRDisplay/getLayers page-type: web-api-instance-method status: - deprecated - non-standard browser-compat: api.VRDisplay.getLayers --- {{APIRef("WebVR API")}}{{Deprecated_Header}}{{Non-standard_Header}} The **`getLayers()`** method of the {{domxref("VRDisplay")}} interface returns the layers currently being presented by the `VRDisplay`. > **Note:** This method 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/). ## Syntax ```js-nolint getLayers() ``` ### Parameters None. ### Return value If the {{domxref("VRDisplay")}} is presenting, this method returns an array of the {{domxref("VRLayerInit")}} objects currently being presented (this will currently be one, as {{domxref("VRDisplayCapabilities.maxLayers")}} is currently always 1). If the {{domxref("VRDisplay")}} is not presenting, this method returns an empty array. ## Examples See [`VRLayerInit`](/en-US/docs/Web/API/VRLayerInit#examples) for example code. ## Specifications This method 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/vrdisplay
data/mdn-content/files/en-us/web/api/vrdisplay/capabilities/index.md
--- title: "VRDisplay: capabilities property" short-title: capabilities slug: Web/API/VRDisplay/capabilities page-type: web-api-instance-property status: - deprecated - non-standard browser-compat: api.VRDisplay.capabilities --- {{APIRef("WebVR API")}}{{Deprecated_Header}}{{Non-standard_Header}} The **`capabilities`** read-only property of the {{domxref("VRDisplay")}} interface returns a {{domxref("VRDisplayCapabilities")}} object that indicates the various capabilities of the `VRDisplay`. > **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/). ## Value A {{domxref("VRDisplayCapabilities")}} object. ## Examples See [`VRDisplayCapabilities`](/en-US/docs/Web/API/VRDisplayCapabilities#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/vrdisplay
data/mdn-content/files/en-us/web/api/vrdisplay/geteyeparameters/index.md
--- title: "VRDisplay: getEyeParameters() method" short-title: getEyeParameters() slug: Web/API/VRDisplay/getEyeParameters page-type: web-api-instance-method status: - deprecated - non-standard browser-compat: api.VRDisplay.getEyeParameters --- {{APIRef("WebVR API")}}{{Deprecated_Header}}{{Non-standard_Header}} The **`getEyeParameters()`** method of the {{domxref("VRDisplay")}} interface returns the {{domxref("VREyeParameters")}} object containing the eye parameters for the specified eye. > **Note:** This method 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/). ## Syntax ```js-nolint getEyeParameters(whichEye) ``` ### Parameters - `whichEye` - : A string representing the eye you want to return the eye parameters for. Available values are `left` and `right` (defined in the [VREye enum](https://w3c.github.io/webvr/spec/1.1/#interface-vreye)). ### Return value A {{domxref("VREyeParameters")}} object, or null if the VR is not able to present content (e.g. {{domxref("VRDisplayCapabilities.canPresent")}} returns `false`). ## Examples See [`VREyeParameters`](/en-US/docs/Web/API/VREyeParameters#examples) for example code. ## Specifications This method 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/vrdisplay
data/mdn-content/files/en-us/web/api/vrdisplay/resetpose/index.md
--- title: "VRDisplay: resetPose() method" short-title: resetPose() slug: Web/API/VRDisplay/resetPose page-type: web-api-instance-method status: - deprecated - non-standard browser-compat: api.VRDisplay.resetPose --- {{APIRef("WebVR API")}}{{Deprecated_Header}}{{Non-standard_Header}} The **`resetPose()`** method of the {{domxref("VRDisplay")}} interface resets the pose for the `VRDisplay`, treating its current {{domxref("VRPose.position")}} and {{domxref("VRPose.orientation")}} as the "origin/zero" values. > **Note:** This method 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/). After `resetPost()` has been called, future poses returned from {{domxref("VRDisplay.getPose()")}}/{{domxref("VRDisplay.getImmediatePose()")}} will describe positions relative to the `VRDisplay`'s position when `resetPose()` was last called and will treat the display's yaw when `resetPose()` was last called as the forward orientation. The VRDisplay's reported roll and pitch do not change when `resetPose()` is called as they are relative to gravity. Calling `resetPose()` may change the {{domxref("VRStageParameters.sittingToStandingTransform")}} matrix. ## Syntax ```js-nolint resetPose() ``` ### Parameters None. ### Return value None ({{jsxref("undefined")}}). ## Examples ```js // Assuming vrDisplay already contains a VRDisplay object, // and we have a <button> referenced inside btn btn.addEventListener("click", () => { vrDisplay.resetPose(); console.log("Current pose set as origin/center"); }); ``` ## Specifications This method was part of the old [WebVR API](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/vrdisplay
data/mdn-content/files/en-us/web/api/vrdisplay/depthfar/index.md
--- title: "VRDisplay: depthFar property" short-title: depthFar slug: Web/API/VRDisplay/depthFar page-type: web-api-instance-property status: - deprecated - non-standard browser-compat: api.VRDisplay.depthFar --- {{APIRef("WebVR API")}}{{Deprecated_Header}}{{Non-standard_Header}} The **`depthFar`** property of the {{domxref("VRDisplay")}} interface gets and sets the z-depth defining the far plane of the [eye view frustum](https://en.wikipedia.org/wiki/Viewing_frustum), i.e. the furthest viewable boundary of the scene. > **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/). Generally you should leave the value as is, but you might want to reduce it if you are trying to improve performance on slower computers. ## Value A double, representing the z-depth in meters. It initial value is `10000.0`. ## Examples ```js let vrDisplay; navigator.getVRDisplays().then((displays) => { vrDisplay = displays[0]; vrDisplay.depthNear = 1.0; vrDisplay.depthFar = 7500.0; }); ``` ## Specifications This property was part of the old [WebVR API](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/vrdisplay
data/mdn-content/files/en-us/web/api/vrdisplay/depthnear/index.md
--- title: "VRDisplay: depthNear property" short-title: depthNear slug: Web/API/VRDisplay/depthNear page-type: web-api-instance-property status: - deprecated - non-standard browser-compat: api.VRDisplay.depthNear --- {{APIRef("WebVR API")}}{{Deprecated_Header}}{{Non-standard_Header}} The **`depthNear`** property of the {{domxref("VRDisplay")}} interface gets and sets the z-depth defining the near plane of the [eye view frustum](https://en.wikipedia.org/wiki/Viewing_frustum), i.e. the nearest viewable boundary of the scene. > **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/). Generally you should leave the value as is, but you might want to increase it if you are trying to improve performance on slower computers, and/or your UI makes sense with the near boundary made further away. ## Value A double, representing the z-depth in meters; its initial value is `0.01`. ## Examples ```js let vrDisplay; navigator.getVRDisplays().then((displays) => { vrDisplay = displays[0]; vrDisplay.depthNear = 1.0; vrDisplay.depthFar = 7500.0; }); ``` ## Specifications This property was part of the old [WebVR API](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/channelmergernode/index.md
--- title: ChannelMergerNode slug: Web/API/ChannelMergerNode page-type: web-api-interface browser-compat: api.ChannelMergerNode --- {{APIRef("Web Audio API")}} The `ChannelMergerNode` interface, often used in conjunction with its opposite, {{domxref("ChannelSplitterNode")}}, reunites different mono inputs into a single output. Each input is used to fill a channel of the output. This is useful for accessing each channels separately, e.g. for performing channel mixing where gain must be separately controlled on each channel. ![Default channel merger node with six mono inputs combining to form a single output.](webaudiomerger.png) If `ChannelMergerNode` has one single output, but as many inputs as there are channels to merge; the number of inputs is defined as a parameter of its constructor and the call to {{domxref("BaseAudioContext/createChannelMerger", "AudioContext.createChannelMerger()")}}. In the case that no value is given, it will default to `6`. Using a `ChannelMergerNode`, it is possible to create outputs with more channels than the rendering hardware is able to process. In that case, when the signal is sent to the {{domxref("BaseAudioContext/listener", "AudioContext.listener")}} object, supernumerary channels will be ignored. {{InheritanceDiagram}} <table class="properties"> <tbody> <tr> <th scope="row">Number of inputs</th> <td>variable; default to <code>6</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>"explicit"</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("ChannelMergerNode.ChannelMergerNode()", "ChannelMergerNode()")}} - : Creates a new `ChannelMergerNode` object instance. ## Instance properties _No specific property; inherits properties from its parent, {{domxref("AudioNode")}}_. ## Instance methods _No specific method; inherits methods from its parent, {{domxref("AudioNode")}}_. ## Example See [`BaseAudioContext.createChannelMerger()`](/en-US/docs/Web/API/BaseAudioContext/createChannelMerger#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/channelmergernode
data/mdn-content/files/en-us/web/api/channelmergernode/channelmergernode/index.md
--- title: "ChannelMergerNode: ChannelMergerNode() constructor" short-title: ChannelMergerNode() slug: Web/API/ChannelMergerNode/ChannelMergerNode page-type: web-api-constructor browser-compat: api.ChannelMergerNode.ChannelMergerNode --- {{APIRef("Web Audio API")}} The **`ChannelMergerNode()`** constructor creates a new {{domxref("ChannelMergerNode")}} object instance. ## Syntax ```js-nolint new ChannelMergerNode(context) new ChannelMergerNode(context, options) ``` ### Parameters - `context` - : A {{domxref("BaseAudioContext")}} representing the audio context you want the node to be associated with. - `options` {{optional_inline}} - : An object defining the properties you want the `ChannelMergerNode` to have: - `numberOfInputs` {{optional_inline}} - : A number defining the number of inputs the {{domxref("ChannelMergerNode")}} should have. If not specified, the default value used is 6. - `channelCount` {{optional_inline}} - : 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` {{optional_inline}} - : A string 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` {{optional_inline}} - : A string 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("ChannelMergerNode")}} object instance. ### Exceptions - `InvalidStateError` {{domxref("DOMException")}} - : Thrown if an option such as `channelCount` or `channelCountMode` has been given an invalid value. ## Examples ```js const ac = new AudioContext(); const options = { numberOfInputs: 2, }; const myMerger = new ChannelMergerNode(ac, options); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/dompointreadonly/index.md
--- title: DOMPointReadOnly slug: Web/API/DOMPointReadOnly page-type: web-api-interface browser-compat: api.DOMPointReadOnly --- {{APIRef("Geometry Interfaces")}} The **`DOMPointReadOnly`** interface specifies the coordinate and perspective fields used by {{domxref("DOMPoint")}} to define a 2D or 3D point in a coordinate system. {{AvailableInWorkers}} There are two ways to create a new `DOMPointReadOnly` instance. First, you can use its constructor, passing in the values of the parameters for each dimension and, optionally, the perspective: ```js /* 2D */ const point2D = new DOMPointReadOnly(50, 50); /* 3D */ const point3D = new DOMPointReadOnly(50, 50, 25); /* 3D with perspective */ const point3DPerspective = new DOMPointReadOnly(100, 100, 100, 1.0); ``` The other option is to use the static {{domxref("DOMPointReadOnly.fromPoint_static", "DOMPointReadOnly.fromPoint()")}} method: ```js const point = DOMPointReadOnly.fromPoint({ x: 100, y: 100, z: 50, w: 1.0 }); ``` ## Constructor - {{domxref("DOMPointReadOnly.DOMPointReadOnly","DOMPointReadOnly()")}} - : Creates a new `DOMPointReadOnly` object given the values of its coordinates and perspective. To create a point using an object, you can instead use {{domxref("DOMPointReadOnly.fromPoint_static", "DOMPointReadOnly.fromPoint()")}}. ## Instance properties - {{domxref("DOMPointReadOnly.x")}} {{ReadOnlyInline}} - : The point's horizontal coordinate, `x`. - {{domxref("DOMPointReadOnly.y")}} {{ReadOnlyInline}} - : The point's vertical coordinate, `y`. - {{domxref("DOMPointReadOnly.z")}} {{ReadOnlyInline}} - : The point's depth coordinate, `z`. - {{domxref("DOMPointReadOnly.w")}} {{ReadOnlyInline}} - : The point's perspective value, `w`. ## Static methods - {{domxref("DOMPointReadOnly.fromPoint_static", "DOMPointReadOnly.fromPoint()")}} - : A static method that creates a new `DOMPointReadOnly` object given the coordinates provided in the specified object. ## Instance methods - {{domxref("DOMPointReadOnly.matrixTransform", "matrixTransform()")}} - : Applies a matrix transform specified as an object to the `DOMPointReadOnly` object. - {{domxref("DOMPointReadOnly.toJSON()", "toJSON()")}} - : Returns a JSON representation of the `DOMPointReadOnly` object. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("DOMPoint")}} - {{domxref("DOMRect")}} - {{domxref("DOMMatrix")}}
0
data/mdn-content/files/en-us/web/api/dompointreadonly
data/mdn-content/files/en-us/web/api/dompointreadonly/z/index.md
--- title: "DOMPointReadOnly: z property" short-title: z slug: Web/API/DOMPointReadOnly/z page-type: web-api-instance-property browser-compat: api.DOMPointReadOnly.z --- {{APIRef("DOM")}} The **`DOMPointReadOnly`** interface's **`z`** property holds the depth coordinate, z, for a read-only point in space. If your script needs to be able to change the value of this property, you should instead use the {{domxref("DOMPoint")}} object. In general, positive values of `z` mean toward the user (out from the screen), and negative values of `z` mean away from the user (into the screen), assuming no transforms have resulted in a reversal. ## Value A double-precision floating-point value indicating the z coordinate's value for the point. This value is **unrestricted**, meaning that it is allowed to be infinite or invalid (that is, its value may be {{jsxref("NaN")}} or {{jsxref("Infinity", "±Infinity")}}). ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The other coordinate properties: {{domxref("DOMPointReadOnly.x", "x")}}, {{domxref("DOMPointReadOnly.y", "y")}}, and the perspective value, {{domxref("DOMPointReadOnly.w", "w")}}.
0
data/mdn-content/files/en-us/web/api/dompointreadonly
data/mdn-content/files/en-us/web/api/dompointreadonly/y/index.md
--- title: "DOMPointReadOnly: y property" short-title: "y" slug: Web/API/DOMPointReadOnly/y page-type: web-api-instance-property browser-compat: api.DOMPointReadOnly.y --- {{APIRef("DOM")}} The **`DOMPointReadOnly`** interface's **`y`** property holds the vertical coordinate, y, for a read-only point in space. If your script needs to be able to change the value of this property, you should instead use the {{domxref("DOMPoint")}} object. In general, positive values of `y` mean downward, and negative values of `y` mean upward, assuming no transforms have resulted in a reversal. ## Value A double-precision floating-point value indicating the y coordinate's value for the point. This value is **unrestricted**, meaning that it is allowed to be infinite or invalid (that is, its value may be {{jsxref("NaN")}} or {{jsxref("Infinity", "±Infinity")}}). ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The other coordinate properties: {{domxref("DOMPointReadOnly.x", "x")}}, {{domxref("DOMPointReadOnly.z", "z")}}, and the perspective value, {{domxref("DOMPointReadOnly.w", "w")}}.
0
data/mdn-content/files/en-us/web/api/dompointreadonly
data/mdn-content/files/en-us/web/api/dompointreadonly/x/index.md
--- title: "DOMPointReadOnly: x property" short-title: x slug: Web/API/DOMPointReadOnly/x page-type: web-api-instance-property browser-compat: api.DOMPointReadOnly.x --- {{APIRef("DOM")}} The **`DOMPointReadOnly`** interface's **`x`** property holds the horizontal coordinate, x, for a read-only point in space. This property cannot be changed by JavaScript code in this read-only version of the `DOMPoint` object. In general, positive values `x` mean to the right, and negative values of `x` means to the left, assuming no transforms have resulted in a reversal. ## Value A double-precision floating-point value indicating the x coordinate's value for the point. This value is **unrestricted**, meaning that it is allowed to be infinite or invalid (that is, its value may be {{jsxref("NaN")}} or {{jsxref("Infinity", "±Infinity")}}). ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The other coordinate properties: {{domxref("DOMPointReadOnly.y", "y")}}, {{domxref("DOMPointReadOnly.z", "z")}}, and the perspective value, {{domxref("DOMPointReadOnly.w", "w")}}.
0
data/mdn-content/files/en-us/web/api/dompointreadonly
data/mdn-content/files/en-us/web/api/dompointreadonly/dompointreadonly/index.md
--- title: "DOMPointReadOnly: DOMPointReadOnly() constructor" short-title: DOMPointReadOnly() slug: Web/API/DOMPointReadOnly/DOMPointReadOnly page-type: web-api-constructor browser-compat: api.DOMPointReadOnly.DOMPointReadOnly --- {{APIRef("DOM")}} The **`DOMPointReadOnly()`** constructor returns a new {{domxref("DOMPointReadOnly")}} object representing a point in 2D or 3D space, optionally with perspective, whose values cannot be altered by script code. ## Syntax ```js-nolint new DOMPointReadOnly() new DOMPointReadOnly(x) new DOMPointReadOnly(x, y) new DOMPointReadOnly(x, y, z) new DOMPointReadOnly(x, y, z, w) ``` ### Parameters - `x` {{optional_inline}} - : The value of the horizontal coordinate, x, as a floating point number. The default value is 0. - `y` {{optional_inline}} - : The value of the vertical coordinate, y, as a floating point number. The default value is 0. - `z` {{optional_inline}} - : The value of the depth coordinate, z, as a floating point number. The default value is 0. - `w` {{optional_inline}} - : The value of the perspective, w, as a floating point number. The default is 1. > **Note:** Each of these values is what's called an _unrestricted_ > number. In addition to any finite floating-point value, you may use special values > such as ±{{jsxref("Infinity")}} and {{jsxref("NaN")}}. ### Return value A new {{domxref("DOMPointReadOnly")}} object representing the specified location in space. ## Examples The following code demonstrates creating both 2D and 3D points. ```js const point2D = new DOMPointReadOnly(50, 25); const point3D = new DOMPointReadOnly(50, 0, 10); const perspectivePoint3D = new DOMPointReadOnly(50, 50, 25, 0.5); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/dompointreadonly
data/mdn-content/files/en-us/web/api/dompointreadonly/w/index.md
--- title: "DOMPointReadOnly: w property" short-title: w slug: Web/API/DOMPointReadOnly/w page-type: web-api-instance-property browser-compat: api.DOMPointReadOnly.w --- {{APIRef("DOM")}} The **`DOMPointReadOnly`** interface's **`w`** property holds the point's perspective value, `w`, for a read-only point in space. If your script needs to be able to change the value of this property, you should instead use the {{domxref("DOMPoint")}} object. ## Value A double-precision floating-point value indicating the `w` perspective value for the point. This value is **unrestricted**, meaning that it is allowed to be infinite or invalid (that is, its value may be {{jsxref("NaN")}} or {{jsxref("Infinity", "±Infinity")}}). The default is `1.0`. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The other coordinate properties: {{domxref("DOMPointReadOnly.x", "x")}}, {{domxref("DOMPointReadOnly.y", "y")}}, and {{domxref("DOMPointReadOnly.z", "z")}}.
0
data/mdn-content/files/en-us/web/api/dompointreadonly
data/mdn-content/files/en-us/web/api/dompointreadonly/tojson/index.md
--- title: "DOMPointReadOnly: toJSON() method" short-title: toJSON() slug: Web/API/DOMPointReadOnly/toJSON page-type: web-api-instance-method browser-compat: api.DOMPointReadOnly.toJSON --- {{APIRef("DOM")}} The {{domxref("DOMPointReadOnly")}} method `toJSON()` returns an object giving the {{Glossary("JSON")}} form of the point object. ## Syntax ```js-nolint toJSON() ``` ### Parameters None. ### Return value A new object whose properties are set to the values in the `DOMPoint` or `DOMPointReadOnly` on which the method was called. ## Examples This example creates a {{domxref("DOMPoint")}} object representing the top-left corner of the current window, in screen coordinates, then converts that to JSON. ```js const topLeft = new DOMPoint(window.screenX, window.screenY); const pointJSON = topLeft.toJSON(); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/dompointreadonly
data/mdn-content/files/en-us/web/api/dompointreadonly/frompoint_static/index.md
--- title: "DOMPointReadOnly: fromPoint() static method" short-title: fromPoint() slug: Web/API/DOMPointReadOnly/fromPoint_static page-type: web-api-static-method browser-compat: api.DOMPointReadOnly.fromPoint_static --- {{APIRef("DOM")}} The static **{{domxref("DOMPointReadOnly")}}** method `fromPoint()` creates and returns a new `DOMPointReadOnly` object given a source point. You can also create a new `DOMPointReadOnly` object using the {{domxref("DOMPointReadOnly.DOMPointReadOnly", "new DOMPointReadOnly()")}} constructor. ## Syntax ```js-nolint DOMPointReadOnly.fromPoint(sourcePoint) ``` ### Parameters - `sourcePoint` - : A {{domxref("DOMPoint")}} or {{domxref("DOMPointReadOnly")}} instance, or an object containing the following properties, from which to take the values of the new point's properties: - `x` - : An unrestricted floating-point value indicating the `x`-coordinate of the point in space. This is generally the horizontal coordinate, with positive values being to the right and negative values to the left. The default value is `0`. - `y` - : An unrestricted floating-point number providing the point's `y`-coordinate. This is the vertical coordinate, and barring any transforms applied to the coordinate system, positive values are downward and negative values upward toward the top of the screen. The default is `0`. - `z` - : An unrestricted floating-point value which gives the point's `z`-coordinate, which is (assuming no transformations that alter the situation) the depth coordinate; positive values are closer to the user and negative values retreat back into the screen. The default value is `0`. - `w` - : The point's `w` perspective value, given as an unrestricted floating-point number. The default is `1`. ### Return value A new {{domxref("DOMPointReadOnly")}} object (which is identical to the source point). ## Examples ### Creating a 2D point This sample creates a 2D point, specifying an inline object that includes the values to use for {{domxref("DOMPointReadOnly.x", "x")}} and {{domxref("DOMPointReadOnly.y", "y")}}. The `z` and `w` properties are allowed to keep their default values (`0` and `1` respectively). ```js const point2D = DOMPointReadOnly.fromPoint({ x: 25, y: 25 }); ``` ### Creating a 3D point using an existing point This example creates a point, `origPoint`, of type {{domxref("DOMPoint")}}, using {{domxref("DOMPoint.DOMPoint", "new DOMPoint()")}}. That point is then used as the input for `fromPoint()` to create a new point, `newPoint`. ```js const origPoint = new DOMPoint(25, 25, 100, 0.5); const newPoint = DOMPointReadOnly.fromPoint(origPoint); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/rtcicecandidatepairstats/index.md
--- title: RTCIceCandidatePairStats slug: Web/API/RTCIceCandidatePairStats page-type: web-api-interface browser-compat: api.RTCStatsReport.type_candidate-pair --- {{APIRef("WebRTC")}} The **`RTCIceCandidatePairStats`** dictionary of the [WebRTC API](/en-US/docs/Web/API/WebRTC_API) is used to report statistics that provide insight into the quality and performance of an {{domxref("RTCPeerConnection")}} while connected and configured as described by the specified pair of {{Glossary("ICE")}} candidates. The statistics can be obtained by iterating the {{domxref("RTCStatsReport")}} returned by {{domxref("RTCPeerConnection.getStats()")}} until you find an entry with the [`type`](#type) of `"candidate-pair"`. ## Instance properties - {{domxref("RTCIceCandidatePairStats.availableIncomingBitrate", "availableIncomingBitrate")}} {{optional_inline}} - : Provides a value representing the available inbound capacity of the network by reporting the total number of bits per second available for all of the candidate pair's incoming {{Glossary("RTP")}} streams. This does not take into account the size of the {{Glossary("IP")}} overhead, nor any other transport layers such as {{Glossary("TCP")}} or {{Glossary("UDP")}}. - {{domxref("RTCIceCandidatePairStats.availableOutgoingBitrate", "availableOutgoingBitrate")}} {{optional_inline}} - : Provides an informative value representing the available outbound capacity of the network by reporting the total number of bits per second available for all of the candidate pair's outgoing {{Glossary("RTP")}} streams. This does not take into account the size of the {{Glossary("IP")}} overhead, nor any other transport layers such as {{Glossary("TCP")}} or {{Glossary("UDP")}}. - {{domxref("RTCIceCandidatePairStats/bytesReceived", "bytesReceived")}} {{optional_inline}} - : The total number of payload bytes received (that is, the total number of bytes received minus any headers, padding, or other administrative overhead) on this candidate pair so far. - {{domxref("RTCIceCandidatePairStats.bytesSent", "bytesSent")}} {{optional_inline}} - : The total number of payload bytes sent (that is, the total number of bytes sent minus any headers, padding, or other administrative overhead) so far on this candidate pair. - {{domxref("RTCIceCandidatePairStats.currentRoundTripTime", "currentRoundTripTime")}} {{optional_inline}} - : A floating-point value indicating the total time, in seconds, that elapsed between the most recently-sent STUN request and the response being received. This may be based upon requests that were involved in confirming permission to open the connection. - {{domxref("RTCIceCandidatePairStats.lastPacketReceivedTimestamp", "lastPacketReceivedTimestamp")}} {{optional_inline}} - : A {{domxref("DOMHighResTimeStamp")}} value indicating the time at which the last packet was received by the local peer from the remote peer for this candidate pair. Timestamps are not recorded for STUN packets. - {{domxref("RTCIceCandidatePairStats.lastPacketSentTimestamp", "lastPacketSentTimestamp")}} {{optional_inline}} - : A {{domxref("DOMHighResTimeStamp")}} value indicating the time at which the last packet was sent from the local peer to the remote peer for this candidate pair. Timestamps are not recorded for STUN packets. - {{domxref("RTCIceCandidatePairStats.localCandidateId", "localCandidateId")}} {{optional_inline}} - : The unique ID string corresponding to the {{domxref("RTCIceCandidate")}} from the data included in the {{domxref("RTCIceCandidateStats")}} object providing statistics for the candidate pair's local candidate. - {{domxref("RTCIceCandidatePairStats.nominated", "nominated")}} {{optional_inline}} - : A Boolean value which, if `true`, indicates that the candidate pair described by this object is one which has been proposed for use, and will be (or was) used if its priority is the highest among the nominated candidate pairs. See {{RFC(5245, "", "7.1.3.2.4")}} for details. - {{domxref("RTCIceCandidatePairStats.remoteCandidateId", "remoteCandidateId")}} {{optional_inline}} - : The unique ID string corresponding to the remote candidate from which data was taken to construct the `RTCIceCandidateStats` object describing the remote end of the connection. - {{domxref("RTCIceCandidatePairStats.requestsReceived", "requestsReceived")}} {{optional_inline}} - : The total number of connectivity check requests that have been received, including retransmissions. This value includes both connectivity checks and STUN consent checks. - {{domxref("RTCIceCandidatePairStats.requestsSent", "requestsSent")}} {{optional_inline}} - : The total number of connectivity check requests that have been sent, _not_ including retransmissions. - {{domxref("RTCIceCandidatePairStats.responsesReceived", "responsesReceived")}} {{optional_inline}} - : The total number of connectivity check responses that have been received. - {{domxref("RTCIceCandidatePairStats.responsesSent", "responsesSent")}} {{optional_inline}} - : The total number of connectivity check responses that have been sent. This includes both connectivity check requests and STUN consent requests. - {{domxref("RTCIceCandidatePairStats.state", "state")}} {{optional_inline}} - : A string which indicates the state of the connection between the two candidates. - {{domxref("RTCIceCandidatePairStats.totalRoundTripTime", "totalRoundTripTime")}} {{optional_inline}} - : A floating-point value indicating the total time, in seconds, that has elapsed between sending STUN requests and receiving responses to them, for all such requests made to date on this candidate pair. This includes both connectivity check and consent check requests. You can compute the average round trip time (RTT) by dividing this value by {{domxref("RTCIceCandidatePairStats.responsesReceived", "responsesReceived")}}. - {{domxref("RTCIceCandidatePairStats.transportId", "transportId")}} {{optional_inline}} - : A string that uniquely identifies the {{domxref("RTCIceTransport")}} that was inspected to obtain the transport-related statistics (as found in {{domxref("RTCTransportStats")}}) used in generating this object. ### Common instance properties The following properties are common to all WebRTC statistics objects. <!-- RTCStats --> - {{domxref("RTCIceCandidatePairStats.id", "id")}} - : A string that uniquely identifies the object that is being monitored to produce this set of statistics. - {{domxref("RTCIceCandidatePairStats.timestamp", "timestamp")}} - : A {{domxref("DOMHighResTimeStamp")}} object indicating the time at which the sample was taken for this statistics object. - {{domxref("RTCIceCandidatePairStats.type", "type")}} - : A string with the value `"candidate-pair"`, indicating the type of statistics that the object contains. ### Deprecated properties The following properties have been removed from the specification and should no longer be used. You should update any existing code to avoid using them as soon as is practical. Check the [compatibility table](#browser_compatibility) for details on which browsers support them and in which versions. - {{domxref("RTCIceCandidatePairStats.priority", "priority")}} {{Deprecated_Inline}} {{optional_inline}} {{non-standard_inline}} - : An integer value indicating the candidate pair's priority. - {{domxref("RTCIceCandidatePairStats.readable", "readable")}} {{Deprecated_Inline}} {{optional_inline}} {{Non-standard_Inline}} - : A Boolean value indicating whether or not data can be sent over the connection described by the candidate pair. - {{domxref("RTCIceCandidatePairStats.writable", "writable")}} {{Deprecated_Inline}} {{optional_inline}} {{Non-standard_Inline}} - : A Boolean value indicating whether or not data can be received on the connection described by the candidate pair. ### Non-standard properties - {{domxref("RTCIceCandidatePairStats.selected", "selected")}} {{Non-standard_Inline}} {{optional_inline}} - : A Firefox-specific Boolean value which is `true` if the candidate pair described by this object is the one currently in use. The spec-compliant way to determine the selected candidate pair is to look for a stats object of type `transport`, which is an {{domxref("RTCTransportStats")}} object. That object's {{domxref("RTCTransportStats.selectedCandidatePairId", "selectedCandidatePairId")}} property indicates whether or not the specified transport is the one being used. ## Usage notes The currently-active ICE candidate pair—if any—can be obtained by calling the {{domxref("RTCIceTransport")}} method {{domxref("RTCIceTransport.getSelectedCandidatePair", "getSelectedCandidatePair()")}}, which returns an {{domxref("RTCIceCandidatePair")}} object, or `null` if there isn't a pair selected. The active candidate pair describes the current configuration of the two ends of the {{domxref("RTCPeerConnection")}}. Any candidate pair that isn't the active pair of candidates for a transport gets deleted if the {{domxref("RTCIceTransport")}} performs an ICE restart, at which point the {{domxref("RTCIceTransport.state", "state")}} of the ICE transport returns to `new` and negotiation starts once again. For more information, see [ICE restart](/en-US/docs/Web/API/WebRTC_API/Session_lifetime#ice_restart). ## Example This example computes the average time elapsed between connectivity checks. ```js if (rtcStats && rtcStats.type === "candidate-pair") { let elapsed = (rtcStats.lastRequestTimestamp - rtcStats.firstRequestTimestamp) / rtcStats.requestsSent; console.log(`Average time between ICE connectivity checks: ${elapsed} ms.`); } ``` The code begins by looking at `rtcStats` to see if its {{domxref("RTCIceCandidatePairStats.type", "type")}} is `candidate-pair`. If it is, then we know that `rtcStats` is in fact an {{domxref("RTCIceCandidatePairStats")}} object. We can then compute the average time elapsed between STUN connectivity checks and log that information. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/rtcicecandidatepairstats
data/mdn-content/files/en-us/web/api/rtcicecandidatepairstats/transportid/index.md
--- title: "RTCIceCandidatePairStats: transportId property" short-title: transportId slug: Web/API/RTCIceCandidatePairStats/transportId page-type: web-api-instance-property browser-compat: api.RTCStatsReport.type_candidate-pair.transportId --- {{APIRef("WebRTC")}} The **`transportId`** property uniquely identifies the {{domxref("RTCIceTransport")}} that was inspected to obtain the transport-related statistics contained in the {{domxref("RTCIceCandidatePairStats")}} object. ## Value A string which uniquely identifies the `RTCIceTransport` object from which the transport-related data was obtained for the statistics contained in this {{domxref("RTCIceCandidatePairStats")}} object. The transport-related statistics come from the {{domxref("RTCTransportStats")}} dictionary's properties. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/rtcicecandidatepairstats
data/mdn-content/files/en-us/web/api/rtcicecandidatepairstats/lastpacketreceivedtimestamp/index.md
--- title: "RTCIceCandidatePairStats: lastPacketReceivedTimestamp property" short-title: lastPacketReceivedTimestamp slug: Web/API/RTCIceCandidatePairStats/lastPacketReceivedTimestamp page-type: web-api-instance-property browser-compat: api.RTCStatsReport.type_candidate-pair.lastPacketReceivedTimestamp --- {{APIRef("WebRTC")}} The {{domxref("RTCIceCandidatePairStats")}} property **`lastPacketReceivedTimestamp`** indicates the time at which the connection described by the candidate pair last received a packet. {{Glossary("STUN")}} packets are not included. ## Value A {{domxref("DOMHighResTimeStamp")}} object indicating the timestamp at which the connection described by pair of candidates last received a packet, STUN packets excluded. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/rtcicecandidatepairstats
data/mdn-content/files/en-us/web/api/rtcicecandidatepairstats/selected/index.md
--- title: "RTCIceCandidatePairStats: selected property" short-title: selected slug: Web/API/RTCIceCandidatePairStats/selected page-type: web-api-instance-property browser-compat: api.RTCIceCandidatePairStats.selected --- {{APIRef("WebRTC")}}{{non-standard_header}} The _non-standard_, Firefox-specific {{domxref("RTCIceCandidatePairStats")}} property **`selected`** indicates whether or not the candidate pair described by the object is the one currently being used to communicate with the remote peer. ## Syntax ```js-nolint icpStats.selected ``` ### Value A Firefox-specific Boolean value which is `true` if the candidate pair described by this object is the one currently in use. In any other browser, you can determine the selected candidate pair by looking for a stats object of type `transport`, which is an {{domxref("RTCTransportStats")}} object. That object's {{domxref("RTCTransportStats.selectedCandidatePairId", "selectedCandidatePairId")}} property indicates whether or not the specified transport is the one being used. ## Example The function shown in this example identifies the currently-selected candidate pair from a statistics report by first iterating over each report, looking for a `transport` report; when one is found, that transport's {{domxref("RTCTransportStats.selectedCandidatePairId", "selectedCandidatePairId")}} is used to get the {{domxref("RTCIceCandidatePair")}} describing the connection. If that fails, then the second section iterates over the reports, looking for a `candidate-pair` record whose Firefox-specific {{domxref("RTCIceCandidatePairStats.selected", "selected")}} property is `true`. This candidate pair is then returned as the currently-selected one. ```js function getCurrentCandidatePair(statsResults) { statsResults.forEach((report) => { if (report.type === "transport") { currentPair = statsResults.get(report.selectedCandidatePairId); } }); if (!currentPair) { statsResults.forEach((report) => { if (report.type === "candidate-pair" && report.selected) { currentPair = report; } }); } return currentPair; } ``` ## Specifications Not part of any specification. This property is unique to Firefox. ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/rtcicecandidatepairstats
data/mdn-content/files/en-us/web/api/rtcicecandidatepairstats/totalroundtriptime/index.md
--- title: "RTCIceCandidatePairStats: totalRoundTripTime property" short-title: totalRoundTripTime slug: Web/API/RTCIceCandidatePairStats/totalRoundTripTime page-type: web-api-instance-property browser-compat: api.RTCStatsReport.type_candidate-pair.totalRoundTripTime --- {{APIRef("WebRTC")}} The {{domxref("RTCIceCandidatePairStats")}} dictionary's **`totalRoundTripTime`** property is the total time that has elapsed between sending {{Glossary("STUN")}} requests and receiving the responses, for all such requests that have been made so far on the pair of candidates described by this `RTCIceCandidatePairStats` object. This value includes both connectivity check and consent check requests. ## Value This floating-point value indicates the total number of seconds which have elapsed between sending out STUN connectivity and consent check requests and receiving their responses, for all such requests made so far on the connection described by this candidate pair. You can calculate the average round-trip time (RTT) by dividing this value by the value of the {{domxref("RTCIceCandidatePairStats.responsesReceived", "responsesReceived")}} property: ```js rtt = rtcIceCandidatePairStats.totalRoundTripTime / rtcIceCandidatePairStats.responsesReceived; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/rtcicecandidatepairstats
data/mdn-content/files/en-us/web/api/rtcicecandidatepairstats/bytesreceived/index.md
--- title: "RTCIceCandidatePairStats: bytesReceived property" short-title: bytesReceived slug: Web/API/RTCIceCandidatePairStats/bytesReceived page-type: web-api-instance-property browser-compat: api.RTCStatsReport.type_candidate-pair.bytesReceived --- {{APIRef("WebRTC")}} The {{domxref("RTCIceCandidatePairStats")}} property **`bytesReceived`** indicates the total number of payload bytes—that is, bytes which aren't overhead such as headers or padding—that have been received to date on the connection described by the candidate pair. The {{domxref("RTCIceCandidatePairStats.bytesSent", "bytesSent")}} property reports the number of bytes sent so far on the described connection. ## Value An integer value indicating the total number of bytes received so far on the connection described by this candidate pair. Only data bytes are counted; overhead such as padding, headers, and the like are not included in this count. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/rtcicecandidatepairstats
data/mdn-content/files/en-us/web/api/rtcicecandidatepairstats/readable/index.md
--- title: "RTCIceCandidatePairStats: readable property" short-title: readable slug: Web/API/RTCIceCandidatePairStats/readable page-type: web-api-instance-property status: - deprecated - non-standard browser-compat: api.RTCIceCandidatePairStats.readable --- {{APIRef("WebRTC")}}{{Deprecated_Header}}{{Non-standard_Header}} The _obsolete_ {{domxref("RTCIceCandidatePairStats")}} property **`readable`** reports whether or not the connection described by the candidate pair has received at least one valid incoming ICE request. ## Value A Boolean value which is `true` if the connection described by this candidate pair has received at least one valid ICE request, and is therefore ready to be read from. > **Note:** This property was removed from the specification in early 2017 > because you can determine whether or not the connection is readable by checking to see > if {{domxref("RTCIceCandidatePairStats.requestsReceived", "requestsReceived")}} is > greater than 0: > > ```js > if (icpStats.requestsReceived > 0) { > /* at least one ICE request has been received */ > } > ``` ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/rtcicecandidatepairstats
data/mdn-content/files/en-us/web/api/rtcicecandidatepairstats/remotecandidateid/index.md
--- title: "RTCIceCandidatePairStats: remoteCandidateId property" short-title: remoteCandidateId slug: Web/API/RTCIceCandidatePairStats/remoteCandidateId page-type: web-api-instance-property browser-compat: api.RTCStatsReport.type_candidate-pair.remoteCandidateId --- {{APIRef("WebRTC")}} The {{domxref("RTCIceCandidatePairStats")}} property **`remoteCandidateId`** is a string that uniquely identifies the remote {{Glossary("ICE")}} candidate which was analyzed to generate the {{domxref("RTCIceCandidateStats")}} used to compute the statistics for this pair of candidates. ## Value A string uniquely identifies the remote {{Glossary("ICE")}} candidate—that is, the candidate describing a configuration for the remote peer—which is represented by the remote end of these statistics. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/rtcicecandidatepairstats
data/mdn-content/files/en-us/web/api/rtcicecandidatepairstats/responsesreceived/index.md
--- title: "RTCIceCandidatePairStats: responsesReceived property" short-title: responsesReceived slug: Web/API/RTCIceCandidatePairStats/responsesReceived page-type: web-api-instance-property browser-compat: api.RTCStatsReport.type_candidate-pair.responsesReceived --- {{APIRef("WebRTC")}} The **`responsesReceived`** property in the {{domxref("RTCIceCandidatePairStats")}} dictionary indicates the total number of {{Glossary("STUN")}} connectivity check responses that have been received on the connection described by this pair of candidates. ## Value An integer value which specifies the number of STUN connectivity request responses that have been received on the connection described by this pair of candidates so far. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/rtcicecandidatepairstats
data/mdn-content/files/en-us/web/api/rtcicecandidatepairstats/writable/index.md
--- title: "RTCIceCandidatePairStats: writable property" short-title: writable slug: Web/API/RTCIceCandidatePairStats/writable page-type: web-api-instance-property status: - deprecated - non-standard browser-compat: api.RTCIceCandidatePairStats.writable --- {{APIRef("WebRTC")}}{{Deprecated_Header}}{{Non-standard_Header}} The _obsolete_ {{domxref("RTCIceCandidatePairStats")}} property **`writable`** reports whether or not the connection described by the candidate pair is writable. ## Value A Boolean value which is `true` if the connection described by this candidate pair has received acknowledgement of receipt (ACK) for at least one ICE request _and_ that {{Glossary("STUN")}} consent hasn't expired. > **Note:** This property was removed from the specification in early 2017 > because you can determine whether or not an incoming ICE request is available to read > by checking to see if {{domxref("RTCIceCandidatePairStats.responsesReceived", "responsesReceived")}} is greater than 0 and that the time specified by > {{domxref("RTCIceCandidatePairStats.consentExpiredTimestamp", "consentExpiredTimestamp")}} has not passed: > > ```js > if ( > icpStats.responsesReceived > 0 && > icpStats.consentExpiredTimestamp < performance.now() > ) { > /* at least one ICE response has been received */ > } > ``` ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/rtcicecandidatepairstats
data/mdn-content/files/en-us/web/api/rtcicecandidatepairstats/currentroundtriptime/index.md
--- title: "RTCIceCandidatePairStats: currentRoundTripTime property" short-title: currentRoundTripTime slug: Web/API/RTCIceCandidatePairStats/currentRoundTripTime page-type: web-api-instance-property browser-compat: api.RTCStatsReport.type_candidate-pair.currentRoundTripTime --- {{APIRef("WebRTC")}} The {{domxref("RTCIceCandidatePairStats")}} property **`currentRoundTripTime`** is a floating-point value indicating the number of seconds it takes for data to be sent by this peer to the remote peer and back over the connection described by this pair of {{Glossary("ICE")}} candidates. ## Syntax ```js-nolint rtt = rtcIceCandidatePairStats.currentRoundTripTime ``` ### Value A floating-point value indicating the round-trip time, in seconds for the connection described by the pair of candidates for which this `RTCIceCandidatePairStats` object offers statistics. This value is computed by observing the time that elapsed between the most recent {{Glossary("STUN")}} request being sent to the remote peer and the response to that request arriving. This information may come from ongoing STUN connectivity checks as well as from consent requests made when the connection was initially being opened. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/rtcicecandidatepairstats
data/mdn-content/files/en-us/web/api/rtcicecandidatepairstats/requestsreceived/index.md
--- title: "RTCIceCandidatePairStats: requestsReceived property" short-title: requestsReceived slug: Web/API/RTCIceCandidatePairStats/requestsReceived page-type: web-api-instance-property browser-compat: api.RTCStatsReport.type_candidate-pair.requestsReceived --- {{APIRef("WebRTC")}} The {{domxref("RTCIceCandidatePairStats")}} dictionary's **`requestsReceived`** property indicates the total number of {{Glossary("STUN")}} connectivity check requests that have been received so far on the connection described by this pairing of candidates. ## Value An integer value which specifies the number of STUN connectivity and/or consent requests that have been received to date on the connection described by this pair of {{Glossary("ICE")}} candidates. Because there's no way to tell the difference between requests made to check connectivity and requests made to check consent, the returned figure includes both. > **Note:** The reported number of requests includes retransmissions. If a > request had to be repeated due to network issues, it will be counted multiple times > here. This differs from {{domxref("RTCIceCandidatePairStats.requestsSent", "requestsSent")}}, which _does not_ include retransmisions. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/rtcicecandidatepairstats
data/mdn-content/files/en-us/web/api/rtcicecandidatepairstats/nominated/index.md
--- title: "RTCIceCandidatePairStats: nominated property" short-title: nominated slug: Web/API/RTCIceCandidatePairStats/nominated page-type: web-api-instance-property browser-compat: api.RTCStatsReport.type_candidate-pair.nominated --- {{APIRef("WebRTC")}} The {{domxref("RTCIceCandidatePairStats")}} property **`nominated`** specifies whether or not the candidate pair described by the underlying `RTCIceCandidatePair` has been nominated to be used as the configuration for the WebRTC connection. ## Value A Boolean value which is set to `true` by the ICE layer if the controlling user agent has indicated that the candidate pair should be used to configure the WebRTC connection between the two peers. > **Note:** If more than one candidate pair are nominated at the same > time, the one whose priority is higher will be selected for use. Once a candidate pair has been nominated and the two peers have each reconfigured themselves to use the specified configuration, the ICE negotiation process can potentially end (or it can continue, to allow the connection to adapt to changing conditions). ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/rtcicecandidatepairstats
data/mdn-content/files/en-us/web/api/rtcicecandidatepairstats/availableoutgoingbitrate/index.md
--- title: "RTCIceCandidatePairStats: availableOutgoingBitrate property" short-title: availableOutgoingBitrate slug: Web/API/RTCIceCandidatePairStats/availableOutgoingBitrate page-type: web-api-instance-property browser-compat: api.RTCStatsReport.type_candidate-pair.availableOutgoingBitrate --- {{APIRef("WebRTC")}} The {{domxref("RTCIceCandidatePairStats")}} property **`availableOutgoingBitrate`** returns a value indicative of the available outbound capacity of the network connection represented by the candidate pair. The higher the value, the more bandwidth you can assume is available for outgoing data. You can get the incoming available bitrate from {{domxref("RTCIceCandidatePairStats.availableIncomingBitrate", "availableIncomingBitrate")}}. ## Value A floating-point value which approximates the amount of available bandwidth for outgoing data on the network connection described by the `RTCIceCandidatePair`. The value is reported in bits per second and is computed over a 1-second interval. The returned value is `undefined` in each of the following situations: - The underlying implementation doesn't support computing a sender-side estimate of the outgoing bit rate. - The {{domxref("RTCIceCandidatePair")}} described by this object has never been used. - The candidate pair was once in use, but no longer is. The value returned is calculated by adding up the available bit rate for every {{Glossary("RTP")}} stream using the connection described by this candidate pair. The returned value doesn't take into account overhead introduced by underlying protocols, including IP, UDP, or TCP. > **Note:** The returned value is computed using a method similar—but not > identical—to the Transport Independent Application Specific Maximum (TIAS) described > in {{RFC(3890, "", "6.2")}}. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/rtcicecandidatepairstats
data/mdn-content/files/en-us/web/api/rtcicecandidatepairstats/localcandidateid/index.md
--- title: "RTCIceCandidateStats: localCandidateId property" short-title: localCandidateId slug: Web/API/RTCIceCandidatePairStats/localCandidateId page-type: web-api-instance-property browser-compat: api.RTCStatsReport.type_candidate-pair.localCandidateId --- {{APIRef("WebRTC")}} The {{domxref("RTCIceCandidatePairStats")}} property **`localCandidateId`** is a string that uniquely identifies the local {{Glossary("ICE")}} candidate which was analyzed to generate the {{domxref("RTCIceCandidateStats")}} used to compute the statistics for this pair of candidates. ## Value A string giving a unique identifier for the local {{domxref("RTCIceCandidate")}} for the connection described by this `RTCIceCandidatePairStats` object. This candidate is the source of one of the two {{domxref("RTCIceCandidateStats")}} objects that were used to compute the contents of this {{domxref("RTCIceCandidatePairStats")}} object. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/rtcicecandidatepairstats
data/mdn-content/files/en-us/web/api/rtcicecandidatepairstats/id/index.md
--- title: "RTCIceCandidatePairStats: id property" short-title: id slug: Web/API/RTCIceCandidatePairStats/id page-type: web-api-instance-property browser-compat: api.RTCStatsReport.type_candidate-pair.id --- {{APIRef("WebRTC")}} The **`id`** property of the {{domxref("RTCIceCandidatePairStats")}} dictionary is a string that uniquely identifies the object for which this object provides statistics. Using the `id`, you can correlate this statistics object with others, in order to monitor statistics over time for a given WebRTC object, such as an {{domxref("RTCPeerConnection")}}, or an {{domxref("RTCDataChannel")}}. ## Value A string that uniquely identifies the object for which this `RTCIceCandidatePairStats` object provides statistics. The format of the ID string is not defined by the specification, so you cannot reliably make any assumptions about the contents of the string, or assume that the format of the string will remain unchanged for a given object type. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/rtcicecandidatepairstats
data/mdn-content/files/en-us/web/api/rtcicecandidatepairstats/state/ice-check-list-states.svg
<svg xmlns="http://www.w3.org/2000/svg" viewBox="367.5 127.5 561 321" width="561" height="321"><defs><marker orient="auto" overflow="visible" markerUnits="strokeWidth" id="a" stroke-linejoin="miter" stroke-miterlimit="10" viewBox="-1 -4 10 8" markerWidth="10" markerHeight="8" color="#000"><path d="M8 0 0-3v6z" fill="currentColor" stroke="currentColor"/></marker></defs><g fill="none"><text transform="rotate(-45 701.527 -758.933)" fill="#000"> <tspan font-family="Arial" font-size="14" font-weight="400" x="0" y="13">failure</tspan> </text><path fill="#ededff" d="M368 128h128v48H368z"/><path stroke="#000" stroke-linecap="round" stroke-linejoin="round" d="M368 128h128v48H368z"/><text transform="translate(373 142.5)" fill="#000"> <tspan font-family="Courier New" font-size="16" font-weight="400" x="30.195" y="13">frozen</tspan> </text><path fill="#ededff" d="M368 264h128v48H368z"/><path stroke="#000" stroke-linecap="round" stroke-linejoin="round" d="M368 264h128v48H368z"/><text transform="translate(373 278.5)" fill="#000"> <tspan font-family="Courier New" font-size="16" font-weight="400" x="25.395" y="13">waiting</tspan> </text><path fill="#ededff" d="M584 264h128v48H584z"/><path stroke="#000" stroke-linecap="round" stroke-linejoin="round" d="M584 264h128v48H584z"/><text transform="translate(589 278.5)" fill="#000"> <tspan font-family="Courier New" font-size="16" font-weight="400" x="6.191" y="13">in-progress</tspan> </text><path fill="#ededff" d="M800 264h128v48H800z"/><path stroke="#000" stroke-linecap="round" stroke-linejoin="round" d="M800 264h128v48H800z"/><text transform="translate(805 278.5)" fill="#000"> <tspan font-family="Courier New" font-size="16" font-weight="400" x="30.195" y="13">failed</tspan> </text><path fill="#ededff" d="M584 400h128v48H584z"/><path stroke="#000" stroke-linecap="round" stroke-linejoin="round" d="M584 400h128v48H584z"/><text transform="translate(589 414.5)" fill="#000"> <tspan font-family="Courier New" font-size="16" font-weight="400" x="15.793" y="13">succeeded</tspan> </text><path marker-end="url(#a)" stroke="#000" stroke-linecap="round" stroke-linejoin="round" d="M432 176v78.1m64 33.9h78.1m137.9 0h78.1M648 312v78.1"/><text transform="translate(440.606 208.923)" fill="#000"> <tspan font-family="Arial" font-size="14" font-weight="400" x="0" y="13">unfreeze</tspan> </text><text transform="rotate(-45 594.07 -497.953)" fill="#000"> <tspan font-family="Arial" font-size="14" font-weight="400" x="0" y="13">check pair</tspan> </text><text transform="translate(655.515 345.869)" fill="#000"> <tspan font-family="Arial" font-size="14" font-weight="400" x="0" y="13">success</tspan> </text></g></svg>
0
data/mdn-content/files/en-us/web/api/rtcicecandidatepairstats
data/mdn-content/files/en-us/web/api/rtcicecandidatepairstats/state/index.md
--- title: "RTCIceCandidatePairStats: state property" short-title: state slug: Web/API/RTCIceCandidatePairStats/state page-type: web-api-instance-property browser-compat: api.RTCStatsReport.type_candidate-pair.state --- {{APIRef("WebRTC")}} The **`state`** property is a string that indicates the state of the checklist of which the candidate pair is a member. ## Value A string whose value is one of the following: - `failed` - : A check for this pair has been performed but failed. A failure can occur either because no response was received or because the response indicated that an unrecoverable error occurred. - `frozen` - : No check has been performed yet for this candidate pair, and performing the check is blocked until another check is successful. Once that check has succeeded, this pair will unfreeze and move into the `waiting` state. - `in-progress` - : A check has been initiated for this pair, but the check's transaction is still in progress. - `succeeded` - : A check for this pair has been completed successfully. - `waiting` - : This pair has not yet been checked, but the check can be performed as soon as this pair is the highest priority pair remaining in the `waiting` state. ## ICE check lists During ICE negotiation, the ICE layer builds up a _checklist_, which is a list of potential pairings of ICE candidates. Each pair has a state, represented by a string literal. ![A diagram showing how ICE candidate pairs change state as the checklist is analyzed](ice-check-list-states.svg) When a candidate pair is added to the checklist, it begins in the `frozen` state. As soon as there are no checks ongoing that block the pair from being analyzed, it is unfrozen and moves into the `waiting` state. This may happen immediately upon being added to the checklist. Each time a candidate pair is checked, the next-highest priority candidate pair remaining on the checklist moves from the `waiting` state to the `in-progress` state, and its check begins. If the check fails for any reason, the pair moves into its final state, `failed`. If the check succeeds, the pair ends up in the `succeeded` state. The ICE checklist state for any given pair of ICE candidates can be found in the corresponding `state` property. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/rtcicecandidatepairstats
data/mdn-content/files/en-us/web/api/rtcicecandidatepairstats/lastpacketsenttimestamp/index.md
--- title: "RTCIceCandidateStats: lastPacketSentTimestamp property" short-title: lastPacketSentTimestamp slug: Web/API/RTCIceCandidatePairStats/lastPacketSentTimestamp page-type: web-api-instance-property browser-compat: api.RTCStatsReport.type_candidate-pair.lastPacketSentTimestamp --- {{APIRef("WebRTC")}} The {{domxref("RTCIceCandidatePairStats")}} property **`lastPacketSentTimestamp`** indicates the time at which the connection described by the candidate pair last sent a packet, not including {{Glossary("STUN")}} packets. ## Value A {{domxref("DOMHighResTimeStamp")}} object indicating the timestamp at which the connection described by pair of candidates last sent a packet, STUN packets excluded. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/rtcicecandidatepairstats
data/mdn-content/files/en-us/web/api/rtcicecandidatepairstats/type/index.md
--- title: "RTCIceCandidatePairStats: type property" short-title: type slug: Web/API/RTCIceCandidatePairStats/type page-type: web-api-instance-property browser-compat: api.RTCStatsReport.type_candidate-pair.type --- {{APIRef("WebRTC")}} The **`type`** property of the {{domxref("RTCIceCandidatePairStats")}} dictionary is a string with the value `"candidate-pair"`. Different statistics are obtained by iterating the {{domxref("RTCStatsReport")}} object returned by a call to {{domxref("RTCPeerConnection.getStats()")}}. The type indicates the set of statistics available through the object in a particular iteration step. A value of `"candidate-pair"` indicates that the statistics available in the current step are those defined in {{domxref("RTCIceCandidatePairStats")}}. ## Value A string with the value `"candidate-pair"`. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/rtcicecandidatepairstats
data/mdn-content/files/en-us/web/api/rtcicecandidatepairstats/priority/index.md
--- title: "RTCIceCandidatePairStats: priority property" short-title: priority slug: Web/API/RTCIceCandidatePairStats/priority page-type: web-api-instance-property status: - deprecated - non-standard browser-compat: api.RTCStatsReport.type_candidate-pair.priority --- {{APIRef("WebRTC")}}{{deprecated_header}}{{non-standard_header}} The _obsolete_ {{domxref("RTCIceCandidatePairStats")}} property **`priority`** reports the priority of the candidate pair as an integer value. The higher the value, the more likely the WebRTC layer is to select the candidate pair when the time comes to establish (or re-establish) a connection between the two peers. ## Value An integer value indicating the priority of this pair of candidates as compared to other pairs on the same peer connection. The higher this value, the better the WebRTC layer thinks this pair of candidates is compared to the others, and the more likely a pair is to be selected for use. > **Note:** This property was removed from the specification as its value > cannot be guaranteed to be accurately represented in a JavaScript number. You can > calculate its value using the algorithm described in {{RFC(5245, "", "5.7.2")}} if > you need this information and can accept the risk that the result may not be entirely > accurate. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/rtcicecandidatepairstats
data/mdn-content/files/en-us/web/api/rtcicecandidatepairstats/timestamp/index.md
--- title: "RTCIceCandidatePairStats: timestamp property" short-title: timestamp slug: Web/API/RTCIceCandidatePairStats/timestamp page-type: web-api-instance-property browser-compat: api.RTCStatsReport.type_candidate-pair.timestamp --- {{APIRef("WebRTC")}} The **`timestamp`** property of the {{domxref("RTCIceCandidatePairStats")}} dictionary is a {{domxref("DOMHighResTimeStamp")}} object specifying the time at which the data in the object was sampled. ## Value A {{domxref("DOMHighResTimeStamp")}} value indicating the time at which the activity described by the statistics in this object was recorded, in milliseconds elapsed since the beginning of January 1, 1970, UTC. The value should be accurate to within a few milliseconds but may not be entirely precise, either because of hardware or operating system limitations or because of [fingerprinting](/en-US/docs/Glossary/Fingerprinting) protection in the form of reduced clock precision or accuracy. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/rtcicecandidatepairstats
data/mdn-content/files/en-us/web/api/rtcicecandidatepairstats/bytessent/index.md
--- title: "RTCIceCandidatePairStats: bytesSent property" short-title: bytesSent slug: Web/API/RTCIceCandidatePairStats/bytesSent page-type: web-api-instance-property browser-compat: api.RTCStatsReport.type_candidate-pair.bytesSent --- {{APIRef("WebRTC")}} The {{domxref("RTCIceCandidatePairStats")}} property **`bytesSent`** indicates the total number of payload bytes—that is, bytes which aren't overhead such as headers or padding—that have been sent so far on the connection described by the candidate pair. The {{domxref("RTCIceCandidatePairStats.bytesReceived", "bytesReceived")}} property reports the number of bytes received so far on the described connection. ## Syntax ```js-nolint sent = rtcIceCandidatePairStats.bytesSent ``` ### Value An integer value indicating the total number of bytes sent so far on the connection described by this candidate pair. Only data bytes are counted; overhead such as padding, headers, and the like are not included in this count. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/rtcicecandidatepairstats
data/mdn-content/files/en-us/web/api/rtcicecandidatepairstats/requestssent/index.md
--- title: "RTCIceCandidatePairStats: requestsSent property" short-title: requestsSent slug: Web/API/RTCIceCandidatePairStats/requestsSent page-type: web-api-instance-property browser-compat: api.RTCStatsReport.type_candidate-pair.requestsSent --- {{APIRef("WebRTC")}} The {{domxref("RTCIceCandidatePairStats")}} dictionary's **`requestsSent`** property indicates the total number of {{Glossary("STUN")}} connectivity check requests that have been sent so far on the connection described by this pair of candidates. ## Value An integer value which specifies the number of STUN connectivity requests that have been sent to date on the connection described by this pair of {{Glossary("ICE")}} candidates. > **Note:** The reported number of requests _does not_ include > retransmissions. If a request had to be repeated due to network issues, it will be > counted multiple times here. This differs from > {{domxref("RTCIceCandidatePairStats.requestsReceived", "requestsReceived")}}, which > _does_ include retransmissions. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/rtcicecandidatepairstats
data/mdn-content/files/en-us/web/api/rtcicecandidatepairstats/availableincomingbitrate/index.md
--- title: "RTCIceCandidatePairStats: availableIncomingBitrate property" short-title: availableIncomingBitrate slug: Web/API/RTCIceCandidatePairStats/availableIncomingBitrate page-type: web-api-instance-property browser-compat: api.RTCIceCandidatePairStats.availableIncomingBitrate --- {{APIRef("WebRTC")}} The {{domxref("RTCIceCandidatePairStats")}} property **`availableIncomingBitrate`** returns a value indicative of the available inbound capacity of the network connection represented by the candidate pair. The higher the value, the more bandwidth you can assume is available for incoming data. You can get the outgoing available bitrate from {{domxref("RTCIceCandidatePairStats.availableoutgoingBitrate", "availableoutgoingBitrate")}}. ## Syntax ```js-nolint availableIncomingBitrate = rtcIceCandidatePairStats.availableIncomingBitrate ``` ### Value A floating-point value which approximates the amount of available bandwidth for incoming data on the network connection described by the `RTCIceCandidatePair`. The value is reported in bits per second and is computed over a 1-second interval. The value returned is calculated by adding up the available bit rate for every {{Glossary("RTP")}} stream using the connection described by this candidate pair. The returned value doesn't take into account overhead introduced by underlying protocols, including IP, UDP, or TCP. > **Note:** The returned value is computed using a method similar—but not > identical—to the Transport Independent Application Specific Maximum (TIAS) described > in {{RFC(3890, "", "6.2")}}. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/rtcicecandidatepairstats
data/mdn-content/files/en-us/web/api/rtcicecandidatepairstats/responsessent/index.md
--- title: "RTCIceCandidatePairStats: responsesSent property" short-title: responsesSent slug: Web/API/RTCIceCandidatePairStats/responsesSent page-type: web-api-instance-property browser-compat: api.RTCStatsReport.type_candidate-pair.responsesSent --- {{APIRef("WebRTC")}} The {{domxref("RTCIceCandidatePairStats")}} dictionary's **`responsesSent`** property indicates the total number of {{Glossary("STUN")}} connectivity check responses that have been sent so far on the connection described by this pair of candidates. ## Value An integer value indicating the number of times a response has been sent to a {{Glossary("STUN")}} connectivity check request. > **Note:** Since it isn't possible to tell the difference between > connectivity check requests and consent requests, this value includes both. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/rtcrtpsender/index.md
--- title: RTCRtpSender slug: Web/API/RTCRtpSender page-type: web-api-interface browser-compat: api.RTCRtpSender --- {{APIRef("WebRTC")}} The **`RTCRtpSender`** interface provides the ability to control and obtain details about how a particular {{domxref("MediaStreamTrack")}} is encoded and sent to a remote peer. With it, you can configure the encoding used for the corresponding track, get information about the device's media capabilities, and so forth. You can also obtain access to an {{domxref("RTCDTMFSender")}} which can be used to send {{Glossary("DTMF")}} codes (to simulate the user pressing buttons on a telephone's dial pad) to the remote peer. ## Instance properties - {{domxref("RTCRtpSender.dtmf")}} {{ReadOnlyInline}} - : An {{domxref("RTCDTMFSender")}} which can be used to send {{Glossary("DTMF")}} tones using `telephone-event` payloads on the {{Glossary("RTP")}} session represented by the `RTCRtpSender` object. If `null`, the track and/or the connection doesn't support DTMF. Only audio tracks can support DTMF. - {{domxref("RTCRtpSender.track")}} {{ReadOnlyInline}} - : The {{domxref("MediaStreamTrack")}} which is being handled by the `RTCRtpSender`. If `track` is `null`, the `RTCRtpSender` doesn't transmit anything. - {{domxref("RTCRtpSender.transport")}} {{ReadOnlyInline}} - : The {{domxref("RTCDtlsTransport")}} over which the sender is exchanging the RTP and RTCP packets used to manage transmission of media and control data. This value is `null` until the transport is established. When bundling is in use, more than transceiver may be sharing the same transport object. - {{domxref("RTCRtpSender.transform")}} - : An {{domxref("RTCRtpScriptTransform")}}<!-- or {{domxref("SFrameTransform")}} --> is used to insert a transform stream ({{domxref("TransformStream")}}) running in a worker thread into the sender pipeline, allowing stream transforms to be applied to encoded video and audio frames after they are output by a codec, and before they are sent. ### Obsolete properties - `rtcpTransport` {{deprecated_inline}} - : This property has been removed; the RTP and RTCP transports have been combined into a single transport. Use the {{domxref("RTCRtpSender.transport", "transport")}} property instead. ## Static methods - {{domxref("RTCRtpSender.getCapabilities_static", "RTCRtpSender.getCapabilities()")}} - : Returns an object describing the system's capabilities for sending a specified kind of media data. ## Instance methods - {{domxref("RTCRtpSender.getParameters()")}} - : Returns an object describing the current configuration for the encoding and transmission of media on the `track`. - {{domxref("RTCRtpSender.getStats()")}} - : Returns a {{jsxref("Promise")}} which is fulfilled with a {{domxref("RTCStatsReport")}} which provides statistics data for all outbound streams being sent using this `RTCRtpSender`. - {{domxref("RTCRtpSender.setParameters()")}} - : Applies changes to parameters which configure how the `track` is encoded and transmitted to the remote peer. - {{domxref("RTCRtpSender.setStreams()")}} - : Sets the {{domxref("MediaStream")}}(s) associated with the {{domxref("RTCRtpSender.track", "track")}} being transmitted by this sender. - {{domxref("RTCRtpSender.replaceTrack()")}} - : Attempts to replace the track currently being sent by the `RTCRtpSender` with another track, without performing renegotiation. This method can be used, for example, to toggle between the front- and rear-facing cameras on a device. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - WebRTC API - {{domxref("RTCPeerConnection.addTrack()")}} - {{domxref("RTCPeerConnection.getSenders()")}} - {{domxref("RTCRtpReceiver")}}
0
data/mdn-content/files/en-us/web/api/rtcrtpsender
data/mdn-content/files/en-us/web/api/rtcrtpsender/getcapabilities_static/index.md
--- title: "RTCRtpSender: getCapabilities() static method" short-title: getCapabilities() slug: Web/API/RTCRtpSender/getCapabilities_static page-type: web-api-static-method browser-compat: api.RTCRtpSender.getCapabilities_static --- {{DefaultAPISidebar("WebRTC")}} The _static method_ **`RTCRtpSender.getCapabilities()`** returns an object describing the codec and header extension capabilities supported by the {{domxref("RTCRtpSender")}}. You can, similarly, obtain the capabilities of {{domxref("RTCRtpReceiver")}} objects on the device by calling the static function {{domxref("RTCRtpReceiver.getCapabilities_static", "RTCRtpReceiver.getCapabilities()")}}. ## Syntax ```js-nolint RTCRtpSender.getCapabilities(kind) ``` ### Parameters - `kind` - : A string indicating the type of media for which the browser's send capabilities are requested. The supported media kinds are: `audio` and `video`. ### Return value A new object that indicates what capabilities the browser has for sending the specified media kind over an {{domxref("RTCPeerConnection")}}. If the browser doesn't have any support for the given media `kind`, the returned value is `null`. The returned object has the following properties: - `codecs` - : An array of objects, each describing the basic capabilities of a single [media codec](/en-US/docs/Web/Media/Formats/WebRTC_codecs) supported by the {{domxref("RTCRtpSender")}}. > **Note:** The array contains special entries that represent the underlying components of the transport — these may be ignored if you're only interested in the actual codecs used for the media itself. > These are described below in the section [The codecs array](#the_codecs_array). Each codec object has the following properties: - `channels` {{optional_inline}} - : A positive integer value indicating the maximum number of channels supported by the codec; for example, a codec that supports only mono sound would have a value of 1; stereo codecs would have a 2, etc. - `clockRate` - : A positive integer specifying the codec's clock rate in Hertz (Hz). The IANA maintains a [list of codecs and their parameters](https://www.iana.org/assignments/rtp-parameters/rtp-parameters.xhtml#rtp-parameters-1), including their clock rates. - `mimeType` - : A string indicating the codec's MIME media type and subtype. The MIME type strings used by RTP differ from those used elsewhere. See {{RFC(3555, "", 4)}} for the complete IANA registry of these types. Also see [Codecs used by WebRTC](/en-US/docs/Web/Media/Formats/WebRTC_codecs) for details about potential codecs that might be referenced here. - `sdpFmtpLine` {{optional_inline}} - : A string giving the format specific parameters field from the `a=fmtp` line in the SDP which corresponds to the codec, if such a line exists. If there is no parameters field, this property is left out. - `headerExtensions` - : An array of objects, each providing the URI of a [header extension](https://datatracker.ietf.org/doc/html/rfc3550#section-5.3.1) supported for the current `kind` of media. Each object has the following property: - `uri` - : A string, specifying the URI of a header extension. The URI is formatted as described in {{RFC(5285)}}. ## Description As a static function, this is always called using the form: ```js capabilities = RTCRtpSender.getCapabilities("audio"); ``` The returned set of capabilities is the most optimistic possible list. It is entirely possible that certain combinations of options may fail to work when you actually try to use them. Calling `RTCRtpSender.getCapabilities()` doesn't prime the browser in any way to handle media. Nothing is loaded, fetched, or otherwise prepared. It's a means of determining what might be usable before starting to try to access media. Because the set of capabilities available tend to be stable for a length of time (people don't install and uninstall codecs and the like very often), the media capabilities can in whole or in part provide a cross-origin method for identifying a user. For that reason, in privacy-sensitive contexts, the browser may choose to obscure the capabilities; this might be done, for example, by leaving out rarely-used codec configurations. ### The codecs array The `codecs` array is an array of objects that describes a single codec and its basic capabilities. The browser will only report distinct capability combinations separately. If two sets of capabilities can be described as one, they will be. That means that, for instance, if there are two entries for the H.264 codec (as identified by the [`mimeType`](#mimetype) being "video/H264"), there are other values in the capabilities objects indicating how they're different in some way. There are three special entries that should always be present, representing underlying components of the transport. Those components are: - RED (REDundant Audio Data) - : The media type of an RED entry may vary due to there being several versions of it, but it will end with `red`, such as `video/red` or `video/fwdred`. The base RED standard can be found in {{RFC(2198)}}. There may be multiple entries for RED if different forms are supported; each will have a unique media type in that case. - FEC (Forward Error Correction) - : An FEC component handles error correction data; its media type may also vary due to there being advanced versions of the standard available, but it will always end with `fec`. One possible value is `video/ulpfec` (a generic error connection model). There may also be multiple FEC entries if more than one form is supported. - RTX (Retransmission) - : This component is responsible for retransmission of data; it's media type should be `video/rtx`. There will only be one entry for RTX, and it will not have an [`sdpFmtpLine`](#sdpfmtpline) property. These entries should be ignored if only codecs related to the media are of interest. ## Examples ### Feature support You can use [`Object.hasOwn()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwn) to check that `RTCRtpSender.getCapabilities()` is supported: ```html hidden <p id="log"></p> ``` ```js hidden const log = document.querySelector("#log"); ``` ```js log.textContent = `RTCRtpSender.getCapabilities() supported: ${Object.hasOwn( RTCRtpSender, "getCapabilities", )}`; ``` {{ EmbedLiveSample('Feature support', '100%', '30px') }} ### Checking support for a particular codec The function below returns a `true` or `false` indicating whether or not the device supports sending H.264 video on an {{domxref("RTCRtpSender")}}. > **Note:** Since `RTCRtpSender.getCapabilities()` actually only indicates _probable_ support. > So below H.264 support might still fail even after getting a positive response from this function. ```js function canSendH264() { let capabilities = RTCRtpSender.getCapabilities("video"); capabilities.codecs.forEach((codec) => { if (codec.mimeType === "video/H264") { return true; } }); return false; } ``` ### Getting all capabilities This code example shows how we might get all supported codecs and headers. The HTML defines a selection list for the two kinds of capabilities, and a log area. ```html <select id="kind"> <option value="audio">audio</option> <option value="video">video</option> </select> <textarea rows="40" cols="100" id="log"></textarea> ``` The JavaScript defines a function to log the capabilities for a particular "kind". This is called initially with the value `audio`. A listener updates the value when the selection list `kind` is changed. ```js const log = document.querySelector("#log"); const kindSelector = document.querySelector("#kind"); logMediaCapabilities("audio"); kindSelector.addEventListener("click", () => { log.textContent = ""; logMediaCapabilities(kindSelector.value); }); function logMediaCapabilities(kind) { const capabilities = RTCRtpSender.getCapabilities(`${kind}`); log.textContent += "Headers\n"; capabilities.headerExtensions.forEach((header) => { log.textContent += ` uri: ${header.uri}\n`; }); log.textContent += "\nCodecs\n"; capabilities.codecs.forEach((codec) => { log.textContent += ` mime type: ${codec.mimeType}\n`; log.textContent += ` channels: ${codec.channels}\n`; // max channels - e.g. 2 is stereo log.textContent += ` clockRate: ${codec.clockRate}\n`; // clock rate in Hz log.textContent += ` sdpFmtpLine: ${codec.sdpFmtpLine}\n`; // mime media type and subtype }); } ``` #### Result {{ EmbedLiveSample('Getting all capabilities', '100%', '500px') }} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/rtcrtpsender
data/mdn-content/files/en-us/web/api/rtcrtpsender/replacetrack/index.md
--- title: "RTCRtpSender: replaceTrack() method" short-title: replaceTrack() slug: Web/API/RTCRtpSender/replaceTrack page-type: web-api-instance-method browser-compat: api.RTCRtpSender.replaceTrack --- {{APIRef("WebRTC")}} The {{domxref("RTCRtpSender")}} method **`replaceTrack()`** replaces the track currently being used as the sender's source with a new {{domxref("MediaStreamTrack")}}. The new track must be of the same media kind (audio, video, etc.) and switching the track should not require negotiation. Among the use cases for `replaceTrack()` is the common need to switch between the rear- and front-facing cameras on a phone. With `replaceTrack()`, you can have a track object for each camera and switch between the two as needed. See the example [Switching cameras](#switching_cameras) below. ## Syntax ```js-nolint replaceTrack(newTrack) ``` ### Parameters - `newTrack` {{optional_inline}} - : A {{domxref("MediaStreamTrack")}} specifying the track with which to replace the `RTCRtpSender`'s current source track. The new track's {{domxref("MediaStreamTrack.kind", "kind")}} must be the same as the current track's, or the replace track request will fail. ### Return value A {{jsxref("Promise")}} which is fulfilled once the track has been successfully replaced. The promise is rejected if the track cannot be replaced for any reason; this is commonly because the change would require renegotiation of the codec, which is not allowed (see [Things that require negotiation](#things_that_require_negotiation)). If `newTrack` was omitted or was `null`, `replaceTrack()` stops the sender. No negotiation is required in this case. When the promise is fulfilled, the fulfillment handler receives a value of `undefined`. ### Exceptions If the returned promise is rejected, one of the following exceptions is provided to the rejection handler: - `InvalidModificationError` {{domxref("DOMException")}} - : Returned if replacing the `RTCRtpSender`'s current track with the new one would require negotiation. - `InvalidStateError` {{domxref("DOMException")}} - : Returned if the track on which this method was called is stopped rather than running. - {{jsxref("TypeError")}} - : Returned if the new track's `kind` doesn't match the original track. ## Usage notes ### Things that require negotiation Most track replacements can be done without renegotiation. In fact, even changes that seem huge can be done without requiring negotiation. However, some changes may require negotiation and thus fail `replaceTrack()`: - The new track has a resolution which is outside the bounds of the dimensions negotiated with the peer; however, most browser end points allow resolution changes. - The new track's frame rate is high enough to cause the codec's block rate to be exceeded. - The new track is a video track and its raw or pre-encoded state differs from that of the original track. - The new track is an audio track with a different number of channels from the original. - Media sources that have built-in encoders — such as hardware encoders — may not be able to provide the negotiated codec. Software sources may not implement the negotiated codec. ## Examples ### Switching video cameras ```js const localConnection = new RTCPeerConnection(); const remoteConnection = new RTCPeerConnection(); // Configuring these to use the WebRTC API can be explored at // https://developer.mozilla.org/en-US/docs/Web/API/WebRTC_API/Simple_RTCDataChannel_sample const connections = [localConnection, remoteConnection]; function setCamera(selectedCamera) { navigator.mediaDevices .getUserMedia({ video: { deviceId: { exact: selectedCamera, }, }, }) .then((stream) => { const [videoTrack] = stream.getVideoTracks(); connections.forEach((pc) => { const sender = pc .getSenders() .find((s) => s.track.kind === videoTrack.kind); console.log("Found sender:", sender); sender.replaceTrack(videoTrack); }); }) .catch((err) => { console.error(`Error happened: ${err}`); }); } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [WebRTC API](/en-US/docs/Web/API/WebRTC_API)
0
data/mdn-content/files/en-us/web/api/rtcrtpsender
data/mdn-content/files/en-us/web/api/rtcrtpsender/setparameters/index.md
--- title: "RTCRtpSender: setParameters() method" short-title: setParameters() slug: Web/API/RTCRtpSender/setParameters page-type: web-api-instance-method browser-compat: api.RTCRtpSender.setParameters --- {{APIRef("WebRTC API")}} The **`setParameters()`** method of the {{domxref("RTCRtpSender")}} interface applies changes the configuration of sender's {{domxref("RTCRtpSender.track", "track")}}, which is the {{domxref("MediaStreamTrack")}} for which the `RTCRtpSender` is responsible. In other words, `setParameters()` updates the configuration of the {{Glossary("RTP")}} transmission as well as the encoding configuration for a specific outgoing media track on the [WebRTC](/en-US/docs/Web/API/WebRTC_API) connection. ## Syntax ```js-nolint setParameters(parameters) ``` ### Parameters - `parameters` - : A parameters object previously obtained by calling the same sender's {{domxref("RTCRtpSender.getParameters", "getParameters()")}} method, with the desired changes to the sender's configuration parameters. These parameters include potential codecs that could be use for encoding the sender's {{domxref("RTCRtpSender.track", "track")}}. The available parameters are: - `encodings` - : An array of objects, each specifying the parameters for a single codec that could be used to encode the track's media. The properties of the objects include: - `active` - : Setting this value `true` (the default) causes this encoding to be sent, while `false` stops it from being sent and used (but does not cause the SSRC to be removed). - `dtx` {{Deprecated_Inline}} {{Non-standard_Inline}} - : Only used for an {{domxref("RTCRtpSender")}} whose {{domxref("MediaStreamTrack.kind", "kind")}} is `audio`, this property indicates whether or not to use discontinuous transmission (a feature by which a phone is turned off or the microphone muted automatically in the absence of voice activity). The value is taken either `enabled` or `disabled`. - `maxBitrate` - : A positive integer indicating the maximum number of bits per second that the user agent is allowed to grant to tracks encoded with this encoding. Other parameters may further constrain the bit rate, such as the value of `maxFramerate`, or the bandwidth available for the transport or physical network. The value is computed using the standard Transport Independent Application Specific Maximum (TIAS) bandwidth as defined by {{RFC(3890, "", "6.2.2")}}; this is the maximum bandwidth needed without considering protocol overheads from IP, TCP or UDP, and so forth. Note that the bitrate can be achieved in a number of ways, depending on the media and encoding. For example, for video a low bit rate might be achieved by dropping frames (a bitrate of zero might allow just one frame to be sent), while for audio the track might have to stop playing if the bitrate is too low for it to be sent. - `maxFramerate` - : A value specifying the maximum number of frames per second to allow for this encoding. - `priority` - : A string indicating the priority of the {{domxref("RTCRtpSender")}}, which may determine how the user agent allocates bandwidth between senders. Allowed values are `very-low`, `low` (default), `medium`, `high`. - `rid` - : A string which, if set, specifies an _RTP stream ID_ (_RID_) to be sent using the RID header extension. This parameter cannot be modified using {{domxref("RTCRtpSender.setParameters", "setParameters()")}}. Its value can only be set when the transceiver is first created. - `scaleResolutionDownBy` - : Only used for senders whose track's {{domxref("MediaStreamTrack.kind", "kind")}} is `video`, this is a floating-point value specifying a factor by which to scale down the video during encoding. The default value, 1.0, means that the video will be encoded at its original size. A value of 2.0 scales the video frames down by a factor of 2 in each dimension, resulting in a video 1/4 the size of the original. The value must not be less than 1.0 (attempting to scale the video to a larger size will throw a {{jsxref("RangeError")}}). - `transactionId` - : A string containing a unique ID. This ID is set in the previous {{domxref("RTCRtpSender.getParameters", "getParameters()")}} call, and ensures that the parameters originated from a previous call to {{domxref("RTCRtpSender.getParameters", "getParameters()")}}. <!-- spec defines following in RTCRtpParameters --> - `codecs` - : An array of {{domxref("RTCRtpCodecParameters")}} objects describing the set of codecs from which the sender will choose. This parameter cannot be changed. - `headerExtensions` - : An array of zero or more RTP header extensions, each identifying an extension supported by the sender. Header extensions are described in {{RFC(3550, "", "5.3.1")}}. This parameter cannot be changed. - `rtcp` - : An {{domxref("RTCRtcpParameters")}} object providing the configuration parameters used for {{Glossary("RTCP")}} on the sender. This parameter cannot be changed. - `degradationPreference` {{deprecated_inline}} - : Specifies the preferred way the WebRTC layer should handle optimizing bandwidth against quality in constrained-bandwidth situations. The possible values are `maintain-framerate`, `maintain-resolution`, or `balanced`. The default value is `balanced`. ### Return value A {{jsxref("Promise")}} that resolves when the {{domxref("RTCRtpSender.track")}} property is updated with the given parameters. ### Exceptions If an error occurs, the returned promise is rejected with the appropriate exception from the list below. - `InvalidModificationError` {{domxref("DOMException")}} - : Returned if one of the following problems is detected: - The number of encodings specified in the `parameters` object's `encodings` property does not match the number of encodings currently listed for the `RTCRtpSender`. You cannot change the number of encoding options after the sender has been created. - The order of the specified `encodings` has changed from the current list's order. - An attempt has been made to alter a property that cannot be changed after the sender is first created. - `InvalidStateError` {{domxref("DOMException")}} - : Returned if the transceiver, of which the `RTCRtpSender` is a part, is not running or has no parameters to set. - `OperationError` {{domxref("DOMException")}} - : Returned if an error occurs that does not match the ones specified here. - {{jsxref("RangeError")}} - : Returned if the value specified for `scaleResolutionDownBy` option is less than 1.0 — which would result in scaling up rather than down, which is not allowed; or if one or more of the specified `encodings` {{domxref("#maxframerate", "maxFramerate")}} values is less than 0.0. In addition, if a WebRTC error occurs while configuring or accessing the media, an {{domxref("RTCError")}} is thrown with its {{domxref("RTCError.errorDetail", "errorDetail")}} set to `hardware-encoder-error`. ## Description It's important to keep in mind that you can't create the `parameters` object yourself and expect it to work. Instead, you _must_ first call {{domxref("RTCRtpSender.getParameters", "getParameters()")}}, modify the received parameters object, then pass that object into `setParameters()`. WebRTC uses the parameters object's `transactionId` property to ensure that when you set parameters, your changes are based on the most recent parameters rather than an out of date configuration. ## Examples One use case for `setParameters()` is to try to reduce network bandwidth used in constrained environments by altering the resolution and/or bit rate of the media being transmitted by the {{domxref("RTCRtpSender")}}. Currently, some browsers have limitations on their implementations that may cause issues. For that reason, two examples are given here. The first shows how to use `setParameters()` when all browsers fully support the parameters being used, while the second example demonstrates workarounds to help solve limitations in browsers with incomplete support for the {{domxref("#maxBitrate","maxBitrate")}} and {{domxref("#scaleResolutionDownBy", "scaleResolutionDownBy")}} parameters. ### By the specification Once all browsers implement the spec fully, this implementation of `setVideoParams()` will do the job. This demonstrates how everything _should_ work. You should probably use the second example, below, for now. But this is a clearer demonstration of the basic concept of first fetching the parameters, then altering them, then setting them. ```js async function setVideoParams(sender, height, bitrate) { const scaleRatio = sender.track.getSettings().height / height; const params = sender.getParameters(); params.encodings[0].scaleResolutionDownBy = Math.max(scaleRatio, 1); params.encodings[0].maxBitrate = bitrate; await sender.setParameters(params); } ``` In calling this function, you specify a sender, as well as the height you wish to scale the sender's video to, as well as a maximum bitrate to permit the sender to transmit. A scaling factor for the size of the video, `scaleRatio`, is computed. Then the sender's current parameters are fetched using {{domxref("RTCRtpSender.getParameters", "getParameters()")}}. The parameters are then altered by changing the first `encodings` object's {{domxref("#scaleResolutionDownBy", "scaleResolutionDownBy")}} and {{domxref("#maxBitrate", "maxBitrate")}} to the calculated scaling factor and the specified maximum `bitrate`. The changed parameters are then saved by calling the sender's `setParameters()` method. ### Currently compatible implementation As mentioned above, the previous example shows how things are meant to work. Unfortunately, there are implementation issues preventing this in many browsers right now. For that reason, if you want to be compatible with iPhone and other devices running Safari, and with Firefox, use code more like this: ```js async function setVideoParams(sender, height, bitrate) { const scaleRatio = sender.track.getSettings().height / height; const params = sender.getParameters(); // If encodings is null, create it if (!params.encodings) { params.encodings = [{}]; } params.encodings[0].scaleResolutionDownBy = Math.max(scaleRatio, 1); params.encodings[0].maxBitrate = bitrate; await sender.setParameters(params); // If the newly changed value of scaleResolutionDownBy is 1, // use applyConstraints() to be sure the height is constrained, // since scaleResolutionDownBy may not be implemented if (sender.getParameters().encodings[0].scaleResolutionDownBy === 1) { await sender.track.applyConstraints({ height }); } } ``` The differences here: - If `encodings` is `null`, we create it, in order to ensure that we can then set the parameters successfully without crashing. - If, after setting the parameters, the value of `scaleResolutionDownBy` is still 1, we call the sender's track's {{domxref("MediaStreamTrack.applyConstraints", "applyConstraints()")}} method to constrain the track's height to `height`. This compensates for an unimplemented `scaleResolutionDownBy` (as is the case in Safari as of this writing). This code will cleanly fall back and work the normal way if the browser fully implements the used features. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [WebRTC API](/en-US/docs/Web/API/WebRTC_API) - [Codecs used by WebRTC](/en-US/docs/Web/Media/Formats/WebRTC_codecs) - [Web media technologies](/en-US/docs/Web/Media)
0
data/mdn-content/files/en-us/web/api/rtcrtpsender
data/mdn-content/files/en-us/web/api/rtcrtpsender/getstats/index.md
--- title: "RTCRtpSender: getStats() method" short-title: getStats() slug: Web/API/RTCRtpSender/getStats page-type: web-api-instance-method browser-compat: api.RTCRtpSender.getStats --- {{APIRef("WebRTC")}} The {{domxref("RTCRtpSender")}} method **`getStats()`** asynchronously requests an {{domxref("RTCStatsReport")}} object which provides statistics about outgoing traffic on the {{domxref("RTCPeerConnection")}} which owns the sender, returning a {{jsxref("Promise")}} which is fulfilled when the results are available. ## Syntax ```js-nolint getStats() ``` ### Parameters None. ### Return value A JavaScript {{jsxref("Promise")}} which is fulfilled once the statistics are available. The promise's fulfillment handler receives as a parameter a {{domxref("RTCStatsReport")}} object containing the collected statistics. The returned `RTCStatsReport` accumulates the statistics for all of the streams being sent using the `RTCRtpSender`, as well as the statistics for any dependencies those streams have. These might include, for example, statistics with [types](2/en-US/docs/Web/API/RTCStatsReport#the_statistic_types): [`outbound-rtp`](/en-US/docs/Web/API/RTCOutboundRtpStreamStats), [`candidate-pair`](/en-US/docs/Web/API/RTCIceCandidatePairStats), [`local-candidate`](/en-US/docs/Web/API/RTCIceCandidateStats), [`remote-candidate`](/en-US/docs/Web/API/RTCIceCandidateStats). ## Examples This simple example obtains the statistics for an `RTCRtpSender` and updates an element's {{domxref("HTMLElement/innerText", "innerText")}} to display the current round trip time for requests on the sender. ```js sender.getStats().then((stats) => { document.getElementById("currentRTT").innerText = stats.roundTripTime; }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [WebRTC API](/en-US/docs/Web/API/WebRTC_API) - {{domxref("RTCStatsReport")}} - {{domxref("RTCRtpReceiver.getStats()")}} - {{domxref("RTCPeerConnection.getStats()")}}
0
data/mdn-content/files/en-us/web/api/rtcrtpsender
data/mdn-content/files/en-us/web/api/rtcrtpsender/transform/index.md
--- title: "RTCRtpSender: transform property" short-title: transform slug: Web/API/RTCRtpSender/transform page-type: web-api-instance-property browser-compat: api.RTCRtpSender.transform --- {{APIRef("WebRTC")}} The **`transform`** property of the {{domxref("RTCRtpSender")}} object is used to insert a transform stream ({{domxref("TransformStream")}}) running in a worker thread into the sender pipeline. This allows stream transforms to be applied to encoded video and audio frames after they are output by a codec, and before they are sent. The transform that is to be added is defined using an {{domxref("RTCRtpScriptTransform")}} and its associated {{domxref("Worker")}}. If the transform is set synchronously immediately after creating the `RTCRtpSender` it will receive the first full frame generated by the sender's encoder. ### Value A {{domxref("RTCRtpScriptTransform")}}<!-- or {{domxref("SFrameTransform")}} -->, or `null` if the sender has no associated transform stream. ## Example This example shows how you might stream video from a user's webcam over WebRTC, adding a WebRTC encoded transform to modify the outgoing streams. Note that this is part of a larger example in the guide topic [Using WebRTC Encoded Transforms](/en-US/docs/Web/API/WebRTC_API/Using_Encoded_Transforms). The code assumes that there is an {{domxref("RTCPeerConnection")}} called `peerConnection` that is already connected to a remote peer. It first gets a {{domxref("MediaStreamTrack")}}, using {{domxref("MediaDevices/getUserMedia", "getUserMedia()")}} to get a video {{domxref("MediaStream")}} from a media device, and then the {{domxref("MediaStream.getTracks()")}} method to get the first {{domxref("MediaStreamTrack")}} in the stream. The track is added to the peer connection using {{domxref("RTCPeerConnection/addTrack()", "addTrack()")}}. This returns a new {{domxref("RTCRtpSender")}} that will be used to send it. ```js const mediaStream = await navigator.mediaDevices.getUserMedia({ video: true }); const [track] = mediaStream.getTracks(); const videoSender = peerConnection.addTrack(track, mediaStream); ``` The code above sets up the connection and starts sending the track. To add a transform stream into the pipeline we need to construct an {{domxref("RTCRtpScriptTransform")}} and assign it to the sender's `transform` property. As the transform is constructed immediately after creation of the {{domxref("RTCRtpSender")}}, it will receive the first frame generated by the sender's encoder, before it is sent. ```js const worker = new Worker("worker.js"); videoSender.transform = new RTCRtpScriptTransform(worker, { name: "senderTransform", }); ``` Note that you can add the transform at any time. However by adding it immediately after calling `addTrack()` the transform will get the first encoded frame that is sent. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using WebRTC Encoded Transforms](/en-US/docs/Web/API/WebRTC_API/Using_Encoded_Transforms) - {{domxref("RTCRtpReceiver.transform")}}
0