WritableStreamDefaultWriter: write() method - Web APIs

WritableStreamDefaultWriter: write() method
===========================================

 The **`write()`** method of the
 `WritableStreamDefaultWriter` interface writes a passed chunk of data to a
 `WritableStream` and its underlying sink, then returns a
 `Promise` that resolves to indicate the success or failure of the write
 operation.

 Note that what "success" means is up to the underlying sink; it might indicate that the
 chunk has been accepted, and not necessarily that it is safely saved to its ultimate
 destination.

Syntax
------

```js
write(chunk)
```

### Parameters

`chunk`

A block of binary data to pass to the `WritableStream`.

### Return value

 A `Promise`, which fulfills with the `undefined` upon a
 successful write, or rejects if the write fails or stream becomes errored before the
 writing process is initiated.

### Exceptions

`TypeError`

The target stream is not a writable stream, or it does not have an owner.

Examples
--------

 The following example shows the creation of a `WritableStream` with a custom
 sink and an API-supplied queuing strategy. It then calls a function called
 `sendMessage()`, passing the newly created stream and a string. Inside this
 function it calls the stream's `getWriter()` method, which returns an
 instance of `WritableStreamDefaultWriter`. A `forEach()` call is
 used to write each chunk of the string to the stream. Finally, `write()` and
 `close()` return promises that are processed to deal with success or failure
 of chunks and streams.

```js
const list = document.querySelector("ul");

function sendMessage(message, writableStream) {
  // defaultWriter is of type WritableStreamDefaultWriter
  const defaultWriter = writableStream.getWriter();
  const encoder = new TextEncoder();
  const encoded = encoder.encode(message);
  encoded.forEach((chunk) => {
    defaultWriter.ready
      .then(() => defaultWriter.write(chunk))
      .then(() => {
        console.log("Chunk written to sink.");
      })
      .catch((err) => {
        console.log("Chunk error:", err);
      });
  });
  // Call ready again to ensure that all chunks are written
  // before closing the writer.
  defaultWriter.ready
    .then(() => {
      defaultWriter.close();
    })
    .then(() => {
      console.log("All chunks written");
    })
    .catch((err) => {
      console.log("Stream error:", err);
    });
}

const decoder = new TextDecoder("utf-8");
const queuingStrategy = new CountQueuingStrategy({ highWaterMark: 1 });
let result = "";
const writableStream = new WritableStream(
  {
    // Implement the sink
    write(chunk) {
      return new Promise((resolve, reject) => {
        const buffer = new ArrayBuffer(1);
        const view = new Uint8Array(buffer);
        view[0] = chunk;
        const decoded = decoder.decode(view, { stream: true });
        const listItem = document.createElement("li");
        listItem.textContent = `Chunk decoded: ${decoded}`;
        list.appendChild(listItem);
        result += decoded;
        resolve();
      });
    },
    close() {
      const listItem = document.createElement("li");
      listItem.textContent = `[MESSAGE RECEIVED] ${result}`;
      list.appendChild(listItem);
    },
    abort(err) {
      console.log("Sink error:", err);
    },
  },
  queuingStrategy,
);

sendMessage("Hello, world.", writableStream);
```

You can find the full code in our Simple writer example.

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

| Specification |
| --- |
| Streams Standard # ref-for-default-writer-write①② |

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

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


WritableStreamDefaultWriter: desiredSize property - Web APIs

WritableStreamDefaultWriter: desiredSize property
=================================================

 The **`desiredSize`** read-only property of the
 `WritableStreamDefaultWriter` interface returns the desired size required
 to fill the stream's internal queue.

Value
-----

An integer. Note that this can be negative if the queue is over-full.

 The value will be `null` if the stream cannot be successfully written to
 (due to either being errored, or having an abort queued up), and zero if the stream is
 closed.

### Exceptions

`TypeError`

The writer's lock is released.

Examples
--------

```js
const writableStream = new WritableStream(
  {
    write(chunk) {
      // ...
    },
    close() {
      // ...
    },
    abort(err) {
      // ...
    },
  },
  queuingStrategy,
);

// ...

const writer = writableStream.getWriter();

// ...

// return stream's desired size
let size = writer.desiredSize;
```

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

| Specification |
| --- |
| Streams Standard # ref-for-default-writer-desired-size⑥ |

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

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


WritableStreamDefaultWriter: releaseLock() method - Web APIs

WritableStreamDefaultWriter: releaseLock() method
=================================================

 The **`releaseLock()`** method of the
 `WritableStreamDefaultWriter` interface releases the writer's lock on the
 corresponding stream. After the lock is released, the writer is no longer active. If the
 associated stream is errored when the lock is released, the writer will appear errored
 in the same way from now on; otherwise, the writer will appear closed.

Syntax
------

```js
releaseLock()
```

### Parameters

None.

### Return value

None (`undefined`).

Examples
--------

```js
const writableStream = new WritableStream(
  {
    write(chunk) {
      // ...
    },
    close() {
      // ...
    },
    abort(err) {
      // ...
    },
  },
  queuingStrategy,
);

// ...

const writer = writableStream.getWriter();

// ...

// release writer's lock on the stream when desired
writer.releaseLock();
```

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

| Specification |
| --- |
| Streams Standard # ref-for-default-writer-release-lock② |

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

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


WritableStreamDefaultWriter: ready property - Web APIs

WritableStreamDefaultWriter: ready property
===========================================

 The **`ready`** read-only property of the
 `WritableStreamDefaultWriter` interface returns a `Promise`
 that resolves when the desired size of the stream's internal queue transitions from
 non-positive to positive, signaling that it is no longer applying backpressure.

Value
-----

A `Promise`.

Examples
--------

 The following example shows two uses of the `ready` property. The first uses
 `ready` to ensure that the `WritableStream` is done writing and
 thus able to receive data before sending a binary chunk. The second also checks whether
 the `WritableStream` is done writing, but this time because the writing
 must be finished before the writer can be closed.

```js
function sendMessage(message, writableStream) {
  // defaultWriter is of type WritableStreamDefaultWriter
  const defaultWriter = writableStream.getWriter();
  const encoder = new TextEncoder();
  const encoded = encoder.encode(message);
  encoded.forEach((chunk) => {
    // Make sure the stream and its writer are able to
    // receive data.
    defaultWriter.ready
      .then(() => defaultWriter.write(chunk))
      .then(() => {
        console.log("Chunk written to sink.");
      })
      .catch((err) => {
        console.error(`Chunk error: ${err}`);
      });
    // Call ready again to ensure that all chunks are written
    // before closing the writer.
    defaultWriter.ready
      .then(() => defaultWriter.close())
      .then(() => {
        console.log("All chunks written");
      })
      .catch((err) => {
        console.error(`Stream error: ${err}`);
      });
  });
}
```

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

| Specification |
| --- |
| Streams Standard # ref-for-default-writer-ready⑨ |

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

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


WritableStreamDefaultWriter: abort() method - Web APIs

WritableStreamDefaultWriter: abort() method
===========================================

 The **`abort()`** method of the
 `WritableStreamDefaultWriter` interface aborts the stream, signaling that
 the producer can no longer successfully write to the stream and it is to be immediately
 moved to an error state, with any queued writes discarded.

 If the writer is active, the `abort()` method behaves the same as that for
 the associated stream (`WritableStream.abort()`). If not, it returns a
 rejected promise.

Syntax
------

```js
abort()
abort(reason)
```

### Parameters

`reason` Optional

A string representing a human-readable reason for the abort.

### Return value

 A `Promise`, which fulfills to `undefined` when the stream is aborted, or
 rejects with an error if the writer was inactive or the receiver stream is invalid.

### Exceptions

`TypeError`

 The stream you are trying to abort is not a `WritableStream`, or it is
 locked.

Examples
--------

```js
const writableStream = new WritableStream(
  {
    write(chunk) {
      // ...
    },
    close() {
      // ...
    },
    abort(err) {
      // ...
    },
  },
  queuingStrategy,
);

// ...

const writer = writableStream.getWriter();

// ...

// abort the stream when desired
await writer.abort("WritableStream aborted. Reason: ...");
```

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

| Specification |
| --- |
| Streams Standard # ref-for-default-writer-abort④ |

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

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


WritableStreamDefaultWriter: WritableStreamDefaultWriter() constructor - Web APIs

WritableStreamDefaultWriter: WritableStreamDefaultWriter() constructor
======================================================================

 The **`WritableStreamDefaultWriter()`**
 constructor creates a new `WritableStreamDefaultWriter` object instance.

**Note:** You generally wouldn't use this constructor manually; instead,
 you'd use the `WritableStream.getWriter()` method.

Syntax
------

```js
new WritableStreamDefaultWriter(stream)
```

### Parameters

`stream`

The `WritableStream` to be written to.

### Return value

An instance of the `WritableStreamDefaultWriter` object.

### Exceptions

`TypeError`

 The provided `stream` value is not a `WritableStream`, or it
 is locked to another writer already.

Examples
--------

 The following example shows the creation of a `WritableStream` with a custom
 sink and an API-supplied queuing strategy. It then calls a function called
 `sendMessage()`, passing the newly created stream and a string. Inside this
 function it calls the stream's `getWriter()` method, which returns an
 instance of `WritableStreamDefaultWriter`. A `forEach()` call is
 used to write each chunk of the string to the stream. Finally, `write()` and
 `close()` return promises that are processed to deal with success or failure
 of chunks and streams.

```js
const list = document.querySelector("ul");

function sendMessage(message, writableStream) {
  // defaultWriter is of type WritableStreamDefaultWriter
  const defaultWriter = writableStream.getWriter();
  const encoder = new TextEncoder();
  const encoded = encoder.encode(message, { stream: true });
  encoded.forEach((chunk) => {
    defaultWriter.ready
      .then(() => defaultWriter.write(chunk))
      .then(() => {
        console.log("Chunk written to sink.");
      })
      .catch((err) => {
        console.log("Chunk error:", err);
      });
  });
  // Call ready again to ensure that all chunks are written
  // before closing the writer.
  defaultWriter.ready
    .then(() => {
      defaultWriter.close();
    })
    .then(() => {
      console.log("All chunks written");
    })
    .catch((err) => {
      console.log("Stream error:", err);
    });
}

const decoder = new TextDecoder("utf-8");
const queuingStrategy = new CountQueuingStrategy({ highWaterMark: 1 });
let result = "";
const writableStream = new WritableStream(
  {
    // Implement the sink
    write(chunk) {
      return new Promise((resolve, reject) => {
        const buffer = new ArrayBuffer(1);
        const view = new Uint8Array(buffer);
        view[0] = chunk;
        const decoded = decoder.decode(view, { stream: true });
        const listItem = document.createElement("li");
        listItem.textContent = `Chunk decoded: ${decoded}`;
        list.appendChild(listItem);
        result += decoded;
        resolve();
      });
    },
    close() {
      const listItem = document.createElement("li");
      listItem.textContent = `[MESSAGE RECEIVED] ${result}`;
      list.appendChild(listItem);
    },
    abort(err) {
      console.log("Sink error:", err);
    },
  },
  queuingStrategy,
);

sendMessage("Hello, world.", writableStream);
```

You can find the full code in our Simple writer example.

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

| Specification |
| --- |
| Streams Standard # ref-for-default-writer-constructor① |

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

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


WritableStreamDefaultWriter: closed property - Web APIs

WritableStreamDefaultWriter: closed property
============================================

 The **`closed`** read-only property of the
 `WritableStreamDefaultWriter` interface returns a
 `Promise` that fulfills if the stream becomes closed, or rejects if
 the stream errors or the writer's lock is released.

Value
-----

A `Promise`.

Examples
--------

```js
const writableStream = new WritableStream(
  {
    start(controller) {},
    write(chunk, controller) {
      // ...
    },
    close(controller) {
      // ...
    },
    abort(err) {
      // ...
    },
  },
  queuingStrategy,
);

// ...

const writer = writableStream.getWriter();

// ..

// check if the stream is closed
writer.closed.then(() => {
  console.log("writer closed");
});
```

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

| Specification |
| --- |
| Streams Standard # ref-for-default-writer-closed② |

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

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


WritableStreamDefaultWriter: close() method - Web APIs

WritableStreamDefaultWriter: close() method
===========================================

 The **`close()`** method of the
 `WritableStreamDefaultWriter` interface closes the associated writable
 stream.

 The underlying sink will finish processing any previously-written chunks, before
 invoking the close behavior. During this time any further attempts to write will fail
 (without erroring the stream).

Syntax
------

```js
close()
```

### Parameters

None.

### Return value

 A `Promise`, which fulfills with the `undefined` if all
 remaining chunks were successfully written before the close, or rejects with an error if
 a problem was encountered during the process.

### Exceptions

`TypeError`

The stream you are trying to close is not a `WritableStream`.

Examples
--------

 The following example shows the creation of a `WritableStream` with a custom
 sink and an API-supplied queuing strategy. It then calls a function called
 `sendMessage()`, passing the newly created stream and a string. Inside this
 function it calls the stream's `getWriter()` method, which returns an
 instance of `WritableStreamDefaultWriter`. Each chunk of the
 encoded string is written to the stream using the `write()` method, and the
 `forEach()` method of the encoded `Uint8Array` to process it byte-by-byte.
 Finally, `close()` is called and the Promise it returns is handled to deal
 with success (or any failures) of the chunked write operations.

```js
const list = document.querySelector("ul");

function sendMessage(message, writableStream) {
  // defaultWriter is of type WritableStreamDefaultWriter
  const defaultWriter = writableStream.getWriter();
  const encoder = new TextEncoder();
  const encoded = encoder.encode(message);
  encoded.forEach((chunk) => {
    defaultWriter.ready
      .then(() => {
        defaultWriter.write(chunk);
      })
      .then(() => {
        console.log("Chunk written to sink.");
      })
      .catch((err) => {
        console.log("Chunk error:", err);
      });
  });
  // Call ready again to ensure that all chunks are written
  // before closing the writer.
  defaultWriter.ready
    .then(() => {
      defaultWriter.close();
    })
    .then(() => {
      console.log("All chunks written");
    })
    .catch((err) => {
      console.log("Stream error:", err);
    });
}

const decoder = new TextDecoder("utf-8");
const queuingStrategy = new CountQueuingStrategy({ highWaterMark: 1 });
let result = "";
const writableStream = new WritableStream(
  {
    // Implement the sink
    write(chunk) {
      return new Promise((resolve, reject) => {
        const buffer = new ArrayBuffer(1);
        const view = new Uint8Array(buffer);
        view[0] = chunk;
        const decoded = decoder.decode(view, { stream: true });
        const listItem = document.createElement("li");
        listItem.textContent = `Chunk decoded: ${decoded}`;
        list.appendChild(listItem);
        result += decoded;
        resolve();
      });
    },
    close() {
      const listItem = document.createElement("li");
      listItem.textContent = `[MESSAGE RECEIVED] ${result}`;
      list.appendChild(listItem);
    },
    abort(err) {
      console.log("Sink error:", err);
    },
  },
  queuingStrategy,
);

sendMessage("Hello, world.", writableStream);
```

You can view a live demonstration of this at our simple writer example.

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

| Specification |
| --- |
| Streams Standard # ref-for-default-writer-close⑦ |

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

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


FileSystemEntry: isFile property - Web APIs

FileSystemEntry: isFile property
================================

 The read-only **`isFile`** property of
 the `FileSystemEntry` interface is `true` if the entry
 represents a file (meaning it's a `FileSystemFileEntry`) and
 `false` if it's not.

 You can also use `isDirectory` to determine
 if the entry is a directory.

**Warning:** You should not assume that any entry which isn't a file is a directory or vice versa.
 There are other types of file descriptors on many operating systems. Be sure to use
 both `isDirectory` and `isFile` as needed to ensure that the
 entry is something you know how to work with.

Value
-----

A Boolean indicating whether or not the `FileSystemEntry` is a file.

Examples
--------

 This example shows how this property might be used to determine whether to process the
 entry as a directory or file. If the entry is neither, an error handler is called with
 an appropriate message.

```js
if (entry.isDirectory) {
  processSubdirectory(entry);
} else if (entry.isFile) {
  processFile(entry);
} else {
  displayErrorMessage("Unsupported file system entry specified.");
}
```

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

| Specification |
| --- |
| File and Directory Entries API # dom-filesystementry-isfile |

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

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

See also
--------

* File and Directory Entries API
* Introduction to the File and Directory Entries API
* `FileSystemEntry`
* `FileSystemEntry.isDirectory`
* `FileSystemFileEntry`


FileSystemEntry: moveTo() method - Web APIs

FileSystemEntry: moveTo() method
================================

**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.

**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

 The `FileSystemEntry` interface's method
 **`moveTo()`** moves the file
 specified by the entry to a new location on the file system, or renames the file if
 the destination directory is the same as the source.

 There are some typical
 restrictions on what you can do:

* A directory can't be moved into itself.
* An entry can't be moved into its parent directory unless you specify a new name.
 Specifying a new name lets `moveTo()` double as a rename operation.
* When moving a directory, the move is always recursive; you can't leave out
 subfolders.
* You can't move a file such that it replaces an existing directory, and you can't
 move a directory such that it replaces an existing file. However, a file can replace a
 file and a directory can replace a directory.
* You can only overwrite a directory if it's empty.
Syntax
------

```js
moveTo(newParent, newName)
moveTo(newParent, newName, successCallback)
moveTo(newParent, newName, successCallback, errorCallback)
```

### Parameters

`newParent`

 A `FileSystemDirectoryEntry` object specifying the destination
 directory for the move operation.

`newName` Optional

 If this parameter is provided, the entry is renamed to have this string as its new
 file or directory name.

`successCallback` Optional

 A function which is called when the move operation is successfully completed.
 Receives a single input parameter: a `FileSystemEntry` based object
 providing the moved item's new details.

`errorCallback` Optional

 An optional callback which is executed if an error occurs while moving the items.
 There's a single parameter: a `FileError` describing what went wrong.

### Return value

None (`undefined`).

### Errors

`FileError.INVALID_MODIFICATION_ERR`

 The requested operation involves an impossible change, such as moving a directory
 inside itself or one of its own child directories, or copying an item within the same
 directory without renaming it.

`FileError.QUOTA_EXCEEDED_ERR`

 The operation exceeded the user's storage quota, or there isn't enough storage space
 left to complete the operation.

Examples
--------

 This example shows how a temporary log file might be moved into a more permanent "log"
 directory when it exceeds a megabyte in size.

```js
workingDirectory.getFile(
  "tmp/log.txt",
  {},
  (fileEntry) => {
    fileEntry.getMetadata((metadata) => {
      if (metadata.size > 1048576) {
        workingDirectory.getDirectory(
          "log",
          {},
          (dirEntry) => {
            fileEntry.moveTo(dirEntry);
          },
          handleError,
        );
      }
    });
  },
  handleError,
);
```

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

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

See also
--------

* File and Directory Entries API
* Introduction to the File and Directory Entries API
* `FileSystemEntry.copyTo()`


FileSystemEntry: remove() method - Web APIs

FileSystemEntry: remove() method
================================

**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.

**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

 The `FileSystemEntry` interface's method
 **`remove()`** deletes the file
 or directory from the file system. Directories must be empty before they can be
 removed.

 To recursively remove a directory as well as all of its contents and its
 subdirectories, call `FileSystemDirectoryEntry.removeRecursively()`
 instead.

Syntax
------

```js
remove(successCallback)
remove(successCallback, errorCallback)
```

### Parameters

`successCallback`

A function which is called once the file has been successfully removed.

`errorCallback` Optional

An optional callback which is called if the attempt to remove the file fails.

### Return value

None (`undefined`).

### Errors

`FileError.INVALID_MODIFICATION_ERR`

 The specified entry was the file system's root directory, or the specified entry is
 a directory which isn't empty.

`FileError.INVALID_STATE_ERR`

 The file system's cached state is inconsistent with its state on disk, so the file
 could not be deleted for safety reasons.

`FileError.NO_MODIFICATION_ALLOWED_ERR`

The file system's state doesn't permit removing the file or directory.

`FileError.NOT_FOUND_ERR`

The file or directory doesn't exist.

`FileError.SECURITY_ERR`

 The entry couldn't be removed due to permissions or other access constraints, or
 because there are too many calls being made on file resources.

Examples
--------

This example deletes a temporary work file.

```js
workingDirectory.getFile(
  "tmp/workfile.json",
  {},
  (fileEntry) => {
    fileEntry.remove(() => {
      /\* the file was removed successfully \*/
    });
  },
  handleError,
);
```

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

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

See also
--------

* File and Directory Entries API
* Introduction to the File and Directory Entries API
* `FileSystemDirectoryEntry.removeRecursively()`


FileSystemEntry: getParent() method - Web APIs

FileSystemEntry: getParent() method
===================================

 The `FileSystemEntry` interface's method
 **`getParent()`** obtains a
 `FileSystemDirectoryEntry`.

Syntax
------

```js
getParent(successCallback, errorCallback)
getParent(successCallback)
```

### Parameters

`successCallback`

 A function which is called when the parent directory entry has been retrieved. The
 callback receives a single input parameter: a `FileSystemDirectoryEntry`
 object representing the parent directory. The parent of the root directory is
 considered to be the root directory, itself, so be sure to watch for that.

`errorCallback` Optional

 An optional callback which is executed if an error occurs. There's a single
 parameter: a `DOMException` describing what went wrong.

### Return value

None (`undefined`).

### Errors

`FileError.INVALID_STATE_ERR`

 The operation failed because the file system's state doesn't permit it. This can
 happen, for example, if the file system's cached state differs from the actual state
 of the file system.

`FileError.NOT_FOUND_ERR`

The specified path could not be found.

`FileError.SECURITY_ERR`

Security restrictions prohibit obtaining the parent directory's information.

Examples
--------

 This example renames the file specified by the variable `fileEntry` to
 `"newname.html"`.

```js
fileEntry.getParent(
  (parent) => {
    fileEntry.moveTo(parent, "newname.html", (updatedEntry) => {
      console.log(`File ${fileEntry.name} renamed to newname.html.`);
    });
  },
  (error) => {
    console.error(
      `An error occurred: Unable to rename ${fileEntry.name} to newname.html.`,
    );
  },
);
```

 This is accomplished by first obtaining a `FileSystemDirectoryEntry`
 object representing the directory the file is currently located in. Then
 `moveTo()` is used to rename the file within that
 directory.

Using promises
--------------

 Currently, there isn't a `Promise`-based version of this method. You can,
 however, create a simple helper function to adapt it, like this:

```js
function getParentPromise(entry) {
  return new Promise((resolve, reject) => {
    entry.getParent(resolve, reject);
  });
}
```

A similar approach can be taken elsewhere in the File and Directory Entries API.

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

| Specification |
| --- |
| File and Directory Entries API # dom-filesystementry-getparent |

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

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

See also
--------

* File and Directory Entries API
* Introduction to the File and Directory Entries API


FileSystemEntry: isDirectory property - Web APIs

FileSystemEntry: isDirectory property
=====================================

 The read-only **`isDirectory`**
 property of the `FileSystemEntry` interface is `true` if the
 entry represents a directory (meaning it's a `FileSystemDirectoryEntry`)
 and `false` if it's not.

 You can also use `isFile` to determine if the
 entry is a file.

**Warning:** You should not assume that any entry which isn't a directory is a file or vice versa.
 There are other types of file descriptors on many operating systems. Be sure to use
 both `isDirectory` and `isFile` as needed to ensure that the
 entry is something you know how to work with.

Value
-----

A Boolean indicating whether or not the `FileSystemEntry` is a directory.

Examples
--------

 This example shows how this property might be used to determine whether to process the
 entry as a directory or file. If the entry is neither, an error handler is called with
 an appropriate message.

```js
if (entry.isDirectory) {
  processSubdirectory(entry);
} else if (entry.isFile) {
  processFile(entry);
} else {
  displayErrorMessage("Unsupported file system entry specified.");
}
```

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

| Specification |
| --- |
| File and Directory Entries API # dom-filesystementry-isdirectory |

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

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

See also
--------

* File and Directory Entries API
* Introduction to the File and Directory Entries API
* `FileSystemEntry`
* `FileSystemEntry.isFile`
* `FileSystemDirectoryEntry`


FileSystemEntry: getMetadata() method - Web APIs

FileSystemEntry: getMetadata() method
=====================================

**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.

**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

 The `FileSystemEntry` interface's method
 **`getMetadata()`** obtains a
 `Metadata` object with information about the file system entry, such as
 its modification date and time and its size.

Syntax
------

```js
getMetadata(successCallback)
getMetadata(successCallback, errorCallback)
```

### Parameters

`successCallback`

 A function which is called when the copy operation is successfully completed.
 Receives a single input parameter: a `Metadata` object with information
 about the file.

`errorCallback` Optional

 An optional callback which is executed if an error occurs while looking up the
 metadata. There's a single parameter: a `FileError` describing what went
 wrong.

### Return value

None (`undefined`).

### Errors

`FileError.NOT_FOUND_ERR`

The `FileSystemEntry` refers to an item which doesn't exist.

`FileError.SECURITY_ERR`

Security restrictions prohibit obtaining the requested metadata.

Examples
--------

 This example checks the size of a log file in a temporary folder and, if it exceeds a
 megabyte, moves it into a different directory.

```js
workingDirectory.getFile(
  "tmp/log.txt",
  {},
  (fileEntry) => {
    fileEntry.getMetadata((metadata) => {
      if (metadata.size > 1048576) {
        workingDirectory.getDirectory(
          "log",
          {},
          (dirEntry) => {
            fileEntry.moveTo(dirEntry);
          },
          handleError,
        );
      }
    });
  },
  handleError,
);
```

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

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

See also
--------

* File and Directory Entries API
* Introduction to the File and Directory Entries API


FileSystemEntry: name property - Web APIs

FileSystemEntry: name property
==============================

 The read-only **`name`** property of
 the `FileSystemEntry` interface returns a string
 specifying the entry's name; this is the entry within its parent directory (the last
 component of the path as indicated by the `fullPath` property).

Value
-----

A string indicating the entry's name.

Examples
--------

 This example shows a function called `isFileWithExtension()` which returns
 true if the specified `FileSystemEntry` is both a file and the file's name
 ends with a given extension.

```js
function isFileWithExtension(entry, extension) {
  return entry.isFile && entry.name.endsWith(`.${extension}`);
}
```

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

| Specification |
| --- |
| File and Directory Entries API # dom-filesystementry-name |

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

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

See also
--------

* File and Directory Entries API
* Introduction to the File and Directory Entries API
* `FileSystemEntry`
* `FileSystemEntry.fullPath`


FileSystemEntry: toURL() method - Web APIs

FileSystemEntry: toURL() method
===============================

**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.

**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

 The `FileSystemEntry` interface's method
 **`toURL()`** creates and
 returns a string containing a URL which can be used to identify the file system entry.
 This is done by exposing a new URL scheme—`filesystem:`—that can be used as
 the value of `src` and `href` attributes.

Syntax
------

```js
toURL()
toURL(mimeType)
```

### Parameters

`mimeType` Optional

 An optional string specifying the MIME type to use when interpreting the file. This
 can be used to help deal with files whose types aren't recognized automatically by the
 user agent. If this parameter is omitted, the user agent uses its standard algorithms
 to identify the file.

### Return value

 A string containing a URL that can then be used as a document
 reference in HTML content, or an empty string if the URL can't be generated (such as if
 the file system implementation doesn't support `toURL()`).

Examples
--------

 If you have a `FileSystemFileEntry` corresponding to an image file in a
 file system available to your website or app, you can call `toURL()` to get
 its URL for use in HTML. If your site is located at
 `http://my-awesome-website.woot`, and you have a temporary file system that
 contains an image file named `awesomesauce.jpg`, the URL returned by
 `toURL()` might be (depending on the browser's implementation) something like
 `"filesystem:http://my-awesome-website.woot/temporary/awesomesauce.jpg"`.

Code that makes use of this might look like this:

```js
let img = document.createElement("img");

img.src = imageFileEntry.toURL();
document.body.appendChild(img);
```

 Assuming the scenario mentioned before the code, the result would be HTML that looks
 like this being appended to the end of the document:

```html
<img
 src="filesystem:http://my-awesome-website.woot/temporary/awesomesauce.jpg" />
```

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

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

See also
--------

* File and Directory Entries API
* Introduction to the File and Directory Entries API
* `FileSystemDirectoryEntry.removeRecursively()`


FileSystemEntry: filesystem property - Web APIs

FileSystemEntry: filesystem property
====================================

 The read-only **`filesystem`**
 property of the `FileSystemEntry` interface contains a
 `FileSystem` object that represents the file system on which the entry
 resides.

Value
-----

 A `FileSystem` representing the file system on which the file or directory
 described by the `FileSystemEntry` is located.

Examples
--------

 This example obtains a `FileSystemDirectoryEntry` for the root directory
 of the file system containing a file.

```js
let rootDirEntry = fileEntry.filesystem.root;
```

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

| Specification |
| --- |
| File and Directory Entries API # dom-filesystementry-filesystem |

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

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

See also
--------

* File and Directory Entries API
* Introduction to the File and Directory Entries API
* `FileSystemEntry`
* `FileSystem`


FileSystemEntry: copyTo() method - Web APIs

FileSystemEntry: copyTo() method
================================

**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.

**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

 The `FileSystemEntry` interface's method
 **`copyTo()`** copies the file
 specified by the entry to a new location on the file system.

 There are some
 typical restrictions on what you can do:

* A directory can't be copied into itself.
* An entry can't be copied into its parent directory unless you specify a new name.
* When copying a directory, the copy is always recursive; you can't leave out
 subfolders.
Syntax
------

```js
copyTo(newParent)
copyTo(newParent, newName)
copyTo(newParent, newName, successCallback)
copyTo(newParent, newName, successCallback, errorCallback)
```

### Parameters

`newParent`

 A `FileSystemDirectoryEntry` object specifying the destination
 directory for the copy operation.

`newName` Optional

 If this parameter is provided, the copy is given this string as its new file or
 directory name.

`successCallback` Optional

 A function which is called when the copy operation is successfully completed.
 Receives a single input parameter: a `FileSystemEntry` based object
 providing the copied item's new details.

`errorCallback` Optional

 An optional callback which is executed if an error occurs while copying the items.
 There's a single parameter: a `FileError` describing what went wrong.

### Return value

None (`undefined`).

### Errors

`FileError.INVALID_MODIFICATION_ERR`

 The requested operation involves an impossible change, such as moving a directory
 inside itself or one of its own child directories, or copying an item within the same
 directory without renaming it.

`FileError.QUOTA_EXCEEDED_ERR`

 The operation exceeded the user's storage quota, or there isn't enough storage space
 left to complete the operation.

Examples
--------

 This example shows how a temporary log file might be moved into a more permanent "log"
 directory.

```js
workingDirectory.getFile(
  "tmp/log.txt",
  {},
  (fileEntry) => {
    workingDirectory.getDirectory(
      "log",
      {},
      (dirEntry) => {
        fileEntry.copyTo(dirEntry);
      },
      handleError,
    );
  },
  handleError,
);
```

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

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

See also
--------

* File and Directory Entries API
* Introduction to the File and Directory Entries API


FileSystemEntry: fullPath property - Web APIs

FileSystemEntry: fullPath property
==================================

 The read-only **`fullPath`** property
 of the `FileSystemEntry` interface returns a string
 specifying the full, absolute path from the file system's root to the file represented
 by the entry.

 This can also be thought of as a path which is relative to the root directory, with a
 "/" prepended to it to make it absolute.

Value
-----

A string indicating the entry's full path.

Examples
--------

 This example shows a function which is called with a file system; it then gets a
 `FileSystemFileEntry` for a file named `data.json` and returns
 its full path.

```js
function gotFileSystem(fs) {
  let path = "";

  fs.root.getFile(
    "data.json",
    { create: true, exclusive: true },
    (entry) => {
      path = fullPath;
    },
    handleError(error),
  );

  return path;
}
```

 Obviously, this is somewhat contrived, since we know that the file's full path is
 `"/data.json"`, having just looked it up ourselves, but the concept holds up
 for scenarios in which you don't know it.

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

| Specification |
| --- |
| File and Directory Entries API # dom-filesystementry-fullpath |

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

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

See also
--------

* File and Directory Entries API
* Introduction to the File and Directory Entries API
* `FileSystemEntry`


GPUQuerySet: destroy() method - Web APIs

GPUQuerySet: destroy() method
=============================

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

 The **`destroy()`** method of the
 `GPUQuerySet` interface destroys the `GPUQuerySet`.

Syntax
------

```js
destroy()
```

### Parameters

None.

### Return value

None (`Undefined`).

Examples
--------

```js
const querySet = device.createQuerySet({
  type: "occlusion",
  count: 32,
});

// Some time later

querySet.destroy();
```

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

| Specification |
| --- |
| WebGPU # dom-gpuqueryset-destroy |

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

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

See also
--------

* The WebGPU API


GPUQuerySet: type property - Web APIs

GPUQuerySet: type property
==========================

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

 The **`type`** read-only property of the
 `GPUQuerySet` interface is an enumerated value specifying the type of queries managed by the `GPUQuerySet`.

Value
-----

An enumerated value. Possible values are:

`"occlusion"`

The `GPUQuerySet` manages occlusion queries.

`"timestamp"`

The `GPUQuerySet` manages timestamp queries.

Examples
--------

See the main `GPUQuerySet` page for an example.

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

| Specification |
| --- |
| WebGPU # dom-gpuqueryset-type |

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

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

See also
--------

* The WebGPU API


GPUQuerySet: label property - Web APIs

GPUQuerySet: label property
===========================

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

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

This can be set by providing a `label` property in the descriptor object passed into the originating `GPUDevice.createQuerySet()` call, or you can get and set it directly on the `GPUQuerySet` object.

Value
-----

A string. If this has not been previously set as described above, it will be an empty string.

Examples
--------

Setting and getting a label via `GPUQuerySet.label`:

```js
const querySet = device.createQuerySet({
  type: "occlusion",
  count: 32,
});

querySet.label = "myqueryset";

console.log(querySet.label); // "myqueryset"
```

Setting a label via the originating `GPUDevice.createQuerySet()` call, and then getting it via `GPUQuerySet.label`:

```js
const querySet = device.createQuerySet({
  type: "occlusion",
  count: 32,
  label: "myqueryset",
});

console.log(querySet.label); // "myqueryset"
```

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

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

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

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

See also
--------

* The WebGPU API


GPUQuerySet: count property - Web APIs

GPUQuerySet: count property
===========================

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

 The **`count`** read-only property of the
 `GPUQuerySet` interface is a number specifying the number of queries managed by the `GPUQuerySet`.

Value
-----

A number.

Examples
--------

See the main `GPUQuerySet` page for an example.

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

| Specification |
| --- |
| WebGPU # dom-gpuqueryset-count |

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

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

See also
--------

* The WebGPU API


DOMPointReadOnly: z property - Web APIs

DOMPointReadOnly: z property
============================

 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 `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 `NaN` or `±Infinity`).

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

| Specification |
| --- |
| Geometry Interfaces Module Level 1 # dom-dompointreadonly-z |

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

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

See also
--------

* The other coordinate properties: `x`,
 `y`, and the perspective value,
 `w`.


DOMPointReadOnly: w property - Web APIs

DOMPointReadOnly: w property
============================

 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 `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 `NaN` or
 `±Infinity`). The default is `1.0`.

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

| Specification |
| --- |
| Geometry Interfaces Module Level 1 # dom-dompointreadonly-w |

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

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

See also
--------

* The other coordinate properties: `x`,
 `y`, and `z`.


DOMPointReadOnly: y property - Web APIs

DOMPointReadOnly: y property
============================

 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 `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 `NaN` or `±Infinity`).

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

| Specification |
| --- |
| Geometry Interfaces Module Level 1 # dom-dompointreadonly-y |

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

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

See also
--------

* The other coordinate properties: `x`,
 `z`, and the perspective value,
 `w`.


DOMPointReadOnly: x property - Web APIs

DOMPointReadOnly: x property
============================

 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 `NaN` or `±Infinity`).

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

| Specification |
| --- |
| Geometry Interfaces Module Level 1 # dom-dompointreadonly-x |

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

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

See also
--------

* The other coordinate properties: `y`,
 `z`, and the perspective value,
 `w`.


DOMPointReadOnly: DOMPointReadOnly() constructor - Web APIs

DOMPointReadOnly: DOMPointReadOnly() constructor
================================================

 The **`DOMPointReadOnly()`**
 constructor returns a new `DOMPointReadOnly` object representing a point
 in 2D or 3D space, optionally with perspective, whose values cannot be altered by
 script code.

Syntax
------

```js
new DOMPointReadOnly()
new DOMPointReadOnly(x)
new DOMPointReadOnly(x, y)
new DOMPointReadOnly(x, y, z)
new DOMPointReadOnly(x, y, z, w)
```

### Parameters

`x` Optional

 The value of the horizontal coordinate, x, as a floating point number. The default
 value is 0.

`y` Optional

 The value of the vertical coordinate, y, as a floating point number. The default
 value is 0.

`z` Optional

 The value of the depth coordinate, z, as a floating point number. The default value
 is 0.

`w` Optional

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 ±`Infinity` and `NaN`.

### Return value

 A new `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
--------------

| Specification |
| --- |
| Geometry Interfaces Module Level 1 # dom-dompointreadonly-dompointreadonly |

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

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


DOMPointReadOnly: fromPoint() static method - Web APIs

DOMPointReadOnly: fromPoint() static method
===========================================

 The static **`DOMPointReadOnly`**
 method `fromPoint()` creates and returns a new
 `DOMPointReadOnly` object given a source point.

 You can also create a new `DOMPointReadOnly` object using the
 `new DOMPointReadOnly()` constructor.

Syntax
------

```js
DOMPointReadOnly.fromPoint(sourcePoint)
```

### Parameters

`sourcePoint`

 A `DOMPoint` or `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 `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 `x` and `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
 `DOMPoint`, using `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
--------------

| Specification |
| --- |
| Geometry Interfaces Module Level 1 # dom-dompointreadonly-frompoint |

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

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


DOMPointReadOnly: toJSON() method - Web APIs

DOMPointReadOnly: toJSON() method
=================================

 The `DOMPointReadOnly` method
 `toJSON()` returns an object giving the
 JSON form of the point object.

Syntax
------

```js
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 `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
--------------

| Specification |
| --- |
| Geometry Interfaces Module Level 1 # dom-dompointreadonly-tojson |

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

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


HTMLCanvasElement: height property - Web APIs

HTMLCanvasElement: height property
==================================

 The **`HTMLCanvasElement.height`** property is a
 positive `integer` reflecting the `height` HTML
 attribute of the `<canvas>` element interpreted in CSS pixels. When the
 attribute is not specified, or if it is set to an invalid value, like a negative, the
 default value of `150` is used.

 This is one of the two properties, the other being
 `HTMLCanvasElement.width`, that controls the size of the canvas.

Value
-----

A number.

Examples
--------

Given this `<canvas>` element:

```html
<canvas id="canvas" width="300" height="300"></canvas>
```

You can get the height of the canvas with the following code:

```js
const canvas = document.getElementById("canvas");
console.log(canvas.height); // 300
```

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

| Specification |
| --- |
| HTML Standard # dom-canvas-height |

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

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

See also
--------

* `HTMLCanvasElement`: Interface used to define the `HTMLCanvasElement.height` property
* `HTMLCanvasElement.width`: Other property used to control the size of the canvas
* `HTMLImageElement.width`
* `HTMLObjectElement.width`
* `HTMLVideoElement.width`


HTMLCanvasElement: contextrestored event - Web APIs

HTMLCanvasElement: contextrestored event
========================================

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
**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

The **`contextrestored`** event of the Canvas API is fired if the user agent restores the backing storage for a `CanvasRenderingContext2D`.

You can redraw, re-retrieve resources, and reinitialize the state of your context after receiving this event.

Syntax
------

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

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

oncontextrestored = (event) => {};
```

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

A generic `Event`.

Example
-------

The code fragment below detects the context restored event.

```js
const canvas = document.getElementById("canvas");

canvas.addEventListener(
  "contextrestored",
  (e) => {
    console.log(e);
    // call to redrawCanvas() or similar
  },
  false,
);
```

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

| Specification |
| --- |
| HTML Standard # event-contextrestored |

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

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

See also
--------

* `HTMLCanvasElement: contextlost` event
* `CanvasRenderingContext2D.isContextLost()`


HTMLCanvasElement: webglcontextcreationerror event - Web APIs

HTMLCanvasElement: webglcontextcreationerror event
==================================================

The **`webglcontextcreationerror`** event of the WebGL API is fired if the user agent is unable to create a `WebGLRenderingContext` context.

This event has a `WebGLContextEvent.statusMessage` property, which can contain a platform dependent string with more information about the failure.

This event does not bubble.

Syntax
------

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

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

onwebglcontextcreationerror = (event) => {};
```

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

A `WebGLContextEvent`. Inherits from `Event`.

Event

WebGLContextEventEvent properties
----------------

*This interface inherits properties from its parent interface, `Event`.*

`WebGLContextEvent.statusMessage`

A read-only property containing additional information about the event.

Example
-------

```js
const canvas = document.getElementById("canvas");

canvas.addEventListener(
  "webglcontextcreationerror",
  (e) => {
    console.log(e.statusMessage || "Unknown error");
  },
  false,
);

const gl = canvas.getContext("webgl");
// logs statusMessage or "Unknown error" if unable to create WebGL context
```

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

| Specification |
| --- |
| WebGL Specification # 5.15.4 |

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

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

See also
--------

* `WebGLContextEvent`
* `WebGLRenderingContext.isContextLost()`
* `WEBGL_lose_context`, `WEBGL_lose_context.loseContext()`, `WEBGL_lose_context.restoreContext()`


HTMLCanvasElement: captureStream() method - Web APIs

HTMLCanvasElement: captureStream() method
=========================================

 The **`captureStream()`** method of the `HTMLCanvasElement` interface returns a `MediaStream`
 which includes a `CanvasCaptureMediaStreamTrack` containing a real-time video capture of the canvas's contents.

Syntax
------

```js
captureStream()
captureStream(frameRate)
```

### Parameters

`frameRate` Optional

 A double-precision floating-point value that indicates the rate of capture of each
 frame. If not set, a new frame will be captured each time the canvas changes; if set
 to `0`, frames will not be captured automatically; instead, they will only
 be captured when the returned track's
 `requestFrame()` method is
 called.

### Return value

 A reference to a `MediaStream` object, which has a single
 `CanvasCaptureMediaStreamTrack` in it.

### Exceptions

`NotSupportedError` `DOMException`

Thrown if the value of `frameRate` is negative.

`SecurityError` `DOMException`

 The canvas's bitmap is not origin clean;
 at least some of its contents have or may have been loaded from a site other than the one from which the document itself was loaded.

Example
-------

```js
// Find the canvas element to capture
const canvasElt = document.querySelector("canvas");

// Get the stream
const stream = canvasElt.captureStream(25); // 25 FPS

// Do things to the stream
// E.g. Send it to another computer using an RTCPeerConnection
// pc is an RTCPeerConnection created elsewhere
stream.getTracks().forEach((track) => pc.addTrack(track, stream));
```

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

| Specification |
| --- |
| Media Capture from DOM Elements # dom-htmlcanvaselement-capturestream |

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

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

See also
--------

* `HTMLMediaElement.captureStream()`, which allows capturing a stream
 from a media element.
* `MediaStream`
* `Media Capture and Streams API`


HTMLCanvasElement: mozOpaque property - Web APIs

HTMLCanvasElement: mozOpaque 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.

**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

 The non-standard **`HTMLCanvasElement.mozOpaque`** property is
 a boolean value reflecting the `moz-opaque` HTML
 attribute of the `<canvas>` element. It lets the canvas know whether or
 not translucency will be a factor. If the canvas knows there's no translucency, painting
 performance can be optimized.

**Note:** This has been standardized as setting the `alpha` option to
 `false` when creating a drawing context with
 `HTMLCanvasElement.getContext()`. Use of `mozOpaque` should be
 avoided. Firefox will stop supporting it in the future.

Value
-----

A boolean value.

Examples
--------

Given this `<canvas>` element:

```html
<canvas id="canvas" width="300" height="300" moz-opaque></canvas>
```

 You can get or set the `mozOpaque` property. For example, you could
 conditionally set it to `true` if `mimeType === 'image/jpeg'`, or
 similar, to gain performance in your application when translucency is not needed.

```js
const canvas = document.getElementById("canvas");
console.log(canvas.mozOpaque); // true
// deactivate it
canvas.mozOpaque = false;
```

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

Not part of any standard.

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

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

See also
--------

* `HTMLCanvasElement`: Interface used to define the `HTMLCanvasElement.mozOpaque` property
* `moz-opaque`: HTML attribute of the `<canvas>` element
* Optimizing your JavaScript game for Firefox OS


HTMLCanvasElement: getContext() method - Web APIs

HTMLCanvasElement: getContext() method
======================================

 The
 **`HTMLCanvasElement.getContext()`** method returns a drawing
 context on the canvas, or `null` if the context identifier is not
 supported, or the canvas has already been set to a different context mode.

 Later calls to this method on the same canvas element, with the same
 `contextType` argument, will always return the same drawing context instance
 as was returned the first time the method was invoked. It is not possible to get a
 different drawing context object on a given canvas element.

Syntax
------

```js
getContext(contextType)
getContext(contextType, contextAttributes)
```

### Parameters

`contextType`

 A string containing the context identifier defining the drawing
 context associated to the canvas. Possible values are:

* `"2d"`, leading to the creation of a
 `CanvasRenderingContext2D` object representing a two-dimensional
 rendering context.
* `"webgl"` (or `"experimental-webgl"`) which will create a
 `WebGLRenderingContext` object representing a three-dimensional
 rendering context. This context is only available on browsers that implement WebGL version 1 (OpenGL ES 2.0).
* `"webgl2"` which will create a `WebGL2RenderingContext`
 object representing a three-dimensional rendering context. This context is only
 available on browsers that implement WebGL
 version 2 (OpenGL ES 3.0).
Experimental
* `"webgpu"`, which will create a
 `GPUCanvasContext` object representing a three-dimensional
 rendering context for WebGPU render pipelines. This context is only available on browsers that implement The WebGPU API.
* `"bitmaprenderer"` which will create an
 `ImageBitmapRenderingContext` which only provides functionality to
 replace the content of the canvas with a given `ImageBitmap`.

**Note:** The identifier `"experimental-webgl"` is used
 in new implementations of WebGL. These implementations have either not reached
 test suite conformance, or the graphics drivers on the platform are not yet
 stable. The Khronos Group certifies WebGL
 implementations under certain conformance rules.

`contextAttributes` Optional

 You can use several context attributes when creating your rendering context, for
 example:

```js
const gl = canvas.getContext("webgl", {
  antialias: false,
  depth: false,
});
```

2d context attributes:

`alpha`

 A boolean value that indicates if the canvas
 contains an alpha channel. If set to `false`, the browser now knows
 that the backdrop is always opaque, which can speed up drawing of transparent
 content and images.

`colorSpace` Optional

Specifies the color space of the rendering context. Possible values are:

* `"srgb"` selects the sRGB color space. This is the default value.
* `"display-p3"` selects the display-p3 color space.

`desynchronized`

 A boolean value that hints the user agent
 to reduce the latency by desynchronizing the canvas paint cycle from the event
 loop

`willReadFrequently`

 A boolean value that indicates whether
 or not a lot of read-back operations are planned. This will force the use of a
 software (instead of hardware accelerated) 2D canvas and can save memory when
 calling `getImageData()`
 frequently.

WebGL context attributes:

`alpha`

 A boolean value that indicates if the canvas
 contains an alpha buffer.

`depth`

 A boolean value that indicates that the drawing
 buffer is requested to have a depth buffer of at least 16 bits.

`stencil`

 A boolean value that indicates that the drawing
 buffer is requested to have a stencil buffer of at least 8 bits.

`desynchronized`

 A boolean value that hints the user agent
 to reduce the latency by desynchronizing the canvas paint cycle from the event
 loop

`antialias`

 A boolean value that indicates whether or not
 to perform anti-aliasing if possible.

`failIfMajorPerformanceCaveat`

 A boolean value that
 indicates if a context will be created if the system performance is low or if no
 hardware GPU is available.

`powerPreference`

 A hint to the user agent
 indicating what configuration of GPU is suitable for the WebGL context. Possible
 values are:

`"default"`

 Let the user agent decide which GPU configuration is
 most suitable. This is the default value.

`"high-performance"`

 Prioritizes rendering performance over
 power consumption.

`"low-power"`

 Prioritizes power saving over rendering
 performance.

`premultipliedAlpha`

 A boolean value that indicates that
 the page compositor will assume the drawing buffer contains colors with
 pre-multiplied alpha.

`preserveDrawingBuffer`

 If the value is true the
 buffers will not be cleared and will preserve their values until cleared or
 overwritten by the author.

`xrCompatible`

 A boolean value that hints to the user agent
 to use a compatible graphics adapter for an
 immersive XR device. Setting this
 synchronous flag at context creation is discouraged; rather call the asynchronous
 `WebGLRenderingContext.makeXRCompatible()` method the moment you
 intend to start an XR session.

**Note:** The WebGPU specification does not define any specific context attributes for `getContext()`. Instead, it provides configuration options via the `GPUCanvasContext.configure()` method.

### Return value

A rendering context which is either a

* `CanvasRenderingContext2D` for `"2d"`,
* `WebGLRenderingContext` for `"webgl"` and
 `"experimental-webgl"`,
* `WebGL2RenderingContext` for `"webgl2"`
* `GPUCanvasContext` for `"webgpu"` or
* `ImageBitmapRenderingContext` for `"bitmaprenderer"`.

 If the `contextType` doesn't match a possible drawing context, or differs
 from the first `contextType` requested, `null` is returned.

Examples
--------

Given this `<canvas>` element:

```html
<canvas id="canvas" width="300" height="300"></canvas>
```

You can get a `2d` context of the canvas with the following code:

```js
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
console.log(ctx); // CanvasRenderingContext2D { /\* … \*/ }
```

Now you have the 2D rendering context for a canvas and you can draw within it.

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

| Specification |
| --- |
| HTML Standard # dom-canvas-getcontext-dev |

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

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

See also
--------

* `HTMLCanvasElement`: Interface used to define the `HTMLCanvasElement.getContext()` method
* `OffscreenCanvas.getContext()`
* `CanvasRenderingContext2D.getContextAttributes()`, `WebGLRenderingContext.getContextAttributes()`
* `CanvasRenderingContext2D`, `ImageBitmapRenderingContext`,
 `WebGLRenderingContext`, `WebGL2RenderingContext`, `GPUCanvasContext`: Available rendering contexts
* DCI-P3 color space on Wikipedia
* sRGB color space on Wikipedia


HTMLCanvasElement: transferControlToOffscreen() method - Web APIs

HTMLCanvasElement: transferControlToOffscreen() method
======================================================

Baseline 2023
-------------

Newly availableSince March 2023, this feature works across the latest devices and browser versions. This feature might not work in older devices or browsers.

* Learn more
* See full compatibility
* Report feedback
The **`HTMLCanvasElement.transferControlToOffscreen()`** method transfers control to an `OffscreenCanvas` object, either on the main thread or on a worker.

Syntax
------

```js
transferControlToOffscreen()
```

### Parameters

None.

### Return value

An `OffscreenCanvas` object.

Examples
--------

The following example shows how to transfer control to an `OffscreenCanvas` object on the main thread.

```js
const htmlCanvas = document.createElement("canvas");
const offscreen = htmlCanvas.transferControlToOffscreen();
const gl = offscreen.getContext("webgl");

// Some drawing using the gl context…
```

The following example shows how to transfer control to an `OffscreenCanvas` object on a worker.

```js
const offscreen = document.querySelector("canvas").transferControlToOffscreen();
const worker = new Worker("myworkerurl.js");
worker.postMessage({ canvas: offscreen }, [offscreen]);
```

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

| Specification |
| --- |
| HTML Standard # dom-canvas-transfercontroltooffscreen-dev |

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

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

See also
--------

* The interface defining this method, `HTMLCanvasElement`
* `OffscreenCanvas`


HTMLCanvasElement: contextlost event - Web APIs

HTMLCanvasElement: contextlost event
====================================

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
**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

 The **`contextlost`** event of the Canvas API is fired if the user agent detects that the backing storage associated with a `CanvasRenderingContext2D` context is lost.
 Contexts can be lost for several reasons like driver crashes or the application runs out of memory, etc.

 By default the user agent will attempt to restore the context and then fire the `contextrestored` event.
 User code can prevent the context from being restored by calling `Event.preventDefault()` during event handling.

Syntax
------

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

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

oncontextlost = (event) => {};
```

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

A generic `Event`.

Example
-------

The code fragment below detects the `contextlost` event.

```js
const canvas = document.getElementById("canvas");

canvas.addEventListener("contextlost", (event) => {
  console.log(event);
});
```

To prevent the context from being restored the code might instead look like this:

```js
const canvas = document.getElementById("canvas");

canvas.addEventListener("contextlost", (event) => {
  event.preventDefault();
});
```

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

| Specification |
| --- |
| HTML Standard # event-contextlost |

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

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

See also
--------

* `HTMLCanvasElement: contextrestored` event
* `CanvasRenderingContext2D.isContextLost()`


HTMLCanvasElement: webglcontextrestored event - Web APIs

HTMLCanvasElement: webglcontextrestored event
=============================================

The **`webglcontextrestored`** event of the WebGL API is fired if the user agent restores the drawing buffer for a `WebGLRenderingContext` object.

Once the context is restored, WebGL resources such as textures and buffers that were created before the context was lost are no longer valid. You need to reinitialize the state of your WebGL application and recreate resources.

This event does not bubble.

Syntax
------

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

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

onwebglcontextrestored = (event) => {};
```

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

A `WebGLContextEvent`. Inherits from `Event`.

Event

WebGLContextEventEvent properties
----------------

*This interface inherits properties from its parent interface, `Event`.*

`WebGLContextEvent.statusMessage`

A read-only property containing additional information about the event.

Example
-------

With the help of the `WEBGL_lose_context` extension, you can simulate the `webglcontextrestored` event:

```js
const canvas = document.getElementById("canvas");
const gl = canvas.getContext("webgl");

canvas.addEventListener(
  "webglcontextrestored",
  (e) => {
    console.log(e);
  },
  false,
);

gl.getExtension("WEBGL\_lose\_context").restoreContext();

// "webglcontextrestored" event is logged.
```

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

| Specification |
| --- |
| WebGL Specification # 5.15.3 |

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

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

See also
--------

* `WebGLContextEvent`
* `WebGLRenderingContext.isContextLost()`
* `WEBGL_lose_context`, `WEBGL_lose_context.loseContext()`, `WEBGL_lose_context.restoreContext()`


HTMLCanvasElement: toDataURL() method - Web APIs

HTMLCanvasElement: toDataURL() method
=====================================

The **`HTMLCanvasElement.toDataURL()`** method returns a data URL containing a representation of the image in the format specified by the `type` parameter.

 The desired file format and image quality may be specified.
 If the file format is not specified, or if the given format is not supported, then the data will be exported as `image/png`.
 In other words, if the returned value starts with `data:image/png` for any other requested `type`, then that format is not supported.

Browsers are required to support `image/png`; many will support additional formats including `image/jpeg` and `image/webp`.

The created image data will have a resolution of 96dpi for file formats that support encoding resolution metadata.

Syntax
------

```js
toDataURL()
toDataURL(type)
toDataURL(type, encoderOptions)
```

### Parameters

`type` Optional

 A string indicating the image format.
 The default type is `image/png`; this image format will be also used if the specified type is not supported.

`encoderOptions` Optional

 A `Number` between `0` and `1` indicating the image quality to be used when creating images using file formats that support lossy compression (such as `image/jpeg` or `image/webp`).
 A user agent will use its default quality value if this option is not specified, or if the number is outside the allowed range.

### Return value

A string containing the requested data URL.

If the height or width of the canvas is `0` or larger than the maximum canvas size, the string `"data:,"` is returned.

### Exceptions

`SecurityError`

 The canvas's bitmap is not origin clean;
 at least some of its contents have or may have been loaded from a site other than the one from which the document itself was loaded.

Examples
--------

Given this `<canvas>` element:

```html
<canvas id="canvas" width="5" height="5"></canvas>
```

You can get a data-URL of the canvas with the following lines:

```js
const canvas = document.getElementById("canvas");
const dataURL = canvas.toDataURL();
console.log(dataURL);
// "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNby
// blAAAADElEQVQImWNgoBMAAABpAAFEI8ARAAAAAElFTkSuQmCC"
```

### Setting image quality with jpegs

```js
const fullQuality = canvas.toDataURL("image/jpeg", 1.0);
// data:image/jpeg;base64,/9j/4AAQSkZJRgABAQ…9oADAMBAAIRAxEAPwD/AD/6AP/Z"
const mediumQuality = canvas.toDataURL("image/jpeg", 0.5);
const lowQuality = canvas.toDataURL("image/jpeg", 0.1);
```

### Example: Dynamically change images

You can use this technique in coordination with mouse events in order to dynamically change images (gray-scale vs. color in this example):

#### HTML

```html
<img class="grayscale" src="myPicture.png" alt="Description of my picture" />
```

#### JavaScript

```js
window.addEventListener("load", removeColors);

function showColorImg() {
  this.style.display = "none";
  this.nextSibling.style.display = "inline";
}

function showGrayImg() {
  this.previousSibling.style.display = "inline";
  this.style.display = "none";
}

function removeColors() {
  const images = document.getElementsByClassName("grayscale");
  const canvas = document.createElement("canvas");
  const ctx = canvas.getContext("2d");

  for (const colorImg of images) {
    const width = colorImg.offsetWidth;
    const height = colorImg.offsetHeight;
    canvas.width = width;
    canvas.height = height;
    ctx.drawImage(colorImg, 0, 0);
    const imgData = ctx.getImageData(0, 0, width, height);
    const pix = imgData.data;
    const pixLen = pix.length;
    for (let pixel = 0; pixel < pixLen; pixel += 4) {
      pix[pixel + 2] =
        pix[pixel + 1] =
        pix[pixel] =
          (pix[pixel] + pix[pixel + 1] + pix[pixel + 2]) / 3;
    }
    ctx.putImageData(imgData, 0, 0);
    const grayImg = new Image();
    grayImg.src = canvas.toDataURL();
    grayImg.onmouseover = showColorImg;
    colorImg.onmouseout = showGrayImg;
    ctx.clearRect(0, 0, width, height);
    colorImg.style.display = "none";
    colorImg.parentNode.insertBefore(grayImg, colorImg);
  }
}
```

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

| Specification |
| --- |
| HTML Standard # dom-canvas-todataurl-dev |

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

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

See also
--------

* Data URLs in the HTTP reference.


HTMLCanvasElement: webglcontextlost event - Web APIs

HTMLCanvasElement: webglcontextlost event
=========================================

The **`webglcontextlost`** event of the WebGL API is fired if the user agent detects that the drawing buffer associated with a `WebGLRenderingContext` object has been lost.

This event does not bubble.

Syntax
------

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

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

onwebglcontextlost = (event) => {};
```

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

A `WebGLContextEvent`. Inherits from `Event`.

Event

WebGLContextEventEvent properties
----------------

*This interface inherits properties from its parent interface, `Event`.*

`WebGLContextEvent.statusMessage`

A read-only property containing additional information about the event.

Example
-------

With the help of the `WEBGL_lose_context` extension, you can simulate the `webglcontextlost` event:

```js
const canvas = document.getElementById("canvas");
const gl = canvas.getContext("webgl");

canvas.addEventListener("webglcontextlost", (event) => {
  console.log(event);
});

gl.getExtension("WEBGL\_lose\_context").loseContext();

// "webglcontextlost" event is logged.
```

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

| Specification |
| --- |
| WebGL Specification # 5.15.2 |

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

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

See also
--------

* `WebGLContextEvent`
* `WebGLRenderingContext.isContextLost()`
* `WEBGL_lose_context`, `WEBGL_lose_context.loseContext()`, `WEBGL_lose_context.restoreContext()`


HTMLCanvasElement: width property - Web APIs

HTMLCanvasElement: width property
=================================

 The **`HTMLCanvasElement.width`** property is a
 positive `integer` reflecting the `width` HTML
 attribute of the `<canvas>` element interpreted in CSS pixels. When the
 attribute is not specified, or if it is set to an invalid value, like a negative, the
 default value of `300` is used.

 This is one of the two properties, the other being
 `HTMLCanvasElement.height`, that controls the size of the canvas.

Value
-----

A number.

Examples
--------

Given this `<canvas>` element:

```html
<canvas id="canvas" width="300" height="300"></canvas>
```

You can get the width of the canvas with the following code:

```js
const canvas = document.getElementById("canvas");
console.log(canvas.width); // 300
```

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

| Specification |
| --- |
| HTML Standard # dom-canvas-height |

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

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

See also
--------

* `HTMLCanvasElement`: Interface used to define the `HTMLCanvasElement.width` property
* `HTMLCanvasElement.height`: Other property used to control the size of the canvas
* `HTMLImageElement.width`
* `HTMLObjectElement.width`
* `HTMLVideoElement.width`


HTMLCanvasElement: toBlob() method - Web APIs

HTMLCanvasElement: toBlob() method
==================================

 The **`HTMLCanvasElement.toBlob()`** method creates a `Blob` object representing the image contained in the canvas.
 This file may be cached on the disk or stored in memory at the discretion of the user agent.

 The desired file format and image quality may be specified.
 If the file format is not specified, or if the given format is not supported, then the data will be exported as `image/png`.
 Browsers are required to support `image/png`; many will support additional formats including `image/jpeg` and `image/webp`.

The created image will have a resolution of 96dpi for file formats that support encoding resolution metadata.

Syntax
------

```js
toBlob(callback)
toBlob(callback, type)
toBlob(callback, type, quality)
```

### Parameters

`callback`

 A callback function with the resulting `Blob` object as a single argument.
 `null` may be passed if the image cannot be created for any reason.

`type` Optional

 A string indicating the image format.
 The default type is `image/png`; that type is also used if the given type isn't supported.

`quality` Optional

 A `Number` between `0` and `1` indicating the image quality to be used when creating images using file formats that support lossy compression (such as `image/jpeg` or `image/webp`).
 A user agent will use its default quality value if this option is not specified, or if the number is outside the allowed range.

### Return value

None (`undefined`).

### Exceptions

`SecurityError`

The canvas's bitmap is not origin-clean; at least some of its contents have or may have been loaded from a site other than the one from which the document itself was loaded.

Examples
--------

### Getting a file representing the canvas

 Once you have drawn content into a canvas, you can convert it into a file of any supported image format.
 The code snippet below, for example, takes the image in the `<canvas>` element whose ID is "canvas", obtains a copy of it as a PNG image, then appends a new `<img>` element to the document, whose source image is the one created using the canvas.

```js
const canvas = document.getElementById("canvas");

canvas.toBlob((blob) => {
  const newImg = document.createElement("img");
  const url = URL.createObjectURL(blob);

  newImg.onload = () => {
    // no longer need to read the blob so it's revoked
    URL.revokeObjectURL(url);
  };

  newImg.src = url;
  document.body.appendChild(newImg);
});
```

 Note that here we're creating a PNG image; if you add a second parameter to the `toBlob()` call, you can specify another image type supported by the user agent.
 For example, to get the image in JPEG format:

```js
canvas.toBlob(
  (blob) => {
    /\* … \*/
  },
  "image/jpeg",
  0.95,
); // JPEG at 95% quality
```

### Convert a canvas to an ico (Mozilla only)

 This uses `-moz-parse` to convert the canvas to ico, and hence only works on Firefox.
 Windows XP doesn't support converting from PNG to ico, so it uses bmp instead.
 A download link is created by setting the download attribute. The value of the download attribute is the name it will use as the file name.

```js
const canvas = document.getElementById("canvas");
const d = canvas.width;
const ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.moveTo(d / 2, 0);
ctx.lineTo(d, d);
ctx.lineTo(0, d);
ctx.closePath();
ctx.fillStyle = "yellow";
ctx.fill();

function blobCallback(iconName) {
  return (b) => {
    const a = document.createElement("a");
    a.textContent = "Download";
    document.body.appendChild(a);
    a.style.display = "block";
    a.download = `${iconName}.ico`;
    a.href = window.URL.createObjectURL(b);
  };
}
canvas.toBlob(
  blobCallback("passThisString"),
  "image/vnd.microsoft.icon",
  "-moz-parse-options:format=bmp;bpp=32",
);
```

### Save toBlob to disk with OS.File (Chrome/add-on context only)

**Note:** This technique saves it to the desktop and is only useful in Firefox chrome context or add-on code, as OS APIs are not present on websites.

```js
const canvas = document.getElementById("canvas");
const d = canvas.width;
ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.moveTo(d / 2, 0);
ctx.lineTo(d, d);
ctx.lineTo(0, d);
ctx.closePath();
ctx.fillStyle = "yellow";
ctx.fill();

function blobCallback(iconName) {
  return (b) => {
    const r = new FileReader();
    r.onloadend = () => {
      // r.result contains the ArrayBuffer.
      Cu.import("resource://gre/modules/osfile.jsm");
      const writePath = OS.Path.join(
        OS.Constants.Path.desktopDir,
        `${iconName}.ico`,
      );
      const promise = OS.File.writeAtomic(writePath, new Uint8Array(r.result), {
        tmpPath: `${writePath}.tmp`,
      });
      promise.then(
        () => {
          console.log("successfully wrote file");
        },
        () => {
          console.log("failure writing file");
        },
      );
    };
    r.readAsArrayBuffer(b);
  };
}

canvas.toBlob(
  blobCallback("passThisString"),
  "image/vnd.microsoft.icon",
  "-moz-parse-options:format=bmp;bpp=32",
);
```

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

| Specification |
| --- |
| HTML Standard # dom-canvas-toblob-dev |

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

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

See also
--------

* `Blob`


XRCompositionLayer: destroy() method - Web APIs

XRCompositionLayer: destroy() method
====================================

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

The **`destroy()`** method of the `XRCompositionLayer` interface deletes the references to the underlying graphics library for the layer. It also sets the color textures and depth stencil texture arrays to an empty array.

Syntax
------

```js
destroy()
```

### Parameters

None.

### Return value

None (`undefined`).

Examples
--------

### Deleting a layer

Call `destroy()` to delete a layer.

```js
myLayer.destroy();
```

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

| Specification |
| --- |
| WebXR Layers API Level 1 # dom-xrcompositionlayer-destroy |

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

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


XRCompositionLayer: blendTextureSourceAlpha property - Web APIs

XRCompositionLayer: blendTextureSourceAlpha property
====================================================

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

The **`blendTextureSourceAlpha`** property of the `XRCompositionLayer` interface is a boolean enabling the layer's texture alpha channel.

Value
-----

A boolean. `true` enables the alpha channel, `false` disables it.

Examples
--------

### Setting a layer's texture alpha channel

The following code snippet toggles a layer to opaque and back.

```js
myLayer.blendTextureSourceAlpha = !myLayer.blendTextureSourceAlpha;
```

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

| Specification |
| --- |
| WebXR Layers API Level 1 # dom-xrcompositionlayer-blendtexturesourcealpha |

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

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

See also
--------

* Alpha channel


XRCompositionLayer: layout property - Web APIs

XRCompositionLayer: layout property
===================================

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

The read-only **`layout`** property of the `XRCompositionLayer` interface is the layout type of the layer.

To specify the layout type of a layer, use one of the layer creation methods and their `layout` option:

* `XRWebGLBinding.createQuadLayer()`
* `XRWebGLBinding.createCylinderLayer()`
* `XRWebGLBinding.createEquirectLayer()`
* `XRWebGLBinding.createCubeLayer()`
Value
-----

A string. Possible values:

`default`

The layer accommodates all views of the session. It is recommended to use the `texture-array` texture type for `default` layouts.

`mono`

A single `XRSubImage` is allocated and presented to both eyes.

`stereo`

The user agent decides how it allocates the `XRSubImage` (one or two) and the layout (top/bottom or left/right). It is recommended to use the `texture-array` texture type for `stereo` layouts.

`stereo-left-right`

A single `XRSubImage` is allocated. Left eye gets the left area of the texture, right eye the right. This layout is designed to minimize draw calls for content that is already in stereo (for example stereo videos or images).

`stereo-top-bottom`

A single `XRSubImage` is allocated. Left eye gets the top area of the texture, right eye the bottom. This layout is designed to minimize draw calls for content that is already in stereo (for example stereo videos or images).

Examples
--------

### Setting and getting a layer's layout

To specify a layer's layout, use a layer creation method (like `XRWebGLBinding.createQuadLayer()`) and its `layout` option. To retrieve the type of layer layout, use the `layout` property:

```js
const layer = xrGlBinding.createQuadLayer({
  pixelWidth: 1024,
  pixelHeight: 768,
  layout: "stereo",
});

layer.layout; // "stereo"
```

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

| Specification |
| --- |
| WebXR Layers API Level 1 # dom-xrcompositionlayer-layout |

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

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

See also
--------

* `XRSubImage`
* `XRWebGLBinding.createQuadLayer()`
* `XRWebGLBinding.createCylinderLayer()`
* `XRWebGLBinding.createEquirectLayer()`
* `XRWebGLBinding.createCubeLayer()`


XRCompositionLayer: needsRedraw property - Web APIs

XRCompositionLayer: needsRedraw property
========================================

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

The read-only **`needsRedraw`** property of the `XRCompositionLayer` interface is a boolean signaling that the layer should be re-rendered in the next frame.

The need for redrawing can occur when the underlying resources of a layer are lost due to textures that might have been freed by the compositor under the hood. This might happen when the device falls asleep or when the browser switches context (to an operating system dialog or similar) and then comes back.

Redrawing is not a problem for layers which are updated with every frame. However, for layers updated infrequently, or for static layers (where you can only draw once after creation or after a `redraw` event), the layer's content might be lost and need to be redrawn. If the layer's resources are lost, the `needsRedraw` property will be `true` and a `redraw` event is fired on the layer.

Value
-----

A boolean. `true` indicates a rerendering is needed in the next frame, `false` indicates no re-rendering is needed.

Examples
--------

### Redrawing layers

Use the `needsRedraw` property to check if a layer needs to be redrawn and then redraw it.

```js
function onXRFrame(time, frame) {
  // …

  if (quadLayer.needsRedraw) {
    // redraw the layer
  }
}
```

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

| Specification |
| --- |
| WebXR Layers API Level 1 # dom-xrcompositionlayer-needsredraw |

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

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

See also
--------

* `XREquirectLayer`: `redraw` event
* `XRCubeLayer`: `redraw` event
* `XRCylinderLayer`: `redraw` event
* `XRQuadLayer`: `redraw` event


XRCompositionLayer: mipLevels property - Web APIs

XRCompositionLayer: mipLevels property
======================================

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

The read-only **`mipLevels`** property of the `XRCompositionLayer` interface is a layer's number of mip levels in the color and texture data. See also Mipmap on Wikipedia.

The desired number of mip levels can be specified when creating layers. However, if the user agent can't create the requested number, it can create less. Use `mipLevels` to determine the actual number of mip levels for a layer.

The `viewPixelWidth` and `viewPixelHeight` need to be powers of two as they get successively halved at each mip level.

Value
-----

A number equal or smaller to the requested mip levels when a layer has been created.

Examples
--------

### Getting a layer's mip levels

The `mipLevels` property indicates the actual number of mip levels that have been created. In this example, the desired number of 5 mip levels that had been requested for an `XRQuadLayer` could be full-filled.

```js
let xrGLBinding = new XRWebGLBinding(session, gl);
let quadLayer = xrGLBinding.createQuadLayer({
  space: refSpace,
  viewPixelHeight: 512,
  viewPixelWidth: 512,
  width: 1.0,
  height: 1.0,
  mipLevels: 5,
  transform: new XRRigidTransform({
    /\* … \*/
  }),
});

quadLayer.mipLevels; // 5
```

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

| Specification |
| --- |
| WebXR Layers API Level 1 # dom-xrcompositionlayer-miplevels |

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

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

See also
--------

* Mipmap on Wikipedia