HTMLImageElement: width property - Web APIs

HTMLImageElement: width property
================================

 The **`width`** property of the
 `HTMLImageElement` interface indicates the width at which an image is
 drawn in CSS pixels if it's being drawn or rendered to
 any visual medium such as a screen or printer. Otherwise, it's the natural, pixel
 density-corrected width of the image.

Value
-----

 An integer value indicating the width of the image. The way the width is defined
 depends on whether or not the image is being rendered to a visual medium, such as a
 screen or printer:

* If the image is being rendered to a visual medium, the width is expressed in
 CSS pixels.
* If the image is not being rendered to a visual medium, its width is represented
 using the image's natural (intrinsic) width, adjusted for the display density as
 indicated by `naturalWidth`.
Examples
--------

 In this example, two different sizes are provided for an image of a clock using the
 `srcset` attribute. One is 200px wide and the other is 400px
 wide. The `sizes` attribute is used to specify the width at
 which the image should be drawn given the viewport's width.

### HTML

 For viewports up to 400px wide, the image is drawn at a width of 200px. Otherwise, it's
 drawn at 400px.

```html
<p>Image width: <span class="size">?</span>px (resize to update)</p>
<img
 src="/en-US/docs/Web/HTML/Element/img/clock-demo-200px.png"
 alt="Clock"
 srcset="
 /en-US/docs/Web/HTML/Element/img/clock-demo-200px.png 200w,
 /en-US/docs/Web/HTML/Element/img/clock-demo-400px.png 400w
 "
 sizes="(max-width: 400px) 200px, 400px" />
```

### JavaScript

 JavaScript looks at the `width` property to determine the width of the image
 at the moment. This is performed in the window's `load` and `resize` event handlers so the most
 current width information is always available.

```js
const clockImage = document.querySelector("img");
let output = document.querySelector(".size");

const updateWidth = (event) => {
  output.innerText = clockImage.width;
};

window.addEventListener("load", updateWidth);
window.addEventListener("resize", updateWidth);
```

### Result

This example may be easier to try out in its own window.

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

| Specification |
| --- |
| HTML Standard # dom-img-width-dev |

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

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

See also
--------

* `HTMLCanvasElement.width`
* `HTMLObjectElement.width`
* `HTMLVideoElement.width`


HTMLImageElement: isMap property - Web APIs

HTMLImageElement: isMap property
================================

 The `HTMLImageElement` property **`isMap`** is a
 Boolean value which indicates that the image is to be used by a server-side image map.
 This may only be used on images located within an `<a>` element.

**Note:** For accessibility reasons, you should generally avoid using
 server-side image maps, as they require the use of a mouse. Use a client-side image map instead.

Value
-----

 A Boolean value which is `true` if the image is being used for a server-side
 image map; otherwise, the value is `false`.

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

 When an image marked as being part of a server-side image map is clicked, the browser
 constructs the string "?x,y", where x and y indicate the coordinates at which the
 mouse was clicked as offsets from the top-left corner of the image, specified in CSS
 pixels.

 The browser then fetches that URL from the server and displays or downloads it
 depending on the value of the `download` attribute.

 Unlike server-side image maps, client-side image maps don't cause the
 `<img>` element to adopt interactive content mode.

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

| Specification |
| --- |
| HTML Standard # dom-img-ismap |

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

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


HTMLImageElement: fetchPriority property - Web APIs

HTMLImageElement: fetchPriority property
========================================

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

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

* Learn more
* See full compatibility
* Report feedback

 The **`fetchPriority`** property of the
 `HTMLImageElement` interface represents a hint given to the browser on how
 it should prioritize the fetch of the image relative to other images.

Value
-----

A string representing the priority hint. Possible values are:

`high`

Fetch the image at a high priority relative to other images.

`low`

Fetch the image at a low priority relative to other images.

`auto`

 Default mode, which indicates no preference for the fetch priority.
 The browser decides what is best for the user.

 The `fetchPriority` property allows you to signal high or low priority image
 fetches. This can be useful when applied to `<img>` elements
 to signal images that are "important" to the user experience early in the
 loading process.

 The effects of the hint on resource loading is browser-specific so make sure to
 test on multiple browser engines.

 Use it sparingly for exceptional cases where the browser may not be able to
 infer the best way to load the image automatically. Over use can result in
 degrading performance.

Examples
--------

```js
const img = new Image();
img.fetchPriority = "high";
img.src = "img/logo.png";
```

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

| Specification |
| --- |
| HTML Standard # attr-img-fetchpriority |

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

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


HTMLImageElement: align property - Web APIs

HTMLImageElement: align property
================================

**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

 The *obsolete* **`align`**
 property of the `HTMLImageElement` interface is a string which indicates
 how to position the image relative to its container.

 You should instead use the
 CSS property `vertical-align`, which does in fact also work on images
 despite its name. You can also use the `float` property to float the image
 to the left or right margin.

 The `align` property reflects the HTML `align`
 content attribute.

Value
-----

 A string specifying one of the following strings which set the
 alignment mode for the image.

### Baseline alignment

 These three values specify the alignment of the element relative to the text baseline.
 These should be replaced by using the CSS `vertical-align` property.

`bottom`

 The bottom edge of the image is to be aligned vertically with the current text
 baseline. **Default value.**

`middle`

The center of the object should be aligned vertically with the current baseline.

`top`

The top edge of the object should be aligned vertically with the current baseline.

 It may be worth noting that `vertical-align` offers several additional
 options for its value; you may wish to consider these when changing your code to use it.

### Floating images horizontally

 The `left` and `right` properties don't affect the
 baseline-relative alignment. Instead, they cause the image to "float" to the left or
 right margin, allowing the following text to flow around the image. You should instead
 use the CSS `float` property, specifying as the value
 either `left` or `right`.

`left`

 Floats the image over to place the left edge flush against the current margin. Any
 text that follows will flow against the image's right edge.

`right`

 Floats the image to place its right edge flush against the right margin. Subsequent
 text will flow along the image's left edge.

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

| Specification |
| --- |
| HTML Standard # attr-img-align |

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

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


HTMLImageElement: border property - Web APIs

HTMLImageElement: border property
=================================

**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

 The obsolete `HTMLImageElement`
 property **`border`** specifies the number of pixels thick the
 border surrounding the image should be. A value of 0, the default, indicates that no
 border should be drawn.

 You should *not* use this property! Instead, you should use CSS to style the
 border. The `border` property or its longhand properties to not only set
 the thickness of the border but to potentially apply a wide variety of other styling
 options to it.

 The width, specifically, is controlled using the writing-mode aware
 `border-block-start-width`, `border-block-end-width`,
 `border-inline-start-width`, and `border-inline-end-width`
 properties.

 For compatibility (or perhaps other) reasons, you can use the older properties instead
 (or in addition): `border-top-width`, `border-right-width`,
 `border-bottom-width`, and `border-left-width`.

Value
-----

 A string containing an integer value specifying the thickness of the
 border that should surround the image, in CSS pixels. A value of `0`, or an
 empty string, indicates that there should be no border drawn. The default value of
 `border` is `0`

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

 Do not use `border`. It is obsolete. Instead, use the CSS
 `border` property and its longhand properties to establish borders around
 images.

For example, if you have the following HTML:

```html
<img src="image.png" border="2" />
```

 The following will provide the same appearance using CSS instead of this obsolete
 property:

```html
<img src="image.png" style="border: 2px;" />
```

 You can further provide additional information to change the color and other features
 of the border:

```html
<img src="image.png" style="border: dashed 2px #333388;" />
```

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

| Specification |
| --- |
| HTML Standard # dom-img-border |

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

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


HTMLImageElement: longDesc property - Web APIs

HTMLImageElement: longDesc property
===================================

**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

 The *deprecated* property **`longDesc`** on
 the `HTMLImageElement` interface specifies the URL of a text or HTML file
 which contains a long-form description of the image. This can be used to
 provide optional added details beyond the short description provided in the
 `title` attribute.

Value
-----

 A string which may be either an empty string (indicating that no long
 description is available) or the URL of a file containing a long form description of the
 image's contents.

 For example, if the image is a PNG of a flowchart.
 The `longDesc` property could be used to provide an explanation of the flow
 of control represented by the chart, using only text. This can be used by readers both
 as an explanation, but also as a substitute for visually-impaired users.

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

 This property is *deprecated* and should no longer be used. Instead of
 using `longDesc` to provide a link to a detailed description of an image,
 encapsulate the image within a link using the `<a>` element.

Consider the following older HTML:

```html
<img
 src="taco-tuesday.jpg"
 alt="Taco Tuesday"
 longdesc="image-descriptions/taco-tuesday.html" />
```

 Here, the `longDesc` is used to indicate that the user should be able to
 access a detailed description of the image `taco-tuesday.jpg` in the HTML
 file `image-descriptions/taco-tuesday.html`.

This can be easily converted into modern HTML:

```html
<a href="image-descriptions/taco-tuesday.html">
  <img src="taco-tuesday.jpg" alt="Taco Tuesday" />
</a>
```

With that, the image is a link to the HTML file describing the image in more detail.

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

This feature is not part of any current specification. It is no longer on track to become a standard.

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

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

See also
--------

* `aria-details`


HTMLImageElement: name property - Web APIs

HTMLImageElement: name property
===============================

**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

 The `HTMLImageElement`
 interface's *deprecated* **`name`** property specifies
 a name for the element. This has been replaced by the `id`
 property available on all elements.

Value
-----

A string providing a name by which the image can be referenced.

**Warning:** This property is deprecated and is only in the
 specification still for backward compatibility purposes. Since it functions
 identically to `id`, you can and should use it instead.

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

| Specification |
| --- |
| HTML Standard # attr-img-name |

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

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


HTMLImageElement: Image() constructor - Web APIs

HTMLImageElement: Image() constructor
=====================================

 The **`Image()`**
 constructor creates a new `HTMLImageElement` instance. It is functionally
 equivalent to `document.createElement('img')`.

**Note:** This function should not be confused with the CSS `image()` function.

Syntax
------

```js
new Image()
new Image(width)
new Image(width, height)
```

### Parameters

`width` Optional

 The width of the image (i.e., the value for the `width`
 attribute).

`height` Optional

 The height of the image (i.e., the value for the `height`
 attribute).

Usage note
----------

 The entire bitmap is loaded regardless of the sizes specified in the constructor. The
 size specified in the constructor is reflected through the properties
 `HTMLImageElement.width` and `HTMLImageElement.height` of the
 resulting instance. The intrinsic width and height of the image in CSS pixels are
 reflected through the properties `HTMLImageElement.naturalWidth` and
 `HTMLImageElement.naturalHeight`. If no size is specified in the
 constructor both pairs of properties have the same values.

Examples
--------

```js
const myImage = new Image(100, 200);
myImage.src = "picture.jpg";
document.body.appendChild(myImage);
```

 This would be the equivalent of defining the following HTML tag inside the
 `<body>`:

```html
<img width="100" height="200" src="picture.jpg" />
```

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

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

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

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


HTMLImageElement: srcset property - Web APIs

HTMLImageElement: srcset property
=================================

 The `HTMLImageElement` property
 **`srcset`** is a string which identifies one or more
 **image candidate strings**, separated using commas (`,`) each
 specifying image resources to use under given circumstances.

 Each image
 candidate string contains an image URL and an optional width or pixel density descriptor
 that indicates the conditions under which that candidate should be used instead of the
 image specified by the `src` property.

 The `srcset` property, along with the `sizes` property, are a crucial component in designing responsive websites, as they
 can be used together to make pages that use appropriate images for the rendering
 situation.

**Note:** If the `srcset` attribute uses width descriptors, the `sizes` attribute must also be present, or the `srcset` itself will be ignored.

Value
-----

 A string containing a comma-separated list of one or more image
 candidate strings to be used when determining which image resource to present inside the
 `<img>` element represented by the
 `HTMLImageElement`.

 Each image candidate string must begin with a valid URL referencing a non-interactive
 graphic resource. This is followed by whitespace and then a condition descriptor that
 indicates the circumstances in which the indicated image should be used. Space
 characters, other than the whitespace separating the URL and the corresponding condition
 descriptor, are ignored; this includes both leading and trailing space, as well as space
 before or after each comma.

The condition descriptor may take one of two forms:

* To indicate that the image resource specified by the image candidate string should
 be used when the image is being rendered with a particular width in pixels, provide a
 **width descriptor** comprised the number giving that width in pixels
 followed by the lower case letter "w". For example, to provide an image resource to be
 used when the renderer needs a 450 pixel wide image, use the width descriptor string
 `450w`. The specified width must be a positive, non-zero, integer, and
 *must* match the intrinsic width of the referenced image. When a `srcset` contains
 "w" descriptors, the browser uses those descriptors together with the
 `sizes` attribute to pick a resource.
* Alternatively, you can use a **pixel density descriptor**, which
 specifies the condition in which the corresponding image resource should be used as
 the display's pixel density. This is written by stating the pixel density as a
 positive, non-zero floating-point value followed by the lower-case letter "x". As an
 example, to state that the corresponding image should be used when the pixel density
 is double the standard density, you can give the pixel density descriptor
 `2x` or `2.0x`.

 If the condition descriptor is not provided (in other words, the image candidate
 provides only a URL), the candidate is assigned a default descriptor of "1x".
```

"images/team-photo.jpg, images/team-photo-retina.jpg 2x"
```

 This string provides versions of an image to be used at the standard pixel density
 (undescribed, assigned a default of `1x`) as well as double that pixel density (`2x`).

 When an image element's `srcset` contains "x" descriptors, browsers also consider
 the URL in the `src` attribute (if present) as a
 candidate, and assign it a default descriptor of `1x`.
```

"header640.png 640w, header960.png 960w, header1024.png 1024w"
```

This string provides versions of a header image to use when the user agent's renderer needs an image of width 640px, 960px, or 1024px.

 Note that if any resource in a `srcset` is described with a "w" descriptor, all
 resources within that `srcset` must also be described with "w" descriptors, and
 the image element's `src` is not considered
 a candidate.

Examples
--------

### HTML

 The HTML below indicates that the default image resource, contained within the
 `src` attribute should be used for 1x
 displays, and that a 400-pixel version (contained within the `srcset`, and assigned
 a `2x` descriptor) should be used for 2x displays.

```html
<div class="box">
  <img
 src="/en-US/docs/Web/HTML/Element/img/clock-demo-200px.png"
 alt="Clock"
 srcset="/en-US/docs/Web/HTML/Element/img/clock-demo-400px.png 2x" />
</div>
```

### CSS

 The CSS specifies that the image and its surrounding box should be 200 pixels square
 and should have a simple border around it. Also provided is the
 `word-break` attribute, using the `break-all` value to tell the
 browser to wrap the string within the width available regardless of where in the string
 the wrap must occur.

```css
.box {
  width: 200px;
  border: 2px solid rgb(150 150 150);
  padding: 0.5em;
  word-break: break-all;
}

.box img {
  width: 200px;
}
```

### JavaScript

 The following code is run within a handler for the `window`'s
 `load` event. It uses the image's
 `currentSrc` property to fetch and display
 the URL selected by the browser from the `srcset`.

```js
window.addEventListener("load", () => {
  let box = document.querySelector(".box");
  let image = box.querySelector("img");

  let newElem = document.createElement("p");
  newElem.innerHTML = `Image: <code>${image.currentSrc}</code>`;
  box.appendChild(newElem);
});
```

### Result

 In the displayed output below, the selected URL will correspond with whether your
 display results in selecting the 1x or the 2x version of the image. If you happen to
 have both standard and high density displays, try moving this window between them and
 reloading the page to see the results change.

For additional examples, see our guide to responsive images.

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

| Specification |
| --- |
| HTML Standard # dom-img-srcset |

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

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

See also
--------

* Images in HTML
* Responsive images
* Image file type and format guide


HTMLImageElement: y property - Web APIs

HTMLImageElement: y property
============================

 The read-only `HTMLImageElement` property
 **`y`** indicates the y-coordinate of the
 `<img>` element's top border edge relative to the root element's
 origin.

 The `x` and `y` properties are only valid
 for an image if its `display` property has the computed value
 `table-column` or `table-column-group`. In other words: it has
 either of those values set explicitly on it, or it has inherited it from a containing
 element, or by being located within a column described by either
 `<col>` or `<colgroup>`.

Value
-----

 An integer value indicating the distance in pixels from the top edge of the element's
 nearest root element to the top edge of the `<img>` element's border
 box. The nearest root element is the outermost `<html>` element that
 contains the image. If the image is in an `<iframe>`, its
 `y` is relative to that frame.

 In the diagram below, the top border edge is the top edge of the blue padding area. So
 the value returned by `y` would be the distance from that point to the top
 edge of the content area.

![Diagram showing the relationships between the various boxes associated with an element](/en-US/docs/Web/API/HTMLImageElement/y/boxmodel-3.png)

**Note:** The `y` property is only valid if the computed
 value of the image's `display` property is either
 `table-column` or `table-column-group`; in other words,
 either of those are set directly on the `<img>` or they're
 inherited from a containing element or by being located within a column described
 by either `<col>` or `<colgroup>`.

Example
-------

See `HTMLImageElement.x` for example code that demonstrates the use of the `HTMLImageElement.y` (and `HTMLImageElement.x`).

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

| Specification |
| --- |
| CSSOM View Module # dom-htmlimageelement-y |

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

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


HTMLImageElement: src property - Web APIs

HTMLImageElement: src property
==============================

 The `HTMLImageElement` property
 **`src`**, which reflects the HTML `src` attribute, specifies the image to display in the `<img>`
 element.

Value
-----

 When providing only a single image, rather than a set of images from which the browser
 selects the best match for the viewport size and display pixel density, the
 `src` attribute is a string specifying the URL of the
 desired image. This can be set either within the HTML itself using the
 `src` content attribute, or programmatically by setting the
 element's `src` property.

 If you use the `srcset` content attribute to provide multiple
 image options for different display pixel densities, the URL specified by the
 `src` attribute is used in one of two ways:

* as a fallback for browsers that don't support `srcset`.
* as an equivalent for specifying an image in `srcset` with the size
 multiplier `1x`; that is, the image specified by `src` is used
 on low-density screens (such as typical 72 DPI or 96 DPI displays).

 Additionally, if you use `src` along with *both*
`sizes` (or the
 corresponding `sizes` content attribute) *and*
`srcset` in order to choose an image based on the viewport size, the
 `src` attribute is only used as a fallback for browsers that don't support
 `sizes` and `srcset`; otherwise, it's not used at all.

Examples
--------

### Specifying a single image

#### HTML

```html
<img
 src="grapefruit-slice-332-332.jpg"
 width="160"
 alt="Slices of grapefruit, looking yummy." />
```

#### Result

### Using src with an image set

 When using a set of images with the `srcset`
 property, the `src` serves as either a fallback for older browsers, or as the
 `1x` size of the image.

#### HTML

#### Result

### Specifying a fallback for viewport-based selection

 When using viewport-bases selection of an image from a `srcset` by also
 specifying the `sizes` property, the
 `src` property serves as the fallback to be used on browsers that don't
 support viewport-based selection. Browsers that *do* support viewport-based
 selection will ignore `src` in this situation.

#### HTML

#### Result

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

| Specification |
| --- |
| HTML Standard # attr-img-src |

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

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


HTMLImageElement: x property - Web APIs

HTMLImageElement: x property
============================

 The read-only `HTMLImageElement` property
 **`x`** indicates the x-coordinate of the
 `<img>` element's left border edge relative to the root element's
 origin.

 The `x` and `y` properties are only valid
 for an image if its `display` property has the computed value
 `table-column` or `table-column-group`. In other words: it has
 either of those values set explicitly on it, or it has inherited it from a containing
 element, or by being located within a column described by either `<col>`
 or `<colgroup>`.

Value
-----

 An integer value indicating the distance in pixels from the left edge of the element's
 nearest root element and the left edge of the `<img>` element's border
 box. The nearest root element is the outermost `<html>` element that
 contains the image. If the image is in an `<iframe>`, its `x`
 is relative to that frame.

 In the diagram below, the left border edge is the left edge of the blue padding area.
 So the value returned by `x` would be the distance from that point to the
 left edge of the content area.

![Diagram showing the relationships between the various boxes associated with an element](/en-US/docs/Web/API/HTMLImageElement/x/boxmodel-3.png)

**Note:** The `x` property is only valid if the computed
 value of the image's `display` property is either
 `table-column` or `table-column-group`; in other words, either
 of those are set directly on the `<img>` or they're inherited from a
 containing element or by being located within a column described by either
 `<col>` or `<colgroup>`.

Example
-------

 The example below demonstrates the use of the `HTMLImageElement` properties
 `x` and `y`.

### HTML

 In this example, we see a table showing information about users of a website,
 including their user ID, their full name, and their avatar image.

```html
<table id="userinfo">
  <colgroup>
    <col span="2" class="group1">
    <col>
  </colgroup>
  <tr>
    <th>UserID</th>
    <th>Name</th>
    <th>Avatar</th>
  </tr>
  <tr>
    <td>12345678</td>
    <td>Johnny Rocket</td>
    <td><img src="https://interactive-examples.mdn.mozilla.net/media/examples/grapefruit-slice-332-332.jpg"></td>
  </th>
</table>
<pre id="log">
</pre>
```

### JavaScript

 The JavaScript code that fetches the image from the table and looks up its
 `x` and `y` values is below.

```js
let logBox = document.querySelector("pre");
let tbl = document.getElementById("userinfo");

let log = (msg) => {
  logBox.innerHTML += `${msg}<br>`;
};

let cell = tbl.rows[1].cells[2];
let image = cell.querySelector("img");

log(`Image's global X: ${image.x}`);
log(`Image's global Y: ${image.y}`);
```

 This uses the `<table>`'s `rows`
 property to get a list of the rows in the table, from which it looks up row 1 (which,
 being a zero-based index, means the second row from the top). Then it looks at that
 `<tr>` (table row) element's `cells` property to get a list of the cells in that row. The third cell is taken from
 that row (once again, specifying 2 as the zero-based offset).

 From there, we can get the `<img>` element itself from the cell by
 calling `querySelector()` on the
 `HTMLTableCellElement` representing that cell.

 Finally, we can look up and display the values of the `HTMLImageElement`'s
 `x` and `y` properties.

### CSS

The CSS defining the appearance of the table:

```css
.group1 {
  background-color: #d7d9f2;
}

table {
  border-collapse: collapse;
  border: 2px solid rgb(100 100 100);
  font-family: sans-serif;
}

td,
th {
  border: 1px solid rgb(100 100 100);
  padding: 10px 14px;
}

td > img {
  max-width: 4em;
}
```

### Result

The resulting table looks like this:

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

| Specification |
| --- |
| CSSOM View Module # dom-htmlimageelement-x |

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

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


HTMLImageElement: naturalHeight property - Web APIs

HTMLImageElement: naturalHeight property
========================================

 The `HTMLImageElement` interface's
 **`naturalHeight`** property is a read-only value which
 returns the intrinsic (natural), density-corrected height of the image in
 CSS pixels.

 This is the height the image is if
 drawn with nothing constraining its height; if you don't specify a height for the image,
 or place the image inside a container that either limits or expressly specifies the
 image height, it will be rendered this tall.

**Note:** Most of the time the natural height is the actual height of the image sent by the server.
 Nevertheless, browsers can modify an image before pushing it to the renderer. For example, Chrome
 degrades the resolution of images on low-end devices. In such cases, `naturalHeight` will consider the height of the image modified
 by such browser interventions as the natural height, and returns this value.

Value
-----

 An integer value indicating the intrinsic height, in CSS pixels, of the image. This is
 the height at which the image is naturally drawn when no constraint or specific value is
 established for the image. This natural height is corrected for the pixel density of the
 device on which it's being presented, unlike `height`.

 If the intrinsic height is not available—either because the image does not specify an
 intrinsic height or because the image data is not available in order to obtain this
 information, `naturalHeight` returns 0.

Examples
--------

 This example displays both the natural, density-adjusted size of an image as well as
 its rendered size as altered by the page's CSS and other factors.

### HTML

```html
<div class="box">
  <img
 src="/en-US/docs/Web/HTML/Element/img/clock-demo-400px.png"
 class="image"
 alt="A round wall clock with a white dial and black numbers" />
</div>
<pre></pre>
```

 The HTML features a 400x398 pixel image which is placed inside a
 `<div>`.

### CSS

```css
.box {
  width: 200px;
  height: 200px;
}

.image {
  width: 100%;
}
```

 The main thing of note in the CSS above is that the style used for the container the
 image will be drawn in is 200px wide, and the image will be drawn to fill its width
 (100%).

### JavaScript

```js
const output = document.querySelector("pre");
const image = document.querySelector("img");

image.addEventListener("load", (event) => {
  const { naturalWidth, naturalHeight, width, height } = image;
  output.textContent = `
Natural size: ${naturalWidth} x ${naturalHeight} pixels
Displayed size: ${width} x ${height} pixels
`;
});
```

 The JavaScript code dumps the natural and as-displayed sizes into the
 `<pre>`. This is done in response to
 the images's `load` event handler, in order to ensure
 that the image is available before attempting to examine its width and height.

### Result

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

| Specification |
| --- |
| HTML Standard # dom-img-naturalheight-dev |

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

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


HTMLImageElement: crossOrigin property - Web APIs

HTMLImageElement: crossOrigin property
======================================

 The `HTMLImageElement`
 interface's **`crossOrigin`** attribute is a string which
 specifies the Cross-Origin Resource Sharing (CORS) setting to use when
 retrieving the image.

Value
-----

 A string of a keyword specifying the CORS mode to use when fetching
 the image resource. If you don't specify `crossOrigin`, the image is fetched
 without CORS (the fetch `no-cors` mode).

Permitted values are:

`anonymous`

 Requests by the `<img>` element have their `mode` set to `cors` and their `credentials` mode set to `same-origin`. This means that CORS is enabled
 and credentials are sent *if* the image is fetched from the same origin from
 which the document was loaded.

`use-credentials`

 Requests by the `HTMLImageElement` will use the `cors` mode
 and the `include` credentials mode; all image requests by the element will
 use CORS, regardless of what domain the fetch is from.

 If `crossOrigin` is an empty string (`""`),
 the `anonymous` mode is selected.

Examples
--------

 In this example, a new `<img>` element is created and added to the
 document, loading the image with the Anonymous state; the image will be loaded using
 CORS and credentials will be used for all cross-origin loads.

### JavaScript

 The code below demonstrates setting the `crossOrigin` property on an
 `<img>` element to configure CORS access for the fetch of a
 newly-created image.

```js
const imageUrl = "clock-demo-400px.png";
const container = document.querySelector(".container");

function loadImage(url) {
  const image = new Image(200, 200);
  image.addEventListener("load", () => container.prepend(image));

  image.addEventListener("error", () => {
    const errMsg = document.createElement("output");
    errMsg.value = `Error loading image at ${url}`;
    container.append(errMsg);
  });

  image.crossOrigin = "anonymous";
  image.alt = "";
  image.src = url;
}

loadImage(imageUrl);
```

### HTML

```html
<div class="container">
  <p>
    Here's a paragraph. It's a very interesting paragraph. You are captivated by
    this paragraph. Keep reading this paragraph. Okay, now you can stop reading
    this paragraph. Thanks for reading me.
  </p>
</div>
```

### CSS

```css
body {
  font:
    1.125rem/1.5,
    Helvetica,
    sans-serif;
}

.container {
  display: flow-root;
  width: 37.5em;
  border: 1px solid #d2d2d2;
}

img {
  float: left;
  padding-right: 1.5em;
}

output {
  background: rgb(100 100 100 / 100%);
  font-family: Courier, monospace;
  width: 95%;
}
```

### Result

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

| Specification |
| --- |
| HTML Standard # dom-img-crossorigin |

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

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

See also
--------

* `HTMLLinkElement.crossOrigin`
* `HTMLMediaElement.crossOrigin`
* `HTMLScriptElement.crossOrigin`


HTMLImageElement: sizes property - Web APIs

HTMLImageElement: sizes property
================================

 The `HTMLImageElement` property
 **`sizes`** allows you to specify the layout width of the
 image for each of a list of media conditions. This provides the ability to
 automatically select among different images—even images of different orientations or
 aspect ratios—as the document state changes to match different media
 conditions.

 Each condition is specified using the same conditional format used
 by media queries.

Value
-----

 A string containing a comma-separated list of source size descriptors
 followed by an optional fallback size. Each **source size descriptor** is
 comprised of a media condition, then at least one whitespace character, then the
 **source size value** to use for the image when the media condition
 evaluates to `true`.

### Media conditions

 Each source size descriptor consists of a media condition as defined by the media
 queries standard. Because a source size descriptor is used to specify the width to use
 for the image during layout of the page, the media condition is typically (but not
 necessarily) based entirely on width information. See
 Using media queries, Syntax for
 details on how to construct a media condition.

### Source size values

 The source size value is a CSS `<length>`. It may
 be specified using font-relative units (such as `em` or `ex`),
 absolute units (such as `px` or `cm`), or the `vw`
 unit, which lets you specify the width as a percentage of the viewport width
 (`1vw` being 1% of the viewport width).

**Note:** The source size value must *not* be specified as a
 percentage of the container size; that is, lengths such as `50%` or
 `100%` are not allowed, as there would be uncertainty as to what the
 specified value is a percentage of.

Examples
--------

### Selecting an image to fit window width

 In this example, a blog-like layout is created, displaying some text and an image
 for which three size points are specified, depending on the width of the window. Three
 versions of the image are also available, with their widths specified. The browser takes
 all of this information and selects an image and width that best meets the specified
 values.

 How exactly the images are used may depend upon the browser and the pixel density
 of the user's display.

 Buttons at the bottom of the example let you actually modify the `sizes`
 property slightly, switching the largest of the three widths for the image between 40em
 and 50em.

#### HTML

```html
<article>
  <h1>An amazing headline</h1>
  <div class="test"></div>
  <p>
    This is even more amazing content text. It's really spectacular. And
    fascinating. Oh, it's also clever and witty. Award-winning stuff, I'm sure.
  </p>
  <img
 src="new-york-skyline-wide.jpg"
 srcset="
 new-york-skyline-wide.jpg 3724w,
 new-york-skyline-4by3.jpg 1961w,
 new-york-skyline-tall.jpg 1060w
 "
 sizes="((min-width: 50em) and (max-width: 60em)) 50em,
 ((min-width: 30em) and (max-width: 50em)) 30em,
 (max-width: 30em) 20em"
 alt="The New York City skyline on a beautiful day, with the One World Trade Center building in the middle." />
  <p>
    Then there's even more amazing stuff to say down here. Can you believe it? I
    sure can't.
  </p>

  <button id="break40">Last Width: 40em</button>
  <button id="break50">Last Width: 50em</button>
</article>
```

#### CSS

```css
article {
  margin: 1em;
  max-width: 60em;
  min-width: 20em;
  border: 4em solid #880e4f;
  border-radius: 7em;
  padding: 1.5em;
  font:
    16px "Open Sans",
    Verdana,
    Arial,
    Helvetica,
    sans-serif;
}

article img {
  display: block;
  max-width: 100%;
  border: 1px solid #888;
  box-shadow: 0 0.5em 0.3em #888;
  margin-bottom: 1.25em;
}
```

#### JavaScript

 The JavaScript code handles the two buttons that let you toggle the third width option
 between 40em and 50em; this is done by handling the `click` event, using the JavaScript string object `replace()` method to replace the relevant portion of the `sizes` string.

```js
const image = document.querySelector("article img");
const break40 = document.getElementById("break40");
const break50 = document.getElementById("break50");

break40.addEventListener(
  "click",
  () => (image.sizes = image.sizes.replace(/50em,/, "40em,")),
);

break50.addEventListener(
  "click",
  () => (image.sizes = image.sizes.replace(/40em,/, "50em,")),
);
```

#### Result

The page is best viewed in its own window, so you can adjust the sizes fully.

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

| Specification |
| --- |
| HTML Standard # dom-img-sizes |

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

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

See also
--------

* Media queries
* Using media queries
* Images in HTML
* Responsive images
* Using the `srcset` and `sizes` attributes


HTMLImageElement: currentSrc property - Web APIs

HTMLImageElement: currentSrc property
=====================================

 The read-only `HTMLImageElement` property
 **`currentSrc`** indicates the URL of the image which is
 currently presented in the `<img>` element it represents.

Value
-----

 A string indicating the full URL of the image currently visible in
 the `<img>` element represented by the `HTMLImageElement`.
 This is useful when you provide multiple image options using the
 `sizes` and/or
 `HTMLImageElement.srcset` properties. `currentSrc` lets you
 determine which image from the set of provided images was selected by the browser.

Examples
--------

 In this example, two different sizes are provided for an image of a clock. One is 200px
 wide and the other is 400px wide. The `sizes` attribute is
 provided to indicate that the image should be drawn at 50% of the document width if the
 viewport is under 400px wide; otherwise, the image is drawn at 90% width of the
 document.

### HTML

```html
<img
 src="/files/16797/clock-demo-400px.png"
 alt="Clock"
 srcset="
 /en-US/docs/Web/HTML/Element/img/clock-demo-200px.png 200w,
 /en-US/docs/Web/HTML/Element/img/clock-demo-400px.png 400w
 "
 sizes="(max-width: 400px) 50%, 90%" />
```

### JavaScript

```js
const clockImage = document.querySelector("img");
const p = document.createElement("p");

p.textContent = clockImage.currentSrc.endsWith("200px.png")
  ? "Using the 400px image!"
  : "Using the 200px image.";
document.body.appendChild(p);
```

### Result

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

| Specification |
| --- |
| HTML Standard # dom-img-currentsrc-dev |

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

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


HTMLImageElement: naturalWidth property - Web APIs

HTMLImageElement: naturalWidth property
=======================================

 The `HTMLImageElement` interface's read-only
 **`naturalWidth`** property returns the intrinsic (natural),
 density-corrected width of the image in CSS
 pixels.

 This is the width the image is if drawn with nothing constraining
 its width; if you neither specify a width for the image nor place the image inside a
 container that limits or expressly specifies the image width, this is the number of CSS
 pixels wide the image will be.

 The corresponding `naturalHeight` method
 returns the natural height of the image.

**Note:** Most of the time the natural width is the actual width of the image sent by the server.
 Nevertheless, browsers can modify an image before pushing it to the renderer. For example, Chrome
 degrades the resolution of images on low-end devices. In such cases, `naturalWidth` will consider the width of the image modified
 by such browser interventions as the natural width, and returns this value.

Value
-----

 An integer value indicating the intrinsic width of the image, in CSS pixels. This is
 the width at which the image is naturally drawn when no constraint or specific value is
 established for the image. This natural width is corrected for the pixel density of the
 device on which it's being presented, unlike the value of
 `width`.

 If the intrinsic width is not available—either because the image does not specify an
 intrinsic width or because the image data is not available in order to obtain this
 information, `naturalWidth` returns 0.

Examples
--------

See `HTMLImageElement.naturalHeight` for example code that displays an image in both its natural "density-adjusted" size, and in its rendered size as altered by the page's CSS and other factors.

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

| Specification |
| --- |
| HTML Standard # dom-img-naturalwidth-dev |

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

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


HTMLImageElement: referrerPolicy property - Web APIs

HTMLImageElement: referrerPolicy property
=========================================

 The
 **`HTMLImageElement.referrerPolicy`**
 property reflects the HTML `referrerpolicy` attribute of the
 `<img>` element defining which referrer is sent when fetching the
 resource.

Value
-----

A string; one of the following:

`no-referrer`

 The `Referer` header will be omitted entirely. No referrer
 information is sent along with requests.

`no-referrer-when-downgrade`

 The URL is sent
 as a referrer when the protocol security level stays the same (e.g.HTTP→HTTP,
 HTTPS→HTTPS), but isn't sent to a less secure destination (e.g. HTTPS→HTTP).

`origin`

 Only send the origin of the document as the referrer in all cases.
 The document `https://example.com/page.html` will send the referrer
 `https://example.com/`.

`origin-when-cross-origin`

 Send a full URL when performing a same-origin request, but only send the origin of
 the document for other cases.

`same-origin`

 A referrer will be sent for same-site origins, but
 cross-origin requests will contain no referrer information.

`strict-origin`

 Only send the origin of the document as the referrer when the protocol security
 level stays the same (e.g. HTTPS→HTTPS), but don't send it to a less secure
 destination (e.g. HTTPS→HTTP).

`strict-origin-when-cross-origin` (default)

 This is the user agent's default behavior if no policy is specified. Send a full URL when performing a same-origin request, only send the origin when the
 protocol security level stays the same (e.g. HTTPS→HTTPS), and send no header to a
 less secure destination (e.g. HTTPS→HTTP).

`unsafe-url`

 Send a full URL when performing a same-origin or cross-origin request. This policy
 will leak origins and paths from TLS-protected resources to insecure origins.
 Carefully consider the impact of this setting.

Examples
--------

```js
const img = new Image();
img.src = "img/logo.png";
img.referrerPolicy = "origin";

const div = document.getElementById("divAround");
div.appendChild(img); // Fetch the image using the origin as the referrer
```

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

| Specification |
| --- |
| HTML Standard # dom-img-referrerpolicy |

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

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

See also
--------

* `HTMLAnchorElement.referrerPolicy`,
 `HTMLAreaElement.referrerPolicy`, and
 `HTMLIFrameElement.referrerPolicy`.


HTMLImageElement: hspace property - Web APIs

HTMLImageElement: hspace property
=================================

**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

 The
 *obsolete* **`hspace`** property of the
 `HTMLImageElement` interface specifies the number of pixels of empty
 space to leave empty on the left and right sides of the `<img>` element
 when laying out the page.

 This property reflects the HTML `hspace`
 attribute.

Value
-----

 An integer value specifying the width, in pixels, of the horizontal margin to apply to
 the left and right sides of the image.

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

 The value specified for `hspace` is mapped to the `margin-left`
 and `margin-right` properties to specify the width of those margins in
 pixels.

**Warning:** This property is obsolete. You should instead use the CSS
 `margin` property and its longhand forms to establish margins around
 an `<img>`.

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

| Specification |
| --- |
| HTML Standard # attr-img-hspace |

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

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


Basic concepts behind Web Audio API - Web APIs

Basic concepts behind Web Audio API
===================================

This article explains some of the audio theory behind how the features of the Web Audio API work to help you make informed decisions while designing how your app routes audio. If you are not already a sound engineer, it will give you enough background to understand why the Web Audio API works as it does.

Audio graphs
------------

The Web Audio API involves handling audio operations inside an audio context, and has been designed to allow *modular routing*. Each audio node performs a basic audio operation and is linked with one more other audio nodes to form an audio routing graph. Several sources with different channel layouts are supported, even within a single context. This modular design provides the flexibility to create complex audio functions with dynamic effects.

Audio nodes are linked via their inputs and outputs, forming a chain that starts with one or more sources, goes through one or more nodes, then ends up at a destination (although you don't have to provide a destination if you only want to visualize some audio data). A simple, typical workflow for web audio would look something like this:

1. Create the audio context.
2. Create audio sources inside the context (such as `<audio>`, an oscillator, or stream).
3. Create audio effects (such as the reverb, biquad filter, panner, or compressor nodes).
4. Choose the final destination for the audio (such as the user's computer speakers).
5. Connect the source nodes to zero or more effect nodes and then to the chosen destination.

**Note:** The channel notation is a numeric value, such as *2.0* or *5.1*, representing the number of audio channels available on a signal. The first number is the number of full frequency range audio channels the signal includes. The number appearing after the period indicates the number of those channels reserved for low-frequency effect (LFE) outputs; these are often called **subwoofers**.

![A simple box diagram with an outer box labeled Audio context and three inner boxes labeled Sources, Effects, and Destination. The three inner boxes have arrows between them pointing from left to right, indicating the flow of audio information.](/en-US/docs/Web/API/Web_Audio_API/Basic_concepts_behind_Web_Audio_API/webaudioapi_en.svg)

Each input or output is composed of one or more audio **channels**, which together represent a specific audio layout. Any discrete channel structure is supported, including *mono*, *stereo*, *quad*, *5.1*, and so on.

![Show the ability of audio nodes to connect via their inputs and outputs and the channels inside these inputs/outputs.](/en-US/docs/Web/API/Web_Audio_API/Basic_concepts_behind_Web_Audio_API/mdn.png)

You have several ways to obtain audio:

* Sound can be generated directly in JavaScript by an audio node (such as an oscillator).
* It can be created from raw PCM data (such as .WAV files or other formats supported by `decodeAudioData()`).
* It can be generated from HTML media elements, such as `<video>` or `<audio>`.
* It can be obtained from a WebRTC `MediaStream`, such as a webcam or microphone.
Audio data: what's in a sample
------------------------------

When an audio signal is processed, sampling happens. **Sampling** is the conversion of a continuous signal to a discrete signal. Put another way, a continuous sound wave, such as a band playing live, is converted into a sequence of digital samples (a discrete-time signal) that allows a computer to handle the audio in distinct blocks.

You'll find more information on the Wikipedia page *Sampling (signal processing)*.

Audio buffers: frames, samples, and channels
--------------------------------------------

An `AudioBuffer` is defined with three parameters:

* the number of channels (1 for mono, 2 for stereo, etc.),
* its length, meaning the number of sample frames inside the buffer,
* and the sample rate, the number of sample frames played per second.

A *sample* is a single 32-bit floating point value representing the value of the audio stream at each specific moment in time within a particular channel (left or right, if in the case of stereo). A *frame*, or *sample frame*, is the set of all values for all channels that will play at a specific moment in time: all the samples of all the channels that play at the same time (two for a stereo sound, six for 5.1, etc.).

The *sample rate* is the quantity of those samples (or frames, since all samples of a frame play at the same time) that will play in one second, measured in Hz. The higher the sample rate, the better the sound quality.

Let's look at a *mono* and a *stereo* audio buffer, each one second long at a rate of 44100Hz:

* The *mono* buffer will have 44,100 samples and 44,100 frames. The `length` property will be 44,100.
* The *stereo* buffer will have 88,200 samples but still 44,100 frames. The `length` property will still be 44100 since it equals the number of frames.

![A diagram showing several frames in an audio buffer in a long line, each one containing two samples, as the buffer has two channels, it is stereo.](/en-US/docs/Web/API/Web_Audio_API/Basic_concepts_behind_Web_Audio_API/sampleframe-english.png)

When a buffer plays, you will first hear the leftmost sample frame, then the one right next to it, then the next, *and so on*, until the end of the buffer. In the case of stereo, you will hear both channels simultaneously. Sample frames are handy because they are independent of the number of channels and represent time in an ideal way for precise audio manipulation.

**Note:** To get a time in seconds from a frame count, divide the number of frames by the sample rate. To get the number of frames from the number of samples, you only need to divide the latter value by the channel count.

Here are a couple of simple examples:

```js
const context = new AudioContext();
const buffer = new AudioBuffer(context, {
  numberOfChannels: 2,
  length: 22050,
  sampleRate: 44100,
});
```

**Note:** In digital audio, **44,100 Hz** (alternately represented as **44.1 kHz**) is a common sampling frequency. Why 44.1 kHz?

Firstly, because the hearing range of human ears is roughly 20 Hz to 20,000 Hz. Via the Nyquist–Shannon sampling theorem, the sampling frequency must be greater than twice the maximum frequency one wishes to reproduce. Therefore, the sampling rate has to be *greater* than 40,000 Hz.

Secondly, signals must be low-pass filtered before sampling, otherwise aliasing occurs. While an ideal low-pass filter would perfectly pass frequencies below 20 kHz (without attenuating them) and perfectly cut off frequencies above 20 kHz, in practice, a transition band is necessary, where frequencies are partly attenuated. The wider this transition band is, the easier and more economical it is to make an anti-aliasing filter. The 44.1 kHz sampling frequency allows for a 2.05 kHz transition band.

If you use this call above, you will get a stereo buffer with two channels that, when played back on an `AudioContext` running at 44100 Hz (very common, most normal sound cards run at this rate), will last for 0.5 seconds: 22,050 frames/44,100 Hz = 0.5 seconds.

```js
const context = new AudioContext();
const buffer = new AudioBuffer(context, {
  numberOfChannels: 1,
  length: 22050,
  sampleRate: 22050,
});
```

If you use this call, you will get a mono buffer (single-channel buffer) that, when played back on an `AudioContext` running at 44,100 Hz, will be automatically *resampled* to 44,100 Hz (and therefore yield 44,100 frames), and last for 1.0 second: 44,100 frames/44,100 Hz = 1 second.

**Note:** Audio resampling is very similar to image resizing. Say you've got a 16 x 16 image but want it to fill a 32 x 32 area. You resize (or resample) it. The result has less quality (it can be blurry or edgy, depending on the resizing algorithm), but it works, with the resized image taking up less space. Resampled audio is the same: you save space, but, in practice, you cannot correctly reproduce high-frequency content or treble sound.

### Planar versus interleaved buffers

The Web Audio API uses a planar buffer format. The left and right channels are stored like this:
```

LLLLLLLLLLLLLLLLRRRRRRRRRRRRRRRR (for a buffer of 16 frames)
```

This structure is widespread in audio processing, making it easy to process each channel independently.

The alternative is to use an interleaved buffer format:
```

LRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLR (for a buffer of 16 frames)
```

This format is prevalent for storing and playing back audio without much processing, for example: .WAV files or a decoded MP3 stream.

Because the Web Audio API is designed for processing, it exposes *only* planar buffers. It uses the planar format but converts the audio to the interleaved format when it sends it to the sound card for playback. Conversely, when the API decodes an MP3, it starts with the interleaved format and converts it to the planar format for processing.

Audio channels
--------------

Each audio buffer may contain different numbers of channels. Most modern audio devices use the basic *mono* (only one channel) and *stereo* (left and right channels) settings. Some more complex sets support *surround sound* settings (like *quad* and *5.1*), which can lead to a richer sound experience thanks to their high channel count. We usually represent the channels with the standard abbreviations detailed in the table below:

| Name | Channels |
| --- | --- |
| *Mono* | `0: M: mono` |
| *Stereo* | `0: L: left 1: R: right` |
| *Quad* | `0: L: left 1: R: right 2: SL: surround left 3: SR: surround right` |
| *5.1* | `0: L: left 1: R: right 2: C: center 3: LFE: subwoofer 4: SL: surround left 5: SR: surround right` |

### Up-mixing and down-mixing

When the numbers of channels of the input and the output don't match, up-mixing, or down-mixing, must be done. The following rules, controlled by setting the `AudioNode.channelInterpretation` property to `speakers` or `discrete`, apply:

| Interpretation | Input channels | Output channels | Mixing rules |
| --- | --- | --- | --- |
| `speakers` | `1` *(Mono)* | `2` *(Stereo)* | *Up-mix from mono to stereo*.The `M` input
 channel is used for both output channels (`L` and
 `R`).`output.L = input.Moutput.R = input.M` |
| `1` *(Mono)* | `4` *(Quad)* | *Up-mix from mono to quad.*The `M` input channel
 is used for non-surround output channels (`L` and
 `R`). Surround output channels (`SL` and
 `SR`) are silent.`output.L = input.Moutput.R = input.Moutput.SL = 0output.SR
= 0` |
| `1` *(Mono)* | `6` *(5.1)* | *Up-mix from mono to 5.1.*The `M` input channel
 is used for the center output channel (`C`). All the others
 (`L`, `R`, `LFE`, `SL`, and
 `SR`) are silent.`output.L = 0output.R = 0``output.C = input.Moutput.LFE = 0output.SL = 0output.SR
= 0` |
| `2` *(Stereo)* | `1` *(Mono)* | *Down-mix from stereo to mono*.Both input channels (`L`
 and `R`) are equally combined to produce the unique output
 channel (`M`).`output.M = 0.5 * (input.L + input.R)` |
| `2` *(Stereo)* | `4` *(Quad)* | *Up-mix from stereo to quad.*The `L` and
 `R` input channels are used for their non-surround respective
 output channels (`L` and `R`). Surround output
 channels (`SL` and `SR`) are silent.`output.L = input.Loutput.R = input.Routput.SL = 0output.SR
= 0` |
| `2` *(Stereo)* | `6` *(5.1)* | *Up-mix from stereo to 5.1.*The `L` and
 `R` input channels are used for their non-surround respective
 output channels (`L` and `R`). Surround output
 channels (`SL` and `SR`), as well as the center
 (`C`) and subwoofer (`LFE`) channels, are left
 silent.`output.L = input.Loutput.R = input.Routput.C = 0output.LFE
= 0output.SL = 0output.SR = 0` |
| `4` *(Quad)* | `1` *(Mono)* | *Down-mix from quad to mono*.All four input channels
 (`L`, `R`, `SL`, and `SR`)
 are equally combined to produce the unique output channel
 (`M`).`output.M = 0.25 * (input.L + input.R +` `input.SL + input.SR``)` |
| `4` *(Quad)* | `2` *(Stereo)* | *Down-mix from quad to stereo*.Both left input channels
 (`L` and `SL`) are equally combined to produce the
 unique left output channel (`L`). And similarly, both right
 input channels (`R` and `SR`) are equally combined
 to produce the unique right output channel (`R`).`output.L = 0.5 * (input.L + input.SL``)``output.R = 0.5 * (input.R + input.SR``)` |
| `4` *(Quad)* | `6` *(5.1)* | *Up-mix from quad to 5.1.*The `L`,
 `R`, `SL`, and `SR` input channels are
 used for their respective output channels (`L` and
 `R`). Center (`C`) and subwoofer
 (`LFE`) channels are left silent.`output.L = input.Loutput.R = input.Routput.C = 0output.LFE
= 0output.SL = input.SLoutput.SR = input.SR` |
| `6` *(5.1)* | `1` *(Mono)* | *Down-mix from 5.1 to mono.*The left (`L` and
 `SL`), right (`R` and `SR`) and central
 channels are all mixed together. The surround channels are slightly
 attenuated, and the regular lateral channels are power-compensated to
 make them count as a single channel by multiplying by `√2/2`.
 The subwoofer (`LFE`) channel is lost.`output.M = 0.7071 * (input.L + input.R) + input.C + 0.5 * (input.SL +
input.SR)` |
| `6` *(5.1)* | `2` *(Stereo)* | *Down-mix from 5.1 to stereo.*The central channel
 (`C`) is summed with each lateral surround channel (`SL`
 or `SR`) and mixed to each lateral channel. As it is mixed
 down to two channels, it is mixed at a lower power: in each case, it is
 multiplied by `√2/2`. The subwoofer (`LFE`)
 channel is lost.`output.L = input.L + 0.7071 * (input.C + input.SL)output.R =
input.R` `+ 0.7071 * (input.C + input.SR)` |
| `6` *(5.1)* | `4` *(Quad)* | *Down-mix from 5.1 to quad.*The central (`C`) is
 mixed with the lateral non-surround channels (`L` and
 `R`). As it is mixed down to two channels, it is mixed at a
 lower power: in each case, it is multiplied by `√2/2`. The
 surround channels are passed unchanged. The subwoofer (`LFE`)
 channel is lost.`output.L = input.L + 0.7071 * input.Coutput.R = input.R +
0.7071 * input.Coutput.SL = input.SLoutput.SR =
input.SR` |
| Other, non-standard layouts |
 Non-standard channel layouts behave as if
 `channelInterpretation` is set to
 `discrete`.The specification explicitly allows the future definition of new speaker layouts. Therefore, this fallback is not future-proof as the behavior of the browsers for a specific number of channels may change in the future.
  |
| `discrete` | any (`x`) | any (`y`) where `x<y` | *Up-mix discrete channels.*Fill each output channel with
 its input counterpart — that is, the input channel with the same index.
 Channels with no corresponding input channels are left silent.
  |
| any (`x`) | any (`y`) where `x>y` | *Down-mix discrete channels.*Fill each output channel with
 its input counterpart — that is, the input channel with the same index.
 Input channels with no corresponding output channels are dropped.
  |

Visualizations
--------------

In general, we get the output over time to produce audio visualizations, usually reading its gain or frequency data. Then, using a graphical tool, we turn the obtained data into a visual representation, such as a graph. The Web Audio API has an `AnalyserNode` available that doesn't alter the audio signal passing through it. Additionally, it outputs the audio data, allowing us to process it via a technology such as `<canvas>`.

![Without modifying the audio stream, the node allows to get the frequency and time-domain data associated with it, using an FFT.](/en-US/docs/Web/API/Web_Audio_API/Basic_concepts_behind_Web_Audio_API/fttaudiodata_en.svg)

You can grab data using the following methods:

`AnalyserNode.getFloatFrequencyData()`

Copies the current frequency data into a `Float32Array` array passed into it.

`AnalyserNode.getByteFrequencyData()`

Copies the current frequency data into a `Uint8Array` (unsigned byte array) passed into it.

`AnalyserNode.getFloatTimeDomainData()`

Copies the current waveform, or time-domain, data into a `Float32Array` array passed into it.

`AnalyserNode.getByteTimeDomainData()`

Copies the current waveform, or time-domain, data into a `Uint8Array` (unsigned byte array) passed into it.

**Note:** For more information, see our Visualizations with Web Audio API article.

Spatializations
---------------

Audio spatialization allows us to model the position and behavior of an audio signal at a certain point in physical space, simulating the listener hearing that audio. In the Web Audio API, spatialization is handled by the `PannerNode` and the `AudioListener`.

The panner uses right-hand Cartesian coordinates to describe the audio source's *position* as a vector and its *orientation* as a 3D directional cone. The cone can be pretty large, for example, for omnidirectional sources.

![The PannerNode defines a spatial position and orientation for a given signal.](/en-US/docs/Web/API/Web_Audio_API/Basic_concepts_behind_Web_Audio_API/pannernode_en.svg)

Similarly, the Web Audio API describes the listener using right-hand Cartesian coordinates: their *position* as one vector and their *orientation* as two direction vectors, *up* and *front*. These vectors define the direction of the top of the listener's head and the direction the listener's nose is pointing. The vectors are perpendicular to one another.

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

**Note:** For more information, see our Web audio spatialization basics article.

Fan-in and Fan-out
------------------

In audio terms, **fan-in** describes the process by which a `ChannelMergerNode` takes a series of *mono* input sources and outputs a single multi-channel signal:

![Fan-in process diagram. Multiple point-less arrows representing mono-input sources combine to output a single pointed arrow representing a single multi-channel signal](/en-US/docs/Web/API/Web_Audio_API/Basic_concepts_behind_Web_Audio_API/fanin.svg)

**Fan-out** describes the opposite process, whereby a `ChannelSplitterNode` takes a multi-channel input source and outputs multiple *mono* output signals:

![Fan-out process diagram. A single point-less arrow representing a multi-channel input source splits to output multiple pointed arrows representing multiple mono output signals](/en-US/docs/Web/API/Web_Audio_API/Basic_concepts_behind_Web_Audio_API/fanout.svg)


Using IIR filters - Web APIs

Using IIR filters
=================

The **`IIRFilterNode`** interface of the Web Audio API is an `AudioNode` processor that implements a general infinite impulse response (IIR) filter; this type of filter can be used to implement tone control devices and graphic equalizers, and the filter response parameters can be specified, so that it can be tuned as needed. This article looks at how to implement one, and use it in a simple example.

Demo
----

Our simple example for this guide provides a play/pause button that starts and pauses audio play, and a toggle that turns an IIR filter on and off, altering the tone of the sound. It also provides a canvas on which is drawn the frequency response of the audio, so you can see what effect the IIR filter has.

![A demo featuring a play button, and toggle to turn a filter on and off, and a line graph showing the filter frequencies returned after the filter has been applied.](/en-US/docs/Web/API/Web_Audio_API/Using_IIR_filters/iir-filter-demo.png)

You can check out the full demo here on Codepen. Also see the source code on GitHub. It includes some different coefficient values for different lowpass frequencies — you can change the value of the `filterNumber` constant to a value between 0 and 3 to check out the different available effects.

Browser support
---------------

IIR filters are supported well across modern browsers, although they have been implemented more recently than some of the more longstanding Web Audio API features, like Biquad filters.

The IIRFilterNode
-----------------

The Web Audio API now comes with an `IIRFilterNode` interface. But what is this and how does it differ from the `BiquadFilterNode` we have already?

An IIR filter is a **infinite impulse response filter**. It's one of two primary types of filters used in audio and digital signal processing. The other type is FIR — **finite impulse response filter**. There's a really good overview to IIF filters and FIR filters here.

A biquad filter is actually a *specific type* of infinite impulse response filter. It's a commonly-used type and we already have it as a node in the Web Audio API. If you choose this node the hard work is done for you. For instance, if you want to filter lower frequencies from your sound, you can set the type to `highpass` and then set which frequency to filter from (or cut off).

When you are using an `IIRFilterNode` instead of a `BiquadFilterNode` you are creating the filter yourself, rather than just choosing a pre-programmed type. So you can create a highpass filter, or a lowpass filter, or a more bespoke one. And this is where the IIR filter node is useful — you can create your own if none of the already available settings is right for what you want. As well as this, if your audio graph needed a highpass and a bandpass filter within it, you could just use one IIR filter node in place of the two biquad filter nodes you would otherwise need for this.

With the IIRFIlter node it's up to you to set what `feedforward` and `feedback` values the filter needs — this determines the characteristics of the filter. The downside is that this involves some complex maths.

If you are looking to learn more there's some information about the maths behind IIR filters here. This enters the realms of signal processing theory — don't worry if you look at it and feel like it's not for you.

If you want to play with the IIR filter node and need some values to help along the way, there's a table of already calculated values here; on pages 4 & 5 of the linked PDF the `an` values refer to the `feedForward` values and the `bn` values refer to the `feedback`. musicdsp.org is also a great resource if you want to read more about different filters and how they are implemented digitally.

With that all in mind, let's take a look at the code to create an IIR filter with the Web Audio API.

Setting our IIRFilter coefficients
----------------------------------

When creating an IIR filter, we pass in the `feedforward` and `feedback` coefficients as options (coefficients is how we describe the values). Both of these parameters are arrays, neither of which can be larger than 20 items.

When setting our coefficients, the `feedforward` values can't all be set to zero, otherwise nothing would be sent to the filter. Something like this is acceptable:

```js
const feedForward = [0.00020298, 0.0004059599, 0.00020298];
```

Our `feedback` values cannot start with zero, otherwise on the first pass nothing would be sent back:

```js
const feedBackward = [1.0126964558, -1.9991880801, 0.9873035442];
```

**Note:** These values are calculated based on the lowpass filter specified in the filter characteristics of the Web Audio API specification. As this filter node gains more popularity we should be able to collate more coefficient values.

Using an IIRFilter in an audio graph
------------------------------------

Let's create our context and our filter node:

```js
const audioCtx = new AudioContext();

const iirFilter = audioCtx.createIIRFilter(feedForward, feedBack);
```

We need a sound source to play. We set this up using a custom function, `playSoundNode()`, which creates a buffer source from an existing `AudioBuffer`, attaches it to the default destination, starts it playing, and returns it:

```js
function playSourceNode(audioContext, audioBuffer) {
  const soundSource = audioContext.createBufferSource();
  soundSource.buffer = audioBuffer;
  soundSource.connect(audioContext.destination);
  soundSource.start();
  return soundSource;
}
```

This function is called when the play button is pressed. The play button HTML looks like this:

```html
<button
 class="button-play"
 role="switch"
 data-playing="false"
 aria-pressed="false">
  Play
</button>
```

And the `click` event listener starts like so:

```js
playButton.addEventListener(
  "click",
  () => {
    if (playButton.dataset.playing === "false") {
      srcNode = playSourceNode(audioCtx, sample);
      // …
    }
  },
  false,
);
```

The toggle that turns the IIR filter on and off is set up in the similar way. First, the HTML:

```html
<button
 class="button-filter"
 role="switch"
 data-filteron="false"
 aria-pressed="false"
 aria-describedby="label"
 disabled></button>
```

The filter button's `click` handler then connects the `IIRFilter` up to the graph, between the source and the destination:

```js
filterButton.addEventListener(
  "click",
  () => {
    if (filterButton.dataset.filteron === "false") {
      srcNode.disconnect(audioCtx.destination);
      srcNode.connect(iirfilter).connect(audioCtx.destination);
      // …
    }
  },
  false,
);
```

### Frequency response

We only have one method available on `IIRFilterNode` instances, `getFrequencyResponse()`, this allows us to see what is happening to the frequencies of the audio being passed into the filter.

Let's draw a frequency plot of the filter we've created with the data we get back from this method.

We need to create three arrays. One of frequency values for which we want to receive the magnitude response and phase response for, and two empty arrays to receive the data. All three of these have to be of type `float32array` and all be of the same size.

```js
// arrays for our frequency response
const totalArrayItems = 30;
let myFrequencyArray = new Float32Array(totalArrayItems);
const magResponseOutput = new Float32Array(totalArrayItems);
const phaseResponseOutput = new Float32Array(totalArrayItems);
```

Let's fill our first array with frequency values we want data to be returned on:

```js
myFrequencyArray = myFrequencyArray.map((item, index) => 1.4 \*\* index);
```

We could go for a linear approach, but it's far better when working with frequencies to take a log approach, so let's fill our array with frequency values that get larger further on in the array items.

Now let's get our response data:

```js
iirFilter.getFrequencyResponse(
  myFrequencyArray,
  magResponseOutput,
  phaseResponseOutput,
);
```

We can use this data to draw a filter frequency plot. We'll do so on a 2d canvas context.

```js
// Create a canvas element and append it to our DOM
const canvasContainer = document.querySelector(".filter-graph");
const canvasEl = document.createElement("canvas");
canvasContainer.appendChild(canvasEl);

// Set 2d context and set dimensions
const canvasCtx = canvasEl.getContext("2d");
const width = canvasContainer.offsetWidth;
const height = canvasContainer.offsetHeight;
canvasEl.width = width;
canvasEl.height = height;

// Set background fill
canvasCtx.fillStyle = "white";
canvasCtx.fillRect(0, 0, width, height);

// Set up some spacing based on size
const spacing = width / 16;
const fontSize = Math.floor(spacing / 1.5);

// Draw our axis
canvasCtx.lineWidth = 2;
canvasCtx.strokeStyle = "grey";

canvasCtx.beginPath();
canvasCtx.moveTo(spacing, spacing);
canvasCtx.lineTo(spacing, height - spacing);
canvasCtx.lineTo(width - spacing, height - spacing);
canvasCtx.stroke();

// Axis is gain by frequency -> make labels
canvasCtx.font = `${fontSize}px sans-serif`;
canvasCtx.fillStyle = "grey";
canvasCtx.fillText("1", spacing - fontSize, spacing + fontSize);
canvasCtx.fillText("g", spacing - fontSize, (height - spacing + fontSize) / 2);
canvasCtx.fillText("0", spacing - fontSize, height - spacing + fontSize);
canvasCtx.fillText("Hz", width / 2, height - spacing + fontSize);
canvasCtx.fillText("20k", width - spacing, height - spacing + fontSize);

// Loop over our magnitude response data and plot our filter
canvasCtx.beginPath();

magResponseOutput.forEach((magResponseData, i) => {
  if (i === 0) {
    canvasCtx.moveTo(spacing, height - magResponseData \* 100 - spacing);
  } else {
    canvasCtx.lineTo(
      (width / totalArrayItems) \* i,
      height - magResponseData \* 100 - spacing,
    );
  }
});

canvasCtx.stroke();
```

Summary
-------

That's it for our IIRFilter demo. This should have shown you how to use the basics, and helped you to understand what it's useful for and how it works.


Web Audio API best practices - Web APIs

Web Audio API best practices
============================

There's no strict right or wrong way when writing creative code. As long as you consider security, performance, and accessibility, you can adapt to your own style. In this article, we'll share a number of *best practices* — guidelines, tips, and tricks for working with the Web Audio API.

Loading sounds/files
--------------------

There are four main ways to load sound with the Web Audio API and it can be a little confusing as to which one you should use.

When working with files, you are looking at either grabbing the file from an `HTMLMediaElement` (i.e. an `<audio>` or `<video>` element), or you're looking to fetch the file and decode it into a buffer. Both are legitimate ways of working, however, it's more common to use the former when you are working with full-length tracks, and the latter when working with shorter, more sample-like tracks.

Media elements have streaming support out of the box. The audio will start playing when the browser determines it can load the rest of the file before playing finishes. You can see an example of how to use this with the Web Audio API in the Using the Web Audio API tutorial.

You will, however, have more control if you use a buffer node. You have to request the file and wait for it to load (this section of our advanced article shows a good way to do it), but then you have access to the data directly, which means more precision, and more precise manipulation.

If you're looking to work with audio from the user's camera or microphone you can access it via the Media Capture and Streams API and the `MediaStreamAudioSourceNode` interface. This is good for WebRTC and situations where you might want to record or possibly analyze audio.

The last way is to generate your own sound, which can be done with either an `OscillatorNode` or by creating a buffer and populating it with your own data. Check out the tutorial here for creating your own instrument for information on creating sounds with oscillators and buffers.

Cross browser & legacy support
------------------------------

The Web Audio API specification is constantly evolving and like most things on the web, there are some issues with it working consistently across browsers. Here we'll look at options for getting around cross-browser problems.

There's the `standardized-audio-context` npm package, which creates API functionality consistently across browsers, filling holes as they are found. It's constantly in development and endeavors to keep up with the current specification.

There is also the option of libraries, of which there are a few depending on your use case. For a good all-rounder, howler.js is a good choice. It has cross-browser support and, provides a useful subset of functionality. Although it doesn't harness the full gamut of filters and other effects the Web Audio API comes with, you can do most of what you'd want to do.

If you are looking for sound creation or a more instrument-based option, tone.js is a great library. It provides advanced scheduling capabilities, synths, and effects, and intuitive musical abstractions built on top of the Web Audio API.

R-audio, from the BBC's Research & Development department, is a library of React components aiming to provide a "more intuitive, declarative interface to Web Audio". If you're used to writing JSX it might be worth looking at.

Autoplay policy
---------------

Browsers have started to implement an autoplay policy, which in general can be summed up as:

>
> "Create or resume context from inside a user gesture".
>
>
>

But what does that mean in practice? A user gesture has been interpreted to mean a user-initiated event, normally a `click` event. Browser vendors decided that Web Audio contexts should not be allowed to automatically play audio; they should instead be started by a user. This is because autoplaying audio can be really annoying and obtrusive. But how do we handle this?

When you create an audio context (either offline or online) it is created with a `state`, which can be `suspended`, `running`, or `closed`.

When working with an `AudioContext`, if you create the audio context from inside a `click` event the state should automatically be set to `running`. Here is a simple example of creating the context from inside a `click` event:

```js
const button = document.querySelector("button");
button.addEventListener(
  "click",
  () => {
    const audioCtx = new AudioContext();
    // Do something with the audio context
  },
  false,
);
```

If however, you create the context outside of a user gesture, its state will be set to `suspended` and it will need to be started after user interaction. We can use the same click event example here, test for the state of the context and start it, if it is suspended, using the `resume()` method.

```js
const audioCtx = new AudioContext();
const button = document.querySelector("button");

button.addEventListener(
  "click",
  () => {
    // check if context is in suspended state (autoplay policy)
    if (audioCtx.state === "suspended") {
      audioCtx.resume();
    }
  },
  false,
);
```

You might instead be working with an `OfflineAudioContext`, in which case you can resume the suspended audio context with the `startRendering()` method.

User control
------------

If your website or application contains sound, you should allow the user control over it, otherwise again, it will become annoying. This can be achieved by play/stop and volume/mute controls. The Using the Web Audio API tutorial goes over how to do this.

If you have buttons that switch audio on and off, using the ARIA `role="switch"` attribute on them is a good option for signalling to assistive technology what the button's exact purpose is, and therefore making the app more accessible. There's a demo of how to use it here.

As you work with a lot of changing values within the Web Audio API and will want to provide users with control over these, the `range input` is often a good choice of control to use. It's a good option as you can set minimum and maximum values, as well as increments with the `step` attribute.

Setting AudioParam values
-------------------------

There are two ways to manipulate `AudioNode` values, which are themselves objects of type `AudioParam` interface. The first is to set the value directly via the property. So for instance if we want to change the `gain` value of a `GainNode` we would do so thus:

```js
gainNode.gain.value = 0.5;
```

This will set our volume to half. However, if you're using any of the `AudioParam`'s defined methods to set these values, they will take precedence over the above property setting. If for example, you want the `gain` value to be raised to 1 in 2 seconds time, you can do this:

```js
gainNode.gain.setValueAtTime(1, audioCtx.currentTime + 2);
```

It will override the previous example (as it should), even if it were to come later in your code.

Bearing this in mind, if your website or application requires timing and scheduling, it's best to stick with the `AudioParam` methods for setting values. If you're sure it doesn't, setting it with the `value` property is fine.


Tools for analyzing Web Audio usage - Web APIs

Tools for analyzing Web Audio usage
===================================

While working on your Web Audio API code, you may find that you need tools to analyze the graph of nodes you create or to otherwise debug your work. This article discusses tools available to help you do that.

Chrome
------

A handy web audio inspector can be found in the Chrome Web Store.

Edge
----

*Add information for developers using Microsoft Edge.*

Firefox
-------

Firefox offers a native Web Audio Editor.

Safari
------

*Add information for developers working in Safari.*

See also
--------

* Web Audio API
* Using the Web Audio API