CanvasRenderingContext2D: getImageData() method - Web APIs

CanvasRenderingContext2D: getImageData() method
===============================================

 The `CanvasRenderingContext2D` method
 **`getImageData()`** of the Canvas 2D API returns an
 `ImageData` object representing the underlying pixel data for a specified
 portion of the canvas.

 This method is not affected by the canvas's transformation matrix. If the specified
 rectangle extends outside the bounds of the canvas, the pixels outside the canvas are
 transparent black in the returned `ImageData` object.

**Note:** Image data can be painted onto a canvas using the
 `putImageData()` method.

 You can find more information about `getImageData()` and general
 manipulation of canvas contents in Pixel manipulation with canvas.

Syntax
------

```js
getImageData(sx, sy, sw, sh)
getImageData(sx, sy, sw, sh, settings)
```

### Parameters

`sx`

 The x-axis coordinate of the top-left corner of the rectangle from which the
 `ImageData` will be extracted.

`sy`

 The y-axis coordinate of the top-left corner of the rectangle from which the
 `ImageData` will be extracted.

`sw`

 The width of the rectangle from which the `ImageData` will be extracted.
 Positive values are to the right, and negative to the left.

`sh`

 The height of the rectangle from which the `ImageData` will be extracted.
 Positive values are down, and negative are up.

`settings` Optional

An object with the following properties:

* `colorSpace`: Specifies the color space of the image data. Can be set to `"srgb"` for the sRGB color space or `"display-p3"` for the display-p3 color space.

### Return value

 An `ImageData` object containing the image data for the rectangle of the
 canvas specified. The coordinates of the rectangle's top-left corner are
 `(sx, sy)`, while the coordinates of the bottom corner are
 `(sx + sw - 1, sy + sh - 1)`.

### Exceptions

`IndexSizeError` `DOMException`

Thrown if either `sw` or `sh` are zero.

`SecurityError` `DOMException`

 The canvas contains or may contain pixels which were loaded from an origin other
 than the one from which the document itself was loaded.
 To avoid a `SecurityError` `DOMException` being thrown in this situation,
 configure CORS to allow the source image to be used in this way.
 See Allowing cross-origin use of images and canvas.

Examples
--------

### Getting image data from a canvas

 This example draws an image, and then uses `getImageData()` to grab a
 portion of the canvas.

We use `getImageData()` to extract a slice of the image, starting at `(10, 20)`, with a width of `80` and a height of `230`. We then draw this slice three times, positioning the slices progressively below and to the right of the last slice.

#### HTML

```html
<canvas id="canvas" width="700" height="400"></canvas>
```

#### JavaScript

```js
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");

const image = new Image();
image.src = "plumeria.jpg";
image.addEventListener("load", () => {
  ctx.drawImage(image, 0, 0, 233, 320);

  const imageData = ctx.getImageData(10, 20, 80, 230);
  ctx.putImageData(imageData, 260, 0);
  ctx.putImageData(imageData, 380, 50);
  ctx.putImageData(imageData, 500, 100);
});
```

#### Result

### Color space conversion

The optional `colorSpace` setting allows you to get image data in the desired format.

```js
const context = canvas.getContext("2d", { colorSpace: "display-p3" });
context.fillStyle = "color(display-p3 0.5 0 0)";
context.fillRect(0, 0, 10, 10);

// Get ImageData converted to sRGB
const imageData = context.getImageData(0, 0, 1, 1, { colorSpace: "srgb" });
console.log(imageData.colorSpace); // "srgb"
```

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

| Specification |
| --- |
| HTML Standard # dom-context-2d-getimagedata-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: `CanvasRenderingContext2D`
* `ImageData` object
* `CanvasRenderingContext2D.putImageData()`
* Pixel manipulation with canvas


CanvasRenderingContext2D: createPattern() method - Web APIs

CanvasRenderingContext2D: createPattern() method
================================================

 The **`CanvasRenderingContext2D.createPattern()`** method of the Canvas 2D API creates a pattern using the specified image and repetition.
 This method returns a `CanvasPattern`.

 This method doesn't draw anything to the canvas directly.
 The pattern it creates must be assigned to the `CanvasRenderingContext2D.fillStyle` or `CanvasRenderingContext2D.strokeStyle` properties, after which it is applied to any subsequent drawing.

Syntax
------

```js
createPattern(image, repetition)
```

### Parameters

`image`

 An image to be used as the pattern's image.
 It can be any of the following:

* `HTMLImageElement` (`<img>`)
* `SVGImageElement` (`<image>`)
* `HTMLVideoElement` (`<video>`, by using the capture of the video)
* `HTMLCanvasElement` (`<canvas>`)
* `ImageBitmap`
* `OffscreenCanvas`
* `VideoFrame`

`repetition`

 A string indicating how to repeat the pattern's image.
 Possible values are:

* `"repeat"` (both directions)
* `"repeat-x"` (horizontal only)
* `"repeat-y"` (vertical only)
* `"no-repeat"` (neither direction)

If `repetition` is specified as an empty string (`""`) or `null` (but not `undefined`), a value of `"repeat"` will be used.

### Return value

`CanvasPattern`

An opaque object describing a pattern.

If the `image` is not fully loaded (`HTMLImageElement.complete` is `false`), then `null` is returned.

Examples
--------

### Creating a pattern from an image

 This example uses the `createPattern()` method to create a `CanvasPattern` with a repeating source image.
 Once created, the pattern is assigned to the canvas context's fill style and applied to a rectangle.

The original image looks like this:

![A flowery pattern](/en-US/docs/Web/API/CanvasRenderingContext2D/createPattern/canvas_createpattern.png)

#### HTML

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

#### JavaScript

```js
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");

const img = new Image();
img.src = "canvas\_createpattern.png";
// Only use the image after it's loaded
img.onload = () => {
  const pattern = ctx.createPattern(img, "repeat");
  ctx.fillStyle = pattern;
  ctx.fillRect(0, 0, 300, 300);
};
```

### Creating a pattern from a canvas

 In this example we create a pattern from the contents of an offscreen canvas.
 We then apply it to the fill style of our primary canvas, and fill that canvas with the pattern.

#### JavaScript

```js
// Create a pattern, offscreen
const patternCanvas = document.createElement("canvas");
const patternContext = patternCanvas.getContext("2d");

// Give the pattern a width and height of 50
patternCanvas.width = 50;
patternCanvas.height = 50;

// Give the pattern a background color and draw an arc
patternContext.fillStyle = "#fec";
patternContext.fillRect(0, 0, patternCanvas.width, patternCanvas.height);
patternContext.arc(0, 0, 50, 0, 0.5 \* Math.PI);
patternContext.stroke();

// Create our primary canvas and fill it with the pattern
const canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d");
const pattern = ctx.createPattern(patternCanvas, "repeat");
ctx.fillStyle = pattern;
ctx.fillRect(0, 0, canvas.width, canvas.height);

// Add our primary canvas to the webpage
document.body.appendChild(canvas);
```

#### Result

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

| Specification |
| --- |
| HTML Standard # dom-context-2d-createpattern-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: `CanvasRenderingContext2D`
* `CanvasPattern`


CanvasRenderingContext2D: rotate() method - Web APIs

CanvasRenderingContext2D: rotate() method
=========================================

 The
 **`CanvasRenderingContext2D.rotate()`**
 method of the Canvas 2D API adds a rotation to the transformation matrix.

Syntax
------

```js
rotate(angle)
```

![Rectangular coordinate system with the rotation of the abscissa axis by the alpha angle](/en-US/docs/Web/API/CanvasRenderingContext2D/rotate/canvas_grid_rotate.png)

### Parameters

`angle`

 The rotation angle, clockwise in radians. You can use
 `degree * Math.PI / 180` to calculate a radian from a degree.

 The rotation center point is always the canvas origin. To change the center point, you
 will need to move the canvas by using the
 `translate()` method.

### Return value

None (`undefined`).

Examples
--------

### Rotating a shape

 This example rotates a rectangle by 45°. Note that the center of rotation is the
 top-left corner of the canvas, and not a location relative to any shape.

#### HTML

```html
<canvas id="canvas"></canvas>
```

#### JavaScript

```js
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");

// Point of transform origin
ctx.arc(0, 0, 5, 0, 2 \* Math.PI);
ctx.fillStyle = "blue";
ctx.fill();

// Non-rotated rectangle
ctx.fillStyle = "gray";
ctx.fillRect(100, 0, 80, 20);

// Rotated rectangle
ctx.rotate((45 \* Math.PI) / 180);
ctx.fillStyle = "red";
ctx.fillRect(100, 0, 80, 20);

// Reset transformation matrix to the identity matrix
ctx.setTransform(1, 0, 0, 1, 0, 0);
```

#### Result

The center of rotation is blue. The non-rotated rectangle is gray, and the rotated rectangle is red.

### Rotating a shape around its center

 This example rotates a shape around its center point. To do this, the following steps
 are applied to the matrix:

1. First, `translate()` moves the
 matrix's origin to the shape's center.
2. `rotate()` rotates the matrix by the desired amount.
3. Finally, `translate()` moves the matrix's origin back to its starting
 point. This is done by applying the values of the shape's center coordinates in a
 negative direction.

#### HTML

```html
<canvas id="canvas"></canvas>
```

#### JavaScript

 The shape is a rectangle with its corner at (80, 60), a width of 140, a height of 30.
 Its horizontal center is at (80 + 140 / 2), or 150. Its vertical center is at (60 + 30 /
 2), or 75. Thus, the center point is at (150, 75).

```js
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");

// Non-rotated rectangle
ctx.fillStyle = "gray";
ctx.fillRect(80, 60, 140, 30);

// Matrix transformation
ctx.translate(150, 75);
ctx.rotate(Math.PI / 2);
ctx.translate(-150, -75);

// Rotated rectangle
ctx.fillStyle = "red";
ctx.fillRect(80, 60, 140, 30);
```

#### Result

The non-rotated rectangle is gray, and the rotated rectangle is red.

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

| Specification |
| --- |
| HTML Standard # dom-context-2d-rotate-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: `CanvasRenderingContext2D`


CanvasRenderingContext2D: direction property - Web APIs

CanvasRenderingContext2D: direction property
============================================

 The
 **`CanvasRenderingContext2D.direction`**
 property of the Canvas 2D API specifies the current text direction used to draw text.

Value
-----

Possible values:

`"ltr"`

The text direction is left-to-right.

`"rtl"`

The text direction is right-to-left.

`"inherit"`

 The text direction is inherited from the `<canvas>` element or the
 `Document` as appropriate. Default value.

The default value is `"inherit"`.

Examples
--------

### Changing text direction

 This example draws two pieces of text. The first one is left-to-right, and the second
 is right-to-left. Note that "Hi!" in `ltr` becomes "!Hi" in `rtl`.

#### HTML

```html
<canvas id="canvas"></canvas>
```

#### JavaScript

```js
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");

ctx.font = "48px serif";
ctx.fillText("Hi!", 150, 50);
ctx.direction = "rtl";
ctx.fillText("Hi!", 150, 130);
```

#### Result

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

| Specification |
| --- |
| HTML Standard # dom-context-2d-direction-dev |

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

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

See also
--------

* The interface defining this property: `CanvasRenderingContext2D`


CanvasRenderingContext2D: createRadialGradient() method - Web APIs

CanvasRenderingContext2D: createRadialGradient() method
=======================================================

 The
 **`CanvasRenderingContext2D.createRadialGradient()`**
 method of the Canvas 2D API creates a radial gradient using the size and coordinates of
 two circles.

 This method returns a `CanvasGradient`. To be applied to a shape, the
 gradient must first be assigned to the `fillStyle` or `strokeStyle`
 properties.

**Note:** Gradient coordinates are global, i.e., relative to the current
 coordinate space. When applied to a shape, the coordinates are NOT relative to the
 shape's coordinates.

Syntax
------

```js
createRadialGradient(x0, y0, r0, x1, y1, r1)
```

 The `createRadialGradient()` method is specified by six parameters, three
 defining the gradient's start circle, and three defining the end circle.

### Parameters

`x0`

The x-axis coordinate of the start circle.

`y0`

The y-axis coordinate of the start circle.

`r0`

The radius of the start circle. Must be non-negative and finite.

`x1`

The x-axis coordinate of the end circle.

`y1`

The y-axis coordinate of the end circle.

`r1`

The radius of the end circle. Must be non-negative and finite.

### Return value

A radial `CanvasGradient` initialized with the two specified circles.

### Exceptions

`NotSupportedError` `DOMException`

Thrown when non-finite values are passed in parameter.

`IndexSizeError` `DOMException`

Thrown when a negative radius is passed in parameter.

Examples
--------

### Filling a rectangle with a radial gradient

 This example initializes a radial gradient using the
 `createRadialGradient()` method. Three color stops between the gradient's two
 circles are then created. Finally, the gradient is assigned to the canvas context, and
 is rendered to a filled rectangle.

#### HTML

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

#### JavaScript

```js
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");

// Create a radial gradient
// The inner circle is at x=110, y=90, with radius=30
// The outer circle is at x=100, y=100, with radius=70
const gradient = ctx.createRadialGradient(110, 90, 30, 100, 100, 70);

// Add three color stops
gradient.addColorStop(0, "pink");
gradient.addColorStop(0.9, "white");
gradient.addColorStop(1, "green");

// Set the fill style and draw a rectangle
ctx.fillStyle = gradient;
ctx.fillRect(20, 20, 160, 160);
```

#### Result

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

| Specification |
| --- |
| HTML Standard # dom-context-2d-createradialgradient-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: `CanvasRenderingContext2D`
* `CanvasRenderingContext2D.createLinearGradient()`
* `CanvasRenderingContext2D.createConicGradient()`


CanvasRenderingContext2D: isPointInStroke() method - Web APIs

CanvasRenderingContext2D: isPointInStroke() method
==================================================

 The
 **`CanvasRenderingContext2D.isPointInStroke()`**
 method of the Canvas 2D API reports whether or not the specified point is inside the
 area contained by the stroking of a path.

Syntax
------

```js
isPointInStroke(x, y)
isPointInStroke(path, x, y)
```

### Parameters

`x`

The x-axis coordinate of the point to check.

`y`

The y-axis coordinate of the point to check.

`path`

 A `Path2D` path to check against. If unspecified, the current path is
 used.

### Return value

A boolean value

 A Boolean, which is `true` if the point is inside the area contained by
 the stroking of a path, otherwise `false`.

Examples
--------

### Checking a point in the current path

 This example uses the `isPointInStroke()` method to check if a point is
 within the area of the current path's stroke.

#### HTML

```html
<canvas id="canvas"></canvas>
<p>In stroke: <code id="result">false</code></p>
```

#### JavaScript

```js
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
const result = document.getElementById("result");

ctx.rect(10, 10, 100, 100);
ctx.stroke();
result.innerText = ctx.isPointInStroke(50, 10);
```

#### Result

### Checking a point in the specified path

 Whenever you move the mouse, this example checks whether the cursor is in the stroke of
 an elliptical `Path2D` path. If yes, the ellipse's stroke becomes green,
 otherwise it is red.

#### HTML

```html
<canvas id="canvas"></canvas>
```

#### JavaScript

```js
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");

// Create ellipse
const ellipse = new Path2D();
ellipse.ellipse(150, 75, 40, 60, Math.PI \* 0.25, 0, 2 \* Math.PI);
ctx.lineWidth = 25;
ctx.strokeStyle = "red";
ctx.fill(ellipse);
ctx.stroke(ellipse);

// Listen for mouse moves
canvas.addEventListener("mousemove", (event) => {
  // Check whether point is inside ellipse's stroke
  const isPointInStroke = ctx.isPointInStroke(
    ellipse,
    event.offsetX,
    event.offsetY,
  );
  ctx.strokeStyle = isPointInStroke ? "green" : "red";

  // Draw ellipse
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.fill(ellipse);
  ctx.stroke(ellipse);
});
```

#### Result

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

| Specification |
| --- |
| HTML Standard # dom-context-2d-ispointinstroke-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: `CanvasRenderingContext2D`


CanvasRenderingContext2D: globalAlpha property - Web APIs

CanvasRenderingContext2D: globalAlpha property
==============================================

 The
 **`CanvasRenderingContext2D.globalAlpha`**
 property of the Canvas 2D API specifies the alpha (transparency) value that is applied
 to shapes and images before they are drawn onto the canvas.

**Note:** See also the chapter Applying styles and color in the Canvas Tutorial.

Value
-----

A number between `0.0` (fully transparent) and `1.0` (fully opaque), inclusive. The default value is `1.0`. Values outside that range, including `Infinity` and `NaN`, will not be set, and `globalAlpha` will retain its previous value.

Examples
--------

### Drawing translucent shapes

 This example uses the `globalAlpha` property to draw two semi-transparent
 rectangles.

#### HTML

```html
<canvas id="canvas"></canvas>
```

#### JavaScript

```js
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");

ctx.globalAlpha = 0.5;

ctx.fillStyle = "blue";
ctx.fillRect(10, 10, 100, 100);

ctx.fillStyle = "red";
ctx.fillRect(50, 50, 100, 100);
```

#### Result

### Overlaying transparent shapes

 This example illustrates the effect of overlaying multiple transparent shapes on top of
 each other. We begin by drawing a solid background composed of four differently colored
 squares. Next, we set the `globalAlpha` property to `0.2` (20%
 opaque); this alpha level will apply to all of our transparent shapes. After that, we
 use a `for` loop to draw a series of circles with increasing radii.

 With each new circle, the opacity of the previous circles underneath is effectively
 increased. If we were to increase the step count (and thus draw more circles), the
 background would eventually disappear completely from the center of the image.
```

<canvas id="canvas" width="150" height="150"></canvas>
```

```js
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");

// Draw background
ctx.fillStyle = "#FD0";
ctx.fillRect(0, 0, 75, 75);
ctx.fillStyle = "#6C0";
ctx.fillRect(75, 0, 75, 75);
ctx.fillStyle = "#09F";
ctx.fillRect(0, 75, 75, 75);
ctx.fillStyle = "#F30";
ctx.fillRect(75, 75, 75, 75);
ctx.fillStyle = "#FFF";

// Set transparency value
ctx.globalAlpha = 0.2;

// Draw transparent circles
for (let i = 0; i < 7; i++) {
  ctx.beginPath();
  ctx.arc(75, 75, 10 + 10 \* i, 0, Math.PI \* 2, true);
  ctx.fill();
}
```

| Screenshot | Live sample |
| --- | --- |
|  |  |

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

| Specification |
| --- |
| HTML Standard # dom-context-2d-globalalpha-dev |

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

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

### Gecko-specific notes

* Starting with Gecko 5.0, specifying invalid values for `globalAlpha` no
 longer throws a `SYNTAX_ERR` exception; these are now correctly silently
 ignored.
### WebKit/Blink-specific notes

* In WebKit- and Blink-based browsers, a non-standard and deprecated method
 `ctx.setAlpha()` is implemented in addition to this property.
See also
--------

* The interface defining this property: `CanvasRenderingContext2D`
* `CanvasRenderingContext2D.globalCompositeOperation`


CanvasRenderingContext2D: imageSmoothingQuality property - Web APIs

CanvasRenderingContext2D: imageSmoothingQuality property
========================================================

 The **`imageSmoothingQuality`** property of the
 `CanvasRenderingContext2D` interface, part of the Canvas API, lets you set the quality of
 image smoothing.

**Note:** For this property to have an effect,
 `imageSmoothingEnabled`
 must be `true`.

Value
-----

One of the following:

`"low"`

Low quality.

`"medium"`

Medium quality.

`"high"`

High quality.

The default value is `"low"`.

Examples
--------

### Setting image smoothing quality

This example uses the `imageSmoothingQuality` property with a scaled image.

#### HTML

```html
<canvas id="canvas"></canvas>
```

#### JavaScript

```js
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");

let img = new Image();
img.src = "canvas\_createpattern.png";
img.onload = () => {
  ctx.imageSmoothingQuality = "low";
  ctx.drawImage(img, 0, 0, 300, 150);
};
```

#### Result

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

| Specification |
| --- |
| HTML Standard # dom-context-2d-imagesmoothingquality-dev |

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

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

See also
--------

* The interface defining this property: `CanvasRenderingContext2D`
* `CanvasRenderingContext2D.imageSmoothingEnabled`
* `image-rendering`


CanvasRenderingContext2D: measureText() method - Web APIs

CanvasRenderingContext2D: measureText() method
==============================================

 The
 `CanvasRenderingContext2D.measureText()`
 method returns a `TextMetrics` object that contains information about the
 measured text (such as its width, for example).

Syntax
------

```js
measureText(text)
```

### Parameters

`text`

The text string to measure.

### Return value

A `TextMetrics` object.

Examples
--------

Given this `<canvas>` element:

```html
<canvas id="canvas"></canvas>
```

… you can get a `TextMetrics` object using the following code:

```js
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");

let text = ctx.measureText("Hello world");
console.log(text.width); // 56;
```

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

| Specification |
| --- |
| HTML Standard # dom-context-2d-measuretext-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: `CanvasRenderingContext2D`
* `TextMetrics`


CanvasRenderingContext2D: font property - Web APIs

CanvasRenderingContext2D: font property
=======================================

 The **`CanvasRenderingContext2D.font`** property of the Canvas 2D API specifies the current text style to use when drawing text.
 This string uses the same syntax as the CSS font specifier.

Value
-----

A string parsed as CSS `font` value. The default font is 10px sans-serif.

Examples
--------

### Using a custom font

In this example we use the `font` property to specify a custom font weight, size, and family.

#### HTML

```html
<canvas id="canvas"></canvas>
```

#### JavaScript

```js
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");

ctx.font = "bold 48px serif";
ctx.strokeText("Hello world", 50, 100);
```

#### Result

### Loading fonts with the CSS Font Loading API

With the help of the `FontFace` API, you can explicitly load fonts before using them in a canvas.

```js
let f = new FontFace("test", "url(x)");

f.load().then(() => {
  // Ready to use the font in a canvas context
});
```

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

| Specification |
| --- |
| HTML Standard # dom-context-2d-font-dev |

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

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

See also
--------

* The interface defining this property: `CanvasRenderingContext2D`


CanvasRenderingContext2D: fontKerning property - Web APIs

CanvasRenderingContext2D: fontKerning property
==============================================

The **`CanvasRenderingContext2D.fontKerning`** property of the Canvas API specifies how font kerning information is used.

 Kerning adjusts how adjacent letters are spaced in a proportional font, allowing them to edge into each other's visual area if there is space available.
 For example, in well-kerned fonts, the characters `AV`, `Ta` and `We` nest together and make character spacing more uniform and pleasant to read than the equivalent text without kerning.

The property corresponds to the `font-kerning` CSS property.

Value
-----

The property can be used to get or set the value.

Allowed values are:

`auto`

 The browser determines whether font kerning should be used or not.
 For example, some browsers will disable kerning on small fonts, since applying it could harm the readability of text.

`normal`

Font kerning information stored in the font must be applied.

`none`

Font kerning information stored in the font is disabled.

Examples
--------

In this example we display the text "AVA Ta We" using each of the supported values of the `textRendering` property.

### HTML

```html
<canvas id="canvas" width="700" height="140"></canvas>
```

### JavaScript

```js
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
ctx.font = "30px serif";

// Default (auto)
ctx.fillText(`AVA Ta We (default: ${ctx.fontKerning})`, 5, 30);

// Font kerning: normal
ctx.fontKerning = "normal";
ctx.fillText(`AVA Ta We (${ctx.fontKerning})`, 5, 70);

// Font kerning: none
ctx.fontKerning = "none";
ctx.fillText(`AVA Ta We (${ctx.fontKerning})`, 5, 110);
```

### Result

Note that the last string has font kerning disabled, so adjacent characters are evenly spread.

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

| Specification |
| --- |
| HTML Standard # dom-context-2d-fontkerning |

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

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


CanvasRenderingContext2D: scrollPathIntoView() method - Web APIs

CanvasRenderingContext2D: scrollPathIntoView() method
=====================================================

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

 The
 **`CanvasRenderingContext2D.scrollPathIntoView()`**
 method of the Canvas 2D API scrolls the current or given path into view. It is similar
 to `Element.scrollIntoView()`.

Syntax
------

```js
scrollPathIntoView()
scrollPathIntoView(path)
```

### Parameters

`path`

A `Path2D` path to use.

### Return value

None (`undefined`).

Examples
--------

### Using the scrollPathIntoView method

This example demonstrates the `scrollPathIntoView()` method.

#### HTML

```html
<canvas id="canvas"></canvas>
```

#### JavaScript

```js
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");

ctx.beginPath();
ctx.fillRect(10, 10, 30, 30);
ctx.scrollPathIntoView();
```

#### Editable demo

Edit the code below to see your changes update live in the canvas:
```

<canvas id="canvas" width="400" height="200" class="playable-canvas">
  <input id="button" type="range" min="1" max="12" />
</canvas>
<div class="playable-buttons">
  <input id="edit" type="button" value="Edit" />
  <input id="reset" type="button" value="Reset" />
</div>
<textarea id="code" class="playable-code">
ctx.beginPath();
ctx.rect(10, 10, 30, 30);
ctx.fill();
if (ctx.scrollPathIntoView) {
  ctx.scrollPathIntoView();
} else {
  ctx.fillText("Your browser does not support 'scrollPathIntoView()'.", 0, 150);
}
</textarea>
```

```
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
const textarea = document.getElementById("code");
const reset = document.getElementById("reset");
const edit = document.getElementById("edit");
const code = textarea.value;

function drawCanvas() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  eval(textarea.value);
}

reset.addEventListener("click", () => {
  textarea.value = code;
  drawCanvas();
});

edit.addEventListener("click", () => {
  textarea.focus();
});

textarea.addEventListener("input", drawCanvas);
window.addEventListener("load", drawCanvas);
```

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

| Specification |
| --- |
| HTML Standard # dom-context-2d-scrollpathintoview-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: `CanvasRenderingContext2D`
* `Element.scrollIntoView()`


CanvasRenderingContext2D: shadowOffsetY property - Web APIs

CanvasRenderingContext2D: shadowOffsetY property
================================================

 The
 **`CanvasRenderingContext2D.shadowOffsetY`**
 property of the Canvas 2D API specifies the distance that shadows will be offset
 vertically.

**Note:** Shadows are only drawn if the
 `shadowColor` property is set to
 a non-transparent value. One of the `shadowBlur`,
 `shadowOffsetX`, or `shadowOffsetY` properties must be non-zero, as
 well.

Value
-----

A float specifying the distance that shadows will be offset vertically. Positive values are down, and negative are up. The default value is `0` (no vertical offset). `Infinity` and `NaN` values are ignored.

Examples
--------

### Moving a shadow vertically

 This example adds a blurred shadow to a rectangle. The
 `shadowColor` property sets its
 color, `shadowOffsetY` sets its offset 25 units towards the bottom, and
 `shadowBlur` gives it a blur level
 of 10.

#### HTML

```html
<canvas id="canvas"></canvas>
```

#### JavaScript

```js
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");

// Shadow
ctx.shadowColor = "red";
ctx.shadowOffsetY = 25;
ctx.shadowBlur = 10;

// Rectangle
ctx.fillStyle = "blue";
ctx.fillRect(20, 20, 150, 80);
```

#### Result

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

| Specification |
| --- |
| HTML Standard # dom-context-2d-shadowoffsety-dev |

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

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

See also
--------

* The interface defining this property: `CanvasRenderingContext2D`
* `CanvasRenderingContext2D.shadowOffsetX`
* `CanvasRenderingContext2D.shadowColor`
* `CanvasRenderingContext2D.shadowBlur`


CanvasRenderingContext2D: fillText() method - Web APIs

CanvasRenderingContext2D: fillText() method
===========================================

 The `CanvasRenderingContext2D` method
 **`fillText()`**, part of the Canvas 2D API, draws a text string
 at the specified coordinates, filling the string's characters with the current
 `fillStyle`. An optional parameter
 allows specifying a maximum width for the rendered text, which the user
 agent will achieve by condensing the text or by using a lower font size.

 This method draws directly to the canvas without modifying the current path, so any
 subsequent `fill()` or
 `stroke()` calls will have no effect
 on it.

 The text is rendered using the font and text layout configuration as defined by the
 `font`,
 `textAlign`,
 `textBaseline`, and
 `direction` properties.

**Note:** To draw the outlines of the characters in a string, call the context's
 `strokeText()` method.

Syntax
------

```js
fillText(text, x, y)
fillText(text, x, y, maxWidth)
```

### Parameters

`text`

 A string specifying the text string to render into the context.
 The text is rendered using the settings specified by
 `font`,
 `textAlign`,
 `textBaseline`, and
 `direction`.

`x`

The x-axis coordinate of the point at which to begin drawing the text, in pixels.

`y`

The y-axis coordinate of the baseline on which to begin drawing the text, in pixels.

`maxWidth` Optional

 The maximum number of pixels wide the text may be once rendered. If not specified,
 there is no limit to the width of the text. However, if this value is provided, the
 user agent will adjust the kerning, select a more horizontally condensed font (if one
 is available or can be generated without loss of quality), or scale down to a smaller
 font size in order to fit the text in the specified width.

### Return value

None (`undefined`).

Examples
--------

### Drawing filled text

This example writes the words "Hello world" using the `fillText()` method.

#### HTML

 First, we need a canvas to draw into. This code creates a context 400 pixels wide and
 150 pixels across.

```html
<canvas id="canvas" width="400" height="150"></canvas>
```

#### JavaScript

The JavaScript code for this example follows.

```js
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");

ctx.font = "50px serif";
ctx.fillText("Hello world", 50, 90);
```

 This code obtains a reference to the `<canvas>`, then gets a reference
 to its 2D graphics context.

 With that in hand, we set the `font` to
 50-pixel-tall "serif" (the user's default serif font),
 then call `fillText()` to draw the text "Hello world," starting at the
 coordinates (50, 90).

#### Result

### Restricting the text size

This example writes the words "Hello world," restricting its width to 140 pixels.

#### HTML

```html
<canvas id="canvas" width="400" height="150"></canvas>
```

#### JavaScript

```js
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");

ctx.font = "50px serif";
ctx.fillText("Hello world", 50, 90, 140);
```

#### Result

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

| Specification |
| --- |
| HTML Standard # dom-context-2d-filltext-dev |

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

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

See also
--------

* Drawing text
* `CanvasRenderingContext2D`
* `CanvasRenderingContext2D.strokeText()`


CanvasRenderingContext2D: lineTo() method - Web APIs

CanvasRenderingContext2D: lineTo() method
=========================================

 The `CanvasRenderingContext2D` method
 **`lineTo()`**, part of the Canvas 2D API, adds a straight line
 to the current sub-path by connecting the sub-path's last point to the specified
 `(x, y)` coordinates.

 Like other methods that modify the current path, this method does not directly render
 anything. To draw the path onto a canvas, you can use the
 `fill()` or
 `stroke()` methods.

Syntax
------

```js
lineTo(x, y)
```

### Parameters

`x`

The x-axis coordinate of the line's end point.

`y`

The y-axis coordinate of the line's end point.

### Return value

None (`undefined`).

Examples
--------

### Drawing a straight line

This example draws a straight line using the `lineTo()` method.

#### HTML

```html
<canvas id="canvas"></canvas>
```

#### JavaScript

The line begins at (30, 50) and ends at (150, 100).

```js
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");

ctx.beginPath(); // Start a new path
ctx.moveTo(30, 50); // Move the pen to (30, 50)
ctx.lineTo(150, 100); // Draw a line to (150, 100)
ctx.stroke(); // Render the path
```

#### Result

### Drawing connected lines

 Each call of `lineTo()` (and similar methods) automatically adds to the
 current sub-path, which means that all the lines will all be stroked or filled together.
 This example draws a letter 'M' with a single contiguous line.

#### HTML

```html
<canvas id="canvas"></canvas>
```

#### JavaScript

```js
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");

ctx.moveTo(90, 130);
ctx.lineTo(95, 25);
ctx.lineTo(150, 80);
ctx.lineTo(205, 25);
ctx.lineTo(210, 130);
ctx.lineWidth = 15;
ctx.stroke();
```

#### Result

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

| Specification |
| --- |
| HTML Standard # dom-context-2d-lineto-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: `CanvasRenderingContext2D`
* `CanvasRenderingContext2D.moveTo()`
* `CanvasRenderingContext2D.stroke()`


CanvasRenderingContext2D: textBaseline property - Web APIs

CanvasRenderingContext2D: textBaseline property
===============================================

 The
 **`CanvasRenderingContext2D.textBaseline`**
 property of the Canvas 2D API specifies the current text baseline used when drawing
 text.

Value
-----

Possible values:

`"top"`

The text baseline is the top of the em square.

`"hanging"`

 The text baseline is the hanging baseline. (Used by Tibetan and other Indic
 scripts.)

`"middle"`

The text baseline is the middle of the em square.

`"alphabetic"`

The text baseline is the normal alphabetic baseline. Default value.

`"ideographic"`

 The text baseline is the ideographic baseline; this is the bottom of the body of the
 characters, if the main body of characters protrudes beneath the alphabetic baseline.
 (Used by Chinese, Japanese, and Korean scripts.)

`"bottom"`

 The text baseline is the bottom of the bounding box. This differs from the
 ideographic baseline in that the ideographic baseline doesn't consider descenders.

The default value is `"alphabetic"`.

Examples
--------

### Comparison of property values

This example demonstrates the various `textBaseline` property values.

#### HTML

```html
<canvas id="canvas" width="550" height="500"></canvas>
```

#### JavaScript

```js
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");

const baselines = [
  "top",
  "hanging",
  "middle",
  "alphabetic",
  "ideographic",
  "bottom",
];
ctx.font = "36px serif";
ctx.strokeStyle = "red";

baselines.forEach((baseline, index) => {
  ctx.textBaseline = baseline;
  const y = 75 + index \* 75;
  ctx.beginPath();
  ctx.moveTo(0, y + 0.5);
  ctx.lineTo(550, y + 0.5);
  ctx.stroke();
  ctx.fillText(`Abcdefghijklmnop (${baseline})`, 0, y);
});
```

#### Result

### Comparison of property values on the same line

As with the previous example, this example demonstrates the various `textBaseline` property values, but in this case with all of them lined up horizontally along the same line — to make it easier to see how they differ from each other.

#### HTML

```html
<canvas id="canvas" width="724" height="160"></canvas>
```

#### JavaScript

```js
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");

const baselines = [
  "top",
  "hanging",
  "middle",
  "alphabetic",
  "ideographic",
  "bottom",
];
ctx.font = "20px serif";
ctx.strokeStyle = "red";

ctx.beginPath();
ctx.moveTo(0, 100);
ctx.lineTo(840, 100);
ctx.moveTo(0, 55);
ctx.stroke();

baselines.forEach((baseline, index) => {
  ctx.save();
  ctx.textBaseline = baseline;
  let x = index \* 120 + 10;
  ctx.fillText("Abcdefghijk", x, 100);
  ctx.restore();
  ctx.fillText(baseline, x + 5, 50);
});
```

#### Result

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

| Specification |
| --- |
| HTML Standard # dom-context-2d-textbaseline-dev |

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

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

See also
--------

* The interface defining this property: `CanvasRenderingContext2D`


CanvasRenderingContext2D: globalCompositeOperation property - Web APIs

CanvasRenderingContext2D: globalCompositeOperation property
===========================================================

 The
 **`CanvasRenderingContext2D.globalCompositeOperation`**
 property of the Canvas 2D API sets the type of compositing operation to apply when
 drawing new shapes.

See also Compositing and clipping in the Canvas Tutorial.

Value
-----

A string identifying which of the compositing or blending mode operations to use. This may be any of the following values:

`"source-over"`

This is the default setting and draws new shapes on top of the existing canvas content.

`"source-in"`

The new shape is drawn only where both the new shape and the destination canvas overlap. Everything else is made transparent.

`"source-out"`

The new shape is drawn where it doesn't overlap the existing canvas content.

`"source-atop"`

The new shape is only drawn where it overlaps the existing canvas content.

`"destination-over"`

New shapes are drawn behind the existing canvas content.

`"destination-in"`

The existing canvas content is kept where both the new shape and existing canvas content overlap. Everything else is made transparent.

`"destination-out"`

The existing content is kept where it doesn't overlap the new shape.

`"destination-atop"`

The existing canvas is only kept where it overlaps the new shape. The new shape is drawn behind the canvas content.

`"lighter"`

Where both shapes overlap, the color is determined by adding color values.

`"copy"`

Only the new shape is shown.

`"xor"`

Shapes are made transparent where both overlap and drawn normal everywhere else.

`"multiply"`

The pixels of the top layer are multiplied with the corresponding pixels of the bottom layer. A darker picture is the result.

`"screen"`

The pixels are inverted, multiplied, and inverted again. A lighter picture is the result (opposite of `multiply`)

`"overlay"`

A combination of `multiply` and `screen`. Dark parts on the base layer become darker, and light parts become lighter.

`"darken"`

Retains the darkest pixels of both layers.

`"lighten"`

Retains the lightest pixels of both layers.

`"color-dodge"`

Divides the bottom layer by the inverted top layer.

`"color-burn"`

Divides the inverted bottom layer by the top layer, and then inverts the result.

`"hard-light"`

Like `overlay`, a combination of `multiply` and `screen` — but instead with the top layer and bottom layer swapped.

`"soft-light"`

A softer version of `hard-light`. Pure black or white does not result in pure black or white.

`"difference"`

Subtracts the bottom layer from the top layer — or the other way round — to always get a positive value.

`"exclusion"`

Like `difference`, but with lower contrast.

`"hue"`

Preserves the luma and chroma of the bottom layer, while adopting the hue of the top layer.

`"saturation"`

Preserves the luma and hue of the bottom layer, while adopting the chroma of the top layer.

`"color"`

Preserves the luma of the bottom layer, while adopting the hue and chroma of the top layer.

`"luminosity"`

Preserves the hue and chroma of the bottom layer, while adopting the luma of the top layer.

Examples
--------

### Changing the composite operation

 This example uses the `globalCompositeOperation` property to draw two
 rectangles that exclude themselves where they overlap.

#### HTML

```html
<canvas id="canvas"></canvas>
```

#### JavaScript

```js
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");

ctx.globalCompositeOperation = "xor";

ctx.fillStyle = "blue";
ctx.fillRect(10, 10, 100, 100);

ctx.fillStyle = "red";
ctx.fillRect(50, 50, 100, 100);
```

#### Result

### Demonstration of all values

#### Global values

This code sets up the global values used by the rest of the program.

```js
const canvas1 = document.createElement("canvas");
const canvas2 = document.createElement("canvas");
const gco = [
  "source-over",
  "source-in",
  "source-out",
  "source-atop",
  "destination-over",
  "destination-in",
  "destination-out",
  "destination-atop",
  "lighter",
  "copy",
  "xor",
  "multiply",
  "screen",
  "overlay",
  "darken",
  "lighten",
  "color-dodge",
  "color-burn",
  "hard-light",
  "soft-light",
  "difference",
  "exclusion",
  "hue",
  "saturation",
  "color",
  "luminosity",
].reverse();
const gcoText = [
  "This is the default setting and draws new shapes on top of the existing canvas content.",
  "The new shape is drawn only where both the new shape and the destination canvas overlap. Everything else is made transparent.",
  "The new shape is drawn where it doesn't overlap the existing canvas content.",
  "The new shape is only drawn where it overlaps the existing canvas content.",
  "New shapes are drawn behind the existing canvas content.",
  "The existing canvas content is kept where both the new shape and existing canvas content overlap. Everything else is made transparent.",
  "The existing content is kept where it doesn't overlap the new shape.",
  "The existing canvas is only kept where it overlaps the new shape. The new shape is drawn behind the canvas content.",
  "Where both shapes overlap the color is determined by adding color values.",
  "Only the new shape is shown.",
  "Shapes are made transparent where both overlap and drawn normal everywhere else.",
  "The pixels of the top layer are multiplied with the corresponding pixel of the bottom layer. A darker picture is the result.",
  "The pixels are inverted, multiplied, and inverted again. A lighter picture is the result (opposite of multiply)",
  "A combination of multiply and screen. Dark parts on the base layer become darker, and light parts become lighter.",
  "Retains the darkest pixels of both layers.",
  "Retains the lightest pixels of both layers.",
  "Divides the bottom layer by the inverted top layer.",
  "Divides the inverted bottom layer by the top layer, and then inverts the result.",
  "A combination of multiply and screen like overlay, but with top and bottom layer swapped.",
  "A softer version of hard-light. Pure black or white does not result in pure black or white.",
  "Subtracts the bottom layer from the top layer or the other way round to always get a positive value.",
  "Like difference, but with lower contrast.",
  "Preserves the luma and chroma of the bottom layer, while adopting the hue of the top layer.",
  "Preserves the luma and hue of the bottom layer, while adopting the chroma of the top layer.",
  "Preserves the luma of the bottom layer, while adopting the hue and chroma of the top layer.",
  "Preserves the hue and chroma of the bottom layer, while adopting the luma of the top layer.",
].reverse();
const width = 320;
const height = 340;
```

#### Main program

When the page loads, this code runs to set up and run the example:

```js
window.onload = () => {
  // lum in sRGB
  const lum = {
    r: 0.33,
    g: 0.33,
    b: 0.33,
  };
  // resize canvas
  canvas1.width = width;
  canvas1.height = height;
  canvas2.width = width;
  canvas2.height = height;
  lightMix();
  colorSphere();
  runComposite();
  return;
};
```

And this code, `runComposite()`, handles the bulk of the work, relying on a number of utility functions to do the hard parts.

```js
function createCanvas() {
  const canvas = document.createElement("canvas");
  canvas.style.background = `url(${op\_8x8.data})`;
  canvas.style.border = "1px solid #000";
  canvas.style.margin = "5px";
  canvas.width = width / 2;
  canvas.height = height / 2;
  return canvas;
}

function runComposite() {
  const dl = document.createElement("dl");
  document.body.appendChild(dl);
  while (gco.length) {
    const pop = gco.pop();
    const dt = document.createElement("dt");
    dt.textContent = pop;
    dl.appendChild(dt);
    const dd = document.createElement("dd");
    const p = document.createElement("p");
    p.textContent = gcoText.pop();
    dd.appendChild(p);

    const canvasToDrawOn = createCanvas();
    const canvasToDrawFrom = createCanvas();
    const canvasToDrawResult = createCanvas();

    let ctx = canvasToDrawResult.getContext("2d");
    ctx.clearRect(0, 0, width, height);
    ctx.save();
    ctx.drawImage(canvas1, 0, 0, width / 2, height / 2);
    ctx.globalCompositeOperation = pop;
    ctx.drawImage(canvas2, 0, 0, width / 2, height / 2);
    ctx.globalCompositeOperation = "source-over";
    ctx.fillStyle = "rgb(0 0 0 / 80%)";
    ctx.fillRect(0, height / 2 - 20, width / 2, 20);
    ctx.fillStyle = "#FFF";
    ctx.font = "14px arial";
    ctx.fillText(pop, 5, height / 2 - 5);
    ctx.restore();

    ctx = canvasToDrawOn.getContext("2d");
    ctx.clearRect(0, 0, width, height);
    ctx.save();
    ctx.drawImage(canvas1, 0, 0, width / 2, height / 2);
    ctx.fillStyle = "rgb(0 0 0 / 80%)";
    ctx.fillRect(0, height / 2 - 20, width / 2, 20);
    ctx.fillStyle = "#FFF";
    ctx.font = "14px arial";
    ctx.fillText("existing content", 5, height / 2 - 5);
    ctx.restore();

    ctx = canvasToDrawFrom.getContext("2d");
    ctx.clearRect(0, 0, width, height);
    ctx.save();
    ctx.drawImage(canvas2, 0, 0, width / 2, height / 2);
    ctx.fillStyle = "rgb(0 0 0 / 80%)";
    ctx.fillRect(0, height / 2 - 20, width / 2, 20);
    ctx.fillStyle = "#FFF";
    ctx.font = "14px arial";
    ctx.fillText("new content", 5, height / 2 - 5);
    ctx.restore();

    dd.appendChild(canvasToDrawOn);
    dd.appendChild(canvasToDrawFrom);
    dd.appendChild(canvasToDrawResult);

    dl.appendChild(dd);
  }
}
```

#### Utility functions

The program relies on a number of utility functions.

```js
const lightMix = () => {
  const ctx = canvas2.getContext("2d");
  ctx.save();
  ctx.globalCompositeOperation = "lighter";
  ctx.beginPath();
  ctx.fillStyle = "rgb(255 0 0 / 100%)";
  ctx.arc(100, 200, 100, Math.PI \* 2, 0, false);
  ctx.fill();
  ctx.beginPath();
  ctx.fillStyle = "rgb(0 0 255 / 100%)";
  ctx.arc(220, 200, 100, Math.PI \* 2, 0, false);
  ctx.fill();
  ctx.beginPath();
  ctx.fillStyle = "rgb(0 255 0 / 100%)";
  ctx.arc(160, 100, 100, Math.PI \* 2, 0, false);
  ctx.fill();
  ctx.restore();
  ctx.beginPath();
  ctx.fillStyle = "#f00";
  ctx.fillRect(0, 0, 30, 30);
  ctx.fill();
};
```

```js
const colorSphere = (element) => {
  const ctx = canvas1.getContext("2d");
  const width = 360;
  const halfWidth = width / 2;
  const rotate = (1 / 360) \* Math.PI \* 2; // per degree
  const offset = 0; // scrollbar offset
  const oleft = -20;
  const otop = -20;
  for (let n = 0; n <= 359; n++) {
    const gradient = ctx.createLinearGradient(
      oleft + halfWidth,
      otop,
      oleft + halfWidth,
      otop + halfWidth,
    );
    const color = Color.HSV\_RGB({ H: (n + 300) % 360, S: 100, V: 100 });
    gradient.addColorStop(0, "rgb(0 0 0 / 0%)");
    gradient.addColorStop(0.7, `rgb(${color.R} ${color.G} ${color.B} / 100%)`);
    gradient.addColorStop(1, "rgb(255 255 255 / 100%)");
    ctx.beginPath();
    ctx.moveTo(oleft + halfWidth, otop);
    ctx.lineTo(oleft + halfWidth, otop + halfWidth);
    ctx.lineTo(oleft + halfWidth + 6, otop);
    ctx.fillStyle = gradient;
    ctx.fill();
    ctx.translate(oleft + halfWidth, otop + halfWidth);
    ctx.rotate(rotate);
    ctx.translate(-(oleft + halfWidth), -(otop + halfWidth));
  }
  ctx.beginPath();
  ctx.fillStyle = "#00f";
  ctx.fillRect(15, 15, 30, 30);
  ctx.fill();
  return ctx.canvas;
};
```

```js
// HSV (1978) = H: Hue / S: Saturation / V: Value
Color = {};
Color.HSV\_RGB = (o) => {
  const S = o.S / 100;
  let H = o.H / 360,
    V = o.V / 100;
  let R, G;
  let A, B, C, D;
  if (S === 0) {
    R = G = B = Math.round(V \* 255);
  } else {
    if (H >= 1) H = 0;
    H \*= 6;
    D = H - Math.floor(H);
    A = Math.round(255 \* V \* (1 - S));
    B = Math.round(255 \* V \* (1 - S \* D));
    C = Math.round(255 \* V \* (1 - S \* (1 - D)));
    V = Math.round(255 \* V);
    switch (Math.floor(H)) {
      case 0:
        R = V;
        G = C;
        B = A;
        break;
      case 1:
        R = B;
        G = V;
        B = A;
        break;
      case 2:
        R = A;
        G = V;
        B = C;
        break;
      case 3:
        R = A;
        G = B;
        B = V;
        break;
      case 4:
        R = C;
        G = A;
        B = V;
        break;
      case 5:
        R = V;
        G = A;
        B = B;
        break;
    }
  }
  return { R, G, B };
};

const createInterlace = (size, color1, color2) => {
  const proto = document.createElement("canvas").getContext("2d");
  proto.canvas.width = size \* 2;
  proto.canvas.height = size \* 2;
  proto.fillStyle = color1; // top-left
  proto.fillRect(0, 0, size, size);
  proto.fillStyle = color2; // top-right
  proto.fillRect(size, 0, size, size);
  proto.fillStyle = color2; // bottom-left
  proto.fillRect(0, size, size, size);
  proto.fillStyle = color1; // bottom-right
  proto.fillRect(size, size, size, size);
  const pattern = proto.createPattern(proto.canvas, "repeat");
  pattern.data = proto.canvas.toDataURL();
  return pattern;
};

const op_8x8 = createInterlace(8, "#FFF", "#eee");
```

#### Result

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

| Specification |
| --- |
| HTML Standard # dom-context-2d-globalcompositeoperation-dev |

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

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

See also
--------

* The interface defining this property: `CanvasRenderingContext2D`
* `CanvasRenderingContext2D.globalAlpha`


CanvasRenderingContext2D: fontVariantCaps property - Web APIs

CanvasRenderingContext2D: fontVariantCaps property
==================================================

The **`CanvasRenderingContext2D.fontVariantCaps`** property of the Canvas API specifies an alternative capitalization of the rendered text.

This corresponds to the CSS `font-variant-caps` property.

Value
-----

The font alternative capitalization value, which is one of:

`normal` (default)

Deactivates of the use of alternate glyphs.

`small-caps`

 Enables display of small capitals (OpenType feature: `smcp`).
 Small-caps glyphs typically use the form of uppercase letters but are reduced to the size of lowercase letters.

`all-small-caps`

Enables display of small capitals for both upper and lowercase letters (OpenType features: `c2sc`, `smcp`).

`petite-caps`

Enables display of petite capitals (OpenType feature: `pcap`).

`all-petite-caps`

Enables display of petite capitals for both upper and lowercase letters (OpenType features: `c2pc`, `pcap`).

`unicase`

Enables display of mixture of small capitals for uppercase letters with normal lowercase letters (OpenType feature: `unic`).

`titling-caps`

 Enables display of titling capitals (OpenType feature: `titl`).
 Uppercase letter glyphs are often designed for use with lowercase letters.
 When used in all uppercase titling sequences they can appear too strong.
 Titling capitals are designed specifically for this situation.

The property can be used to get or set the font capitalization value.

Note that there are accessibility concerns with some of these, which are outlined in the corresponding `font-variant-caps` topic.

Examples
--------

 In this example we display the text "Hello World" using each of the supported values of the `fontVariantCaps` property.
 The value is also displayed for each case by reading the property.

### HTML

```html
<canvas id="canvas" width="700" height="220"></canvas>
```

### JavaScript

```js
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
ctx.font = "20px serif";

// Default (normal)
ctx.fillText(`Hello world (default: ${ctx.fontVariantCaps})`, 5, 20);

// Capitalization: small-caps
ctx.fontVariantCaps = "small-caps";
ctx.fillText(`Hello world (${ctx.fontVariantCaps})`, 5, 50);

// Capitalization: all-small-caps
ctx.fontVariantCaps = "all-small-caps";
ctx.fillText(`Hello world (${ctx.fontVariantCaps})`, 5, 80);

// Capitalization: petite-caps
ctx.fontVariantCaps = "petite-caps";
ctx.fillText(`Hello world (${ctx.fontVariantCaps})`, 5, 110);

// Capitalization: all-petite-caps
ctx.fontVariantCaps = "all-petite-caps";
ctx.fillText(`Hello world (${ctx.fontVariantCaps})`, 5, 140);

// Capitalization: unicase
ctx.fontVariantCaps = "unicase";
ctx.fillText(`Hello world (${ctx.fontVariantCaps})`, 5, 170);

// Capitalization: titling-caps
ctx.fontVariantCaps = "titling-caps";
ctx.fillText(`Hello world (${ctx.fontVariantCaps})`, 5, 200);
```

### Result

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

| Specification |
| --- |
| HTML Standard # dom-context-2d-fontvariantcaps |

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

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


CanvasRenderingContext2D: createLinearGradient() method - Web APIs

CanvasRenderingContext2D: createLinearGradient() method
=======================================================

 The
 **`CanvasRenderingContext2D.createLinearGradient()`**
 method of the Canvas 2D API creates a gradient along the line connecting two given
 coordinates.

![The gradient transitions colors along the gradient line, starting at point x0, y0 and going to x1, y1, even if those points extend the gradient line beyond the edges of the element on which the gradient is drawn.](/en-US/docs/Web/API/CanvasRenderingContext2D/createLinearGradient/mdn-canvas-lineargradient.png)

 This method returns a linear `CanvasGradient`. To be applied to a shape,
 the gradient must first be assigned to the
 `fillStyle` or
 `strokeStyle` properties.

**Note:** Gradient coordinates are global, i.e., relative to the current
 coordinate space. When applied to a shape, the coordinates are NOT relative to the
 shape's coordinates.

Syntax
------

```js
createLinearGradient(x0, y0, x1, y1)
```

 The `createLinearGradient()` method is specified by four parameters defining
 the start and end points of the gradient line.

### Parameters

`x0`

The x-axis coordinate of the start point.

`y0`

The y-axis coordinate of the start point.

`x1`

The x-axis coordinate of the end point.

`y1`

The y-axis coordinate of the end point.

### Return value

A linear `CanvasGradient` initialized with the specified line.

### Exceptions

`NotSupportedError` `DOMException`

Thrown when non-finite values are passed as parameters.

Examples
--------

### Filling a rectangle with a linear gradient

 This example initializes a linear gradient using the
 `createLinearGradient()` method. Three color stops between the gradient's
 start and end points are then created. Finally, the gradient is assigned to the canvas
 context, and is rendered to a filled rectangle.

#### HTML

```html
<canvas id="canvas"></canvas>
```

#### JavaScript

```js
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");

// Create a linear gradient
// The start gradient point is at x=20, y=0
// The end gradient point is at x=220, y=0
const gradient = ctx.createLinearGradient(20, 0, 220, 0);

// Add three color stops
gradient.addColorStop(0, "green");
gradient.addColorStop(0.5, "cyan");
gradient.addColorStop(1, "green");

// Set the fill style and draw a rectangle
ctx.fillStyle = gradient;
ctx.fillRect(20, 20, 200, 100);
```

#### Result

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

| Specification |
| --- |
| HTML Standard # dom-context-2d-createlineargradient-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: `CanvasRenderingContext2D`
* `CanvasRenderingContext2D.createRadialGradient()`
* `CanvasRenderingContext2D.createConicGradient()`


CanvasRenderingContext2D: arc() method - Web APIs

CanvasRenderingContext2D: arc() method
======================================

 The
 **`CanvasRenderingContext2D.arc()`**
 method of the Canvas 2D API adds a circular arc to the current sub-path.

Syntax
------

```js
arc(x, y, radius, startAngle, endAngle)
arc(x, y, radius, startAngle, endAngle, counterclockwise)
```

 The `arc()` method creates a circular arc centered at `(x, y)`
 with a radius of `radius`. The path starts at `startAngle`, ends
 at `endAngle`, and travels in the direction given by
 `counterclockwise` (defaulting to clockwise).

### Parameters

`x`

The horizontal coordinate of the arc's center.

`y`

The vertical coordinate of the arc's center.

`radius`

The arc's radius. Must be positive.

`startAngle`

The angle at which the arc starts in radians, measured from the positive x-axis.

`endAngle`

The angle at which the arc ends in radians, measured from the positive x-axis.

`counterclockwise` Optional

 An optional boolean value. If `true`, draws the arc
 counter-clockwise between the start and end angles. The default is `false`
 (clockwise).

### Return value

None (`undefined`).

Examples
--------

### Drawing a full circle

This example draws a complete circle with the `arc()` method.

#### HTML

```html
<canvas></canvas>
```

#### JavaScript

 The arc is given an x-coordinate of 100, a y-coordinate of 75, and a radius of 50. To
 make a full circle, the arc begins at an angle of 0 radians (0**°**), and
 ends at an angle of 2π radians (360**°**).

```js
const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");

ctx.beginPath();
ctx.arc(100, 75, 50, 0, 2 \* Math.PI);
ctx.stroke();
```

#### Result

### Different shapes demonstrated

This example draws various shapes to show what is possible with `arc()`.
```

<canvas width="150" height="200"></canvas>
```

```js
const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");

// Draw shapes
for (let i = 0; i <= 3; i++) {
  for (let j = 0; j <= 2; j++) {
    ctx.beginPath();
    let x = 25 + j \* 50; // x coordinate
    let y = 25 + i \* 50; // y coordinate
    let radius = 20; // Arc radius
    let startAngle = 0; // Starting point on circle
    let endAngle = Math.PI + (Math.PI \* j) / 2; // End point on circle
    let counterclockwise = i % 2 === 1; // Draw counterclockwise

    ctx.arc(x, y, radius, startAngle, endAngle, counterclockwise);

    if (i > 1) {
      ctx.fill();
    } else {
      ctx.stroke();
    }
  }
}
```

#### Result

| Screenshot | Live sample |
| --- | --- |
|  |  |

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

| Specification |
| --- |
| HTML Standard # dom-context-2d-arc-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: `CanvasRenderingContext2D`
* Use `CanvasRenderingContext2D.ellipse()` to draw an elliptical arc.


CanvasRenderingContext2D: isContextLost() method - Web APIs

CanvasRenderingContext2D: isContextLost() method
================================================

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 **`CanvasRenderingContext2D.isContextLost()`** method of the Canvas 2D API returns `true` if the rendering context is lost (and has not yet been reset).
 This might occur due to driver crashes, running out of memory, and so on.

 If the user agent detects that the canvas backing storage is lost it will fire the `contextlost` event at the associated `HTMLCanvasElement`.
 If this event is not cancelled it will attempt to reset the backing storage to the default state (this is equivalent to calling `CanvasRenderingContext2D.reset()`).
 On success it will fire the `contextrestored` event, indicating that the context is ready to reinitialize and redraw.

Syntax
------

```js
isContextLost()
```

### Parameters

None.

### Return value

`true` if the rendering context was lost; `false` otherwise.

### Examples

```js
const ctx = canvas.getContext("2d");

if (ctx.isContextLost()) {
  console.log("Context is lost");
}
```

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

| Specification |
| --- |
| HTML Standard # dom-context-2d-iscontextlost |

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

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

See also
--------

* The interface defining this method: `CanvasRenderingContext2D`
* `HTMLCanvasElement: contextlost` event
* `HTMLCanvasElement: contextrestored` event


CanvasRenderingContext2D: quadraticCurveTo() method - Web APIs

CanvasRenderingContext2D: quadraticCurveTo() method
===================================================

 The
 **`CanvasRenderingContext2D.quadraticCurveTo()`**
 method of the Canvas 2D API adds a quadratic Bézier curve to the current
 sub-path. It requires two points: the first one is a control point and the second one is
 the end point. The starting point is the latest point in the current path, which can be
 changed using `moveTo()` before creating
 the quadratic Bézier curve.

Syntax
------

```js
quadraticCurveTo(cpx, cpy, x, y)
```

### Parameters

`cpx`

The x-axis coordinate of the control point.

`cpy`

The y-axis coordinate of the control point.

`x`

The x-axis coordinate of the end point.

`y`

The y-axis coordinate of the end point.

### Return value

None (`undefined`).

Examples
--------

### How quadraticCurveTo works

This example shows how a quadratic Bézier curve is drawn.

#### HTML

```html
<canvas id="canvas"></canvas>
```

#### JavaScript

```js
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");

// Quadratic Bézier curve
ctx.beginPath();
ctx.moveTo(50, 20);
ctx.quadraticCurveTo(230, 30, 50, 100);
ctx.stroke();

// Start and end points
ctx.fillStyle = "blue";
ctx.beginPath();
ctx.arc(50, 20, 5, 0, 2 \* Math.PI); // Start point
ctx.arc(50, 100, 5, 0, 2 \* Math.PI); // End point
ctx.fill();

// Control point
ctx.fillStyle = "red";
ctx.beginPath();
ctx.arc(230, 30, 5, 0, 2 \* Math.PI);
ctx.fill();
```

#### Result

 In this example, the control point is red and the
 start and end points are blue.

### A simple quadratic curve

 This example draws a simple quadratic Bézier curve using
 `quadraticCurveTo()`.

#### HTML

```html
<canvas id="canvas"></canvas>
```

#### JavaScript

 The curve begins at the point specified by `moveTo()`: (20, 110). The
 control point is placed at (230, 150). The curve ends at (250, 20).

```js
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");

ctx.beginPath();
ctx.moveTo(20, 110);
ctx.quadraticCurveTo(230, 150, 250, 20);
ctx.stroke();
```

#### Result

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

| Specification |
| --- |
| HTML Standard # dom-context-2d-quadraticcurveto-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: `CanvasRenderingContext2D`
* Bézier curve


CanvasRenderingContext2D: lineCap property - Web APIs

CanvasRenderingContext2D: lineCap property
==========================================

 The
 **`CanvasRenderingContext2D.lineCap`**
 property of the Canvas 2D API determines the shape used to draw the end points of lines.

**Note:** Lines can be drawn with the
 `stroke()`, `strokeRect()`,
 and `strokeText()` methods.

Value
-----

One of the following:

`"butt"`

The ends of lines are squared off at the endpoints. Default value.

`"round"`

The ends of lines are rounded.

`"square"`

 The ends of lines are squared off by adding a box with an equal width and half the
 height of the line's thickness.

Examples
--------

### Changing the shape of line caps

This example rounds the end caps of a straight line.

#### HTML

```html
<canvas id="canvas"></canvas>
```

#### JavaScript

```js
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");

ctx.beginPath();
ctx.moveTo(20, 20);
ctx.lineWidth = 15;
ctx.lineCap = "round";
ctx.lineTo(100, 100);
ctx.stroke();
```

#### Result

### Comparison of line caps

 In this example three lines are drawn, each with a different value for the
 `lineCap` property. Two guides to see the exact differences between the three
 are added. Each of these lines starts and ends exactly on these guides.

 The line on the left uses the default `"butt"` option. It's drawn completely
 flush with the guides. The second is set to use the `"round"` option. This
 adds a semicircle to the end that has a radius half the width of the line. The line on
 the right uses the `"square"` option. This adds a box with an equal width and
 half the height of the line thickness.
```

<canvas id="canvas" width="150" height="150"></canvas>
```

```js
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");

// Draw guides
ctx.strokeStyle = "#09f";
ctx.beginPath();
ctx.moveTo(10, 10);
ctx.lineTo(140, 10);
ctx.moveTo(10, 140);
ctx.lineTo(140, 140);
ctx.stroke();

// Draw lines
ctx.strokeStyle = "black";
["butt", "round", "square"].forEach((lineCap, i) => {
  ctx.lineWidth = 15;
  ctx.lineCap = lineCap;
  ctx.beginPath();
  ctx.moveTo(25 + i \* 50, 10);
  ctx.lineTo(25 + i \* 50, 140);
  ctx.stroke();
});
```

| Screenshot | Live sample |
| --- | --- |
|  |  |

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

| Specification |
| --- |
| HTML Standard # dom-context-2d-linecap-dev |

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

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

### WebKit/Blink-specific notes

* In WebKit- and Blink-based Browsers, a non-standard and deprecated method
 `ctx.setLineCap()` is implemented in addition to this property.
See also
--------

* The interface defining this property: `CanvasRenderingContext2D`
* `CanvasRenderingContext2D.lineWidth`
* `CanvasRenderingContext2D.lineJoin`
* Applying styles and color


CanvasRenderingContext2D: stroke() method - Web APIs

CanvasRenderingContext2D: stroke() method
=========================================

 The
 **`CanvasRenderingContext2D.stroke()`**
 method of the Canvas 2D API strokes (outlines) the current or given path with the
 current stroke style.

 Strokes are aligned to the center of a path; in other words, half of the stroke is
 drawn on the inner side, and half on the outer side.

 The stroke is drawn using the non-zero winding rule, which
 means that path intersections will still get filled.

Syntax
------

```js
stroke()
stroke(path)
```

### Parameters

`path`

A `Path2D` path to stroke.

### Return value

None (`undefined`).

Examples
--------

### A simple stroked rectangle

 This example creates a rectangle using the `rect()` method, and then draws
 it to the canvas using `stroke()`.

#### HTML

```html
<canvas id="canvas"></canvas>
```

#### JavaScript

```js
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
ctx.rect(10, 10, 150, 100);
ctx.stroke();
```

#### Result

### Re-stroking paths

 Typically, you'll want to call `beginPath()` for each new thing you want to stroke. If you don't, the previous
 sub-paths will remain part of the current path, and get stroked every time you call the
 `stroke()` method. In some cases, however, this may be the desired effect.

#### HTML

```html
<canvas id="canvas"></canvas>
```

#### JavaScript

 This code strokes the first path three times, the second path two times, and the third
 path only once.

```js
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");

// First sub-path
ctx.lineWidth = 26;
ctx.strokeStyle = "orange";
ctx.moveTo(20, 20);
ctx.lineTo(160, 20);
ctx.stroke();

// Second sub-path
ctx.lineWidth = 14;
ctx.strokeStyle = "green";
ctx.moveTo(20, 80);
ctx.lineTo(220, 80);
ctx.stroke();

// Third sub-path
ctx.lineWidth = 4;
ctx.strokeStyle = "pink";
ctx.moveTo(20, 140);
ctx.lineTo(280, 140);
ctx.stroke();
```

#### Result

### Stroking and filling

 If you want to both stroke and fill a path, the order in which you perform these
 actions will determine the result. In this example, the square on the left is drawn with
 the stroke on top of the fill. The square on the right is drawn with the fill on top of
 the stroke.

#### HTML

```html
<canvas id="canvas"></canvas>
```

#### JavaScript

```js
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");

ctx.lineWidth = 16;
ctx.strokeStyle = "red";

// Stroke on top of fill
ctx.beginPath();
ctx.rect(25, 25, 100, 100);
ctx.fill();
ctx.stroke();

// Fill on top of stroke
ctx.beginPath();
ctx.rect(175, 25, 100, 100);
ctx.stroke();
ctx.fill();
```

#### Result

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

| Specification |
| --- |
| HTML Standard # dom-context-2d-stroke-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: `CanvasRenderingContext2D`


FeaturePolicy: allowsFeature() method - Web APIs

FeaturePolicy: allowsFeature() method
=====================================

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

 The **`allowsFeature()`** method of
 the `FeaturePolicy` interface enables introspection of individual
 directives of the Permissions Policy it is run on. It returns a `Boolean`
 that is `true` if and only if the specified feature is allowed in the
 specified context (or the default context if no context is specified).

Syntax
------

```js
allowsFeature(feature)
allowsFeature(feature, origin)
```

### Parameters

`feature`

The specific feature name to check its availability.

`origin` Optional

The specific origin name to check its availability. If not specificed, the default origin will be used.

### Return value

 A `Boolean` that is `true` if and only if the feature is
 allowed.

Example
-------

 The following example queries whether or not the document is allowed to use camera API
 by the Permissions Policy. Please note that Camera API might be restricted by the
 Permissions API, if the user did not grant the corresponding permission yet.

```js
// First, get the Feature Policy object
const featurePolicy = document.featurePolicy;

// Then query feature for specific
const allowed = featurePolicy.allowsFeature("camera");

if (allowed) {
  console.log("FP allows camera.");
} else {
  console.log("FP does not allows camera.");
}
```

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

#### No specification found

No specification data found for `api.FeaturePolicy.allowsFeature`.
Check for problems with this page or contribute a missing `spec_url` to mdn/browser-compat-data. Also make sure the specification is included in w3c/browser-specs.

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

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


FeaturePolicy: features() method - Web APIs

FeaturePolicy: features() method
================================

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

 The **`features()`** method of the
 `FeaturePolicy` interface returns a list of names of all features
 supported by the User Agent. Feature whose name appears on the list might not be
 allowed by the Permissions Policy of the current execution context and/or might not be
 accessible because of user's permissions.

Syntax
------

```js
features()
```

### Parameters

None.

### Return value

 A list of strings that represent names of all Permissions Policy directives supported by
 the user agent.

Example
-------

The following example logs all the supported directives in the console.

```js
// Get the FeaturePolicy object
const featurePolicy = document.featurePolicy;

// Retrieve the list of all supported Permissions Policy directives
const supportedDirectives = featurePolicy.features();

// Print out each directive into the console
for (const directive of supportedDirectives) {
  console.log(directive);
}
```

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

#### No specification found

No specification data found for `api.FeaturePolicy.features`.
Check for problems with this page or contribute a missing `spec_url` to mdn/browser-compat-data. Also make sure the specification is included in w3c/browser-specs.

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

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


FeaturePolicy: allowedFeatures() method - Web APIs

FeaturePolicy: allowedFeatures() method
=======================================

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

 The **`allowedFeatures()`** method of
 the `FeaturePolicy` interface returns a list of directive names of all
 features allowed by the Permissions Policy. This enables introspection of individual directives
 of the Permissions Policy it is run on. As such, `allowedFeatures()` method
 returns a subset of directives returned by `features()`.

Syntax
------

```js
allowedFeatures()
```

### Parameters

None.

### Return value

 An array of strings representing the Permissions Policy directive names that are allowed by
 the Permissions Policy this method is called on.

Example
-------

 The following example logs all the allowed directives for the current document. Please
 note that these features might be restricted by the Permissions API, if the user did not
 grant the corresponding permission yet.

```js
// First, get the Permissions Policy object
const featurePolicy = document.featurePolicy;

// Then query feature for specific
const allowed = featurePolicy.allowedFeatures();

for (const directive of allowed) {
  console.log(directive);
}
```

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

#### No specification found

No specification data found for `api.FeaturePolicy.allowedFeatures`.
Check for problems with this page or contribute a missing `spec_url` to mdn/browser-compat-data. Also make sure the specification is included in w3c/browser-specs.

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

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


FeaturePolicy: getAllowlistForFeature() method - Web APIs

FeaturePolicy: getAllowlistForFeature() method
==============================================

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

 The **`getAllowlistForFeature()`**
 method of the `FeaturePolicy` interface enables querying of the allowlist for a specific feature for the current Permissions Policy.

Syntax
------

```js
getAllowlistForFeature(feature)
```

### Parameter

`feature`

The specific feature name to get its allowlist.

### Return value

An array of strings containing the serialized list of allowed origins for the feature. If a wildcard (`*`) is used, the array will contain `*`.

Errors
------

 The function will raise a warning if the specified Permissions Policy directive name is not
 known. However, it will also return empty array, indicating that no origin is allowed to
 use the feature.

Example
-------

 The following example prints all the origins that are allowed to use Camera API by the
 Permissions Policy. Please note that Camera API might also be restricted by the Permissions API, if the user did not grant the corresponding permission.

```js
// First, get the FeaturePolicy object
const featurePolicy = document.featurePolicy;

// Query for specific feature
const allowlist = featurePolicy.getAllowlistForFeature("camera");

for (const origin of allowlist) {
  console.log(origin);
}
```

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

#### No specification found

No specification data found for `api.FeaturePolicy.getAllowlistForFeature`.
Check for problems with this page or contribute a missing `spec_url` to mdn/browser-compat-data. Also make sure the specification is included in w3c/browser-specs.

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

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


CSSVariableReferenceValue: fallback property - Web APIs

CSSVariableReferenceValue: fallback property
============================================

 The **`fallback`** read-only property of the
 `CSSVariableReferenceValue` interface returns the custom property fallback value of the `CSSVariableReferenceValue`.

Value
-----

A `CSSUnparsedValue`.

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

| Specification |
| --- |
| CSS Typed OM Level 1 # dom-cssvariablereferencevalue-fallback |

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

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


CSSVariableReferenceValue: variable property - Web APIs

CSSVariableReferenceValue: variable property
============================================

 The **`variable`** property of the
 `CSSVariableReferenceValue` interface returns the custom property name of the
 `CSSVariableReferenceValue`.

Value
-----

A string beginning with `--` (that is, a custom property name).

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

| Specification |
| --- |
| CSS Typed OM Level 1 # dom-cssvariablereferencevalue-variable |

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

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


CSSVariableReferenceValue: CSSVariableReferenceValue() constructor - Web APIs

CSSVariableReferenceValue: CSSVariableReferenceValue() constructor
==================================================================

Creates a new `CSSVariableReferenceValue`.

Syntax
------

```js
new CSSVariableReferenceValue(variable)
new CSSVariableReferenceValue(variable, fallback)
```

### Parameters

`variable`

A custom property name.

`fallback` Optional

A custom property fallback value.

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

| Specification |
| --- |
| CSS Typed OM Level 1 # dom-cssvariablereferencevalue-cssvariablereferencevalue |

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

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


CSSMathNegate: CSSMathNegate() constructor - Web APIs

CSSMathNegate: CSSMathNegate() constructor
==========================================

 The **`CSSMathNegate()`** constructor creates a
 new `CSSMathNegate` object which negates the value passed into it.

Syntax
------

```js
new CSSMathNegate(arg)
```

### Parameters

`arg`

A `CSSNumericValue`.

Examples
--------

To do

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

| Specification |
| --- |
| CSS Typed OM Level 1 # dom-cssmathnegate-cssmathnegate |

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

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


CSSMathNegate: value property - Web APIs

CSSMathNegate: value property
=============================

 The CSSMathNegate.value read-only property of the
 `CSSMathNegate` interface returns a `CSSNumericValue` object.

Value
-----

A `CSSNumericValue`.

Examples
--------

To do

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

| Specification |
| --- |
| CSS Typed OM Level 1 # dom-cssmathnegate-value |

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

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