CanvasRenderingContext2D: rect() method - Web APIs

CanvasRenderingContext2D: rect() method
=======================================

 The
 **`CanvasRenderingContext2D.rect()`**
 method of the Canvas 2D API adds a rectangle to the current path.

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

**Note:** To both create and render a rectangle in one step, use the
 `fillRect()` or
 `strokeRect()` methods.

Syntax
------

```js
rect(x, y, width, height)
```

 The `rect()` method creates a rectangular path whose starting point is at
 `(x, y)` and whose size is specified by `width` and
 `height`.

### Parameters

`x`

The x-axis coordinate of the rectangle's starting point.

`y`

The y-axis coordinate of the rectangle's starting point.

`width`

The rectangle's width. Positive values are to the right, and negative to the left.

`height`

The rectangle's height. Positive values are down, and negative are up.

### Return value

None (`undefined`).

Examples
--------

### Drawing a rectangle

 This example creates a rectangular path using the `rect()` method. The path
 is then rendered using the `fill()` method.

#### HTML

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

#### JavaScript

 The rectangle's corner is located at (10, 20). It has a width of 150 and a height of
 100.

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

#### Result

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

| Specification |
| --- |
| HTML Standard # dom-context-2d-rect-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.fillRect`
* `CanvasRenderingContext2D.strokeRect()`
* `CanvasRenderingContext2D.fill()`
* `CanvasRenderingContext2D.stroke()`


CanvasRenderingContext2D: ellipse() method - Web APIs

CanvasRenderingContext2D: ellipse() method
==========================================

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

Syntax
------

```js
ellipse(x, y, radiusX, radiusY, rotation, startAngle, endAngle)
ellipse(x, y, radiusX, radiusY, rotation, startAngle, endAngle, counterclockwise)
```

 The `ellipse()` method creates an elliptical arc centered at
 `(x, y)` with the radii `radiusX` and `radiusY`. The
 path starts at `startAngle` and ends at `endAngle`, and travels in
 the direction given by `counterclockwise` (defaulting to clockwise).

### Parameters

`x`

The x-axis (horizontal) coordinate of the ellipse's center.

`y`

The y-axis (vertical) coordinate of the ellipse's center.

`radiusX`

The ellipse's major-axis radius. Must be non-negative.

`radiusY`

The ellipse's minor-axis radius. Must be non-negative.

`rotation`

The rotation of the ellipse, expressed in radians.

`startAngle`

 The eccentric angle at which the ellipse starts, measured clockwise from the positive x-axis
 and expressed in radians.

`endAngle`

 The eccentric angle at which the ellipse ends, measured clockwise from the positive x-axis and
 expressed in radians.

`counterclockwise` Optional

 An optional boolean value which, if `true`, draws the ellipse
 counterclockwise (anticlockwise). The default value is `false`
 (clockwise).

### Return value

None (`undefined`).

Examples
--------

### Drawing a full ellipse

 This example draws an ellipse at an angle of π/4 radians (45**°**). To
 make a full ellipse, the arc begins at an angle of 0 radians (0**°**), and
 ends at an angle of 2π radians (360**°**).

#### HTML

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

#### JavaScript

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

// Draw the ellipse
ctx.beginPath();
ctx.ellipse(100, 100, 50, 75, Math.PI / 4, 0, 2 \* Math.PI);
ctx.stroke();

// Draw the ellipse's line of reflection
ctx.beginPath();
ctx.setLineDash([5, 5]);
ctx.moveTo(0, 200);
ctx.lineTo(200, 0);
ctx.stroke();
```

#### Result

### Various elliptical arcs

This example creates three elliptical paths with varying properties.

#### HTML

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

#### JavaScript

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

ctx.fillStyle = "red";
ctx.beginPath();
ctx.ellipse(60, 75, 50, 30, Math.PI \* 0.25, 0, Math.PI \* 1.5);
ctx.fill();

ctx.fillStyle = "blue";
ctx.beginPath();
ctx.ellipse(150, 75, 50, 30, Math.PI \* 0.25, 0, Math.PI);
ctx.fill();

ctx.fillStyle = "green";
ctx.beginPath();
ctx.ellipse(240, 75, 50, 30, Math.PI \* 0.25, 0, Math.PI, true);
ctx.fill();
```

#### Result

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

| Specification |
| --- |
| HTML Standard # dom-context-2d-ellipse-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.arc()` to draw a circular arc


CanvasRenderingContext2D: drawFocusIfNeeded() method - Web APIs

CanvasRenderingContext2D: drawFocusIfNeeded() method
====================================================

 The
 **`CanvasRenderingContext2D.drawFocusIfNeeded()`**
 method of the Canvas 2D API draws a focus ring around the current or given path, if the
 specified element is focused.

Syntax
------

```js
drawFocusIfNeeded(element)
drawFocusIfNeeded(path, element)
```

### Parameters

`element`

The element to check whether it is focused or not.

`path`

A `Path2D` path to use.

### Return value

None (`undefined`).

Examples
--------

### Managing button focus

 This example draws two buttons on a canvas. The `drawFocusIfNeeded()` method
 is used to draw a focus ring when appropriate.

#### HTML

```html
<canvas id="canvas">
  <button id="button1">Continue</button>
  <button id="button2">Quit</button>
</canvas>
```

#### JavaScript

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

document.addEventListener("focus", redraw, true);
document.addEventListener("blur", redraw, true);
canvas.addEventListener("click", handleClick, false);
redraw();

function redraw() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  drawButton(button1, 20, 20);
  drawButton(button2, 20, 80);
}

function handleClick(e) {
  // Calculate click coordinates
  const x = e.clientX - canvas.offsetLeft;
  const y = e.clientY - canvas.offsetTop;

  // Focus button1, if appropriate
  drawButton(button1, 20, 20);
  if (ctx.isPointInPath(x, y)) {
    button1.focus();
  }

  // Focus button2, if appropriate
  drawButton(button2, 20, 80);
  if (ctx.isPointInPath(x, y)) {
    button2.focus();
  }
}

function drawButton(el, x, y) {
  const active = document.activeElement === el;
  const width = 150;
  const height = 40;

  // Button background
  ctx.fillStyle = active ? "pink" : "lightgray";
  ctx.fillRect(x, y, width, height);

  // Button text
  ctx.font = "15px sans-serif";
  ctx.textAlign = "center";
  ctx.textBaseline = "middle";
  ctx.fillStyle = active ? "blue" : "black";
  ctx.fillText(el.textContent, x + width / 2, y + height / 2);

  // Define clickable area
  ctx.beginPath();
  ctx.rect(x, y, width, height);

  // Draw focus ring, if appropriate
  ctx.drawFocusIfNeeded(el);
}
```

#### Result

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

| Specification |
| --- |
| HTML Standard # dom-context-2d-drawfocusifneeded-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: getTransform() method - Web APIs

CanvasRenderingContext2D: getTransform() method
===============================================

The **`CanvasRenderingContext2D.getTransform()`** method of the Canvas 2D API retrieves the current transformation matrix being applied to the context.

Syntax
------

```js
getTransform()
```

### Parameters

None.

### Return value

A `DOMMatrix` object.

The transformation matrix is described by:

[

a

c

e

b

d

f

0

0

1

]

 \left[ \begin{array}{ccc} a & c & e \ b & d
 & f \ 0 & 0 & 1 \end{array} \right]

**Note:** The returned object is not live, so updating it will not
 affect the current transformation matrix, and updating the current transformation
 matrix will not affect an already returned `DOMMatrix`.

Examples
--------

 In the following example, we have two `<canvas>` elements. We apply a
 transform to the first one's context using
 `CanvasRenderingContext2D.setTransform()` and draw a square on it, then
 retrieve the matrix from it using `getTransform()`.

 We then apply the retrieved matrix directly to the second canvas context by passing the
 `DOMMatrix` object directly to `setTransform()`, and draw a circle
 on it.

### HTML

```html
<canvas width="240"></canvas> <canvas width="240"></canvas>
```

### CSS

```css
canvas {
  border: 1px solid black;
}
```

### JavaScript

```js
const canvases = document.querySelectorAll("canvas");
const ctx1 = canvases[0].getContext("2d");
const ctx2 = canvases[1].getContext("2d");

ctx1.setTransform(1, 0.2, 0.8, 1, 0, 0);
ctx1.fillRect(25, 25, 50, 50);

let storedTransform = ctx1.getTransform();
console.log(storedTransform);

ctx2.setTransform(storedTransform);
ctx2.beginPath();
ctx2.arc(50, 50, 50, 0, 2 \* Math.PI);
ctx2.fill();
```

### Result

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

| Specification |
| --- |
| HTML Standard # dom-context-2d-gettransform-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.transform()`


CanvasRenderingContext2D: shadowColor property - Web APIs

CanvasRenderingContext2D: shadowColor property
==============================================

 The
 **`CanvasRenderingContext2D.shadowColor`**
 property of the Canvas 2D API specifies the color of shadows.

 Be aware that the shadow's rendered opacity will be affected by the opacity of the
 `fillStyle` color when filling, and
 of the `strokeStyle` color when
 stroking.

**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 string parsed as a CSS `<color>` value. The default value is fully-transparent black.

Examples
--------

### Adding a shadow to shapes

 This example adds a shadow to two squares; the first one is filled, and the second one
 is stroked. The `shadowColor` property sets the shadows' color, while
 `shadowOffsetX` and `shadowOffsetY` set their position relative to
 the shapes.

#### HTML

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

#### JavaScript

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

// Shadow
ctx.shadowColor = "red";
ctx.shadowOffsetX = 10;
ctx.shadowOffsetY = 10;

// Filled rectangle
ctx.fillRect(20, 20, 100, 100);

// Stroked rectangle
ctx.lineWidth = 6;
ctx.strokeRect(170, 20, 100, 100);
```

#### Result

### Shadows on translucent shapes

 A shadow's opacity is affected by the transparency level of its parent object (even
 when `shadowColor` specifies a completely opaque value). This example strokes
 and fills a rectangle with translucent colors.

#### HTML

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

#### JavaScript

 The resulting alpha value of the fill shadow is `.8 * .2`, or
 `.16`. The alpha of the stroke shadow is `.8 * .6`, or
 `.48`.

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

// Shadow
ctx.shadowColor = "rgb(255 0 0 / 80%)";
ctx.shadowBlur = 8;
ctx.shadowOffsetX = 30;
ctx.shadowOffsetY = 20;

// Filled rectangle
ctx.fillStyle = "rgb(0 255 0 / 20%)";
ctx.fillRect(10, 10, 150, 100);

// Stroked rectangle
ctx.lineWidth = 10;
ctx.strokeStyle = "rgb(0 0 255 / 60%)";
ctx.strokeRect(10, 10, 150, 100);
```

#### Result

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

| Specification |
| --- |
| HTML Standard # dom-context-2d-shadowcolor-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, the non-standard and deprecated method
 `ctx.setShadow()` is implemented besides this property.

```js
setShadow(width, height, blur, color, alpha);
setShadow(width, height, blur, graylevel, alpha);
setShadow(width, height, blur, r, g, b, a);
setShadow(width, height, blur, c, m, y, k, a);
```

See also
--------

* The interface defining this property: `CanvasRenderingContext2D`


CanvasRenderingContext2D: drawImage() method - Web APIs

CanvasRenderingContext2D: drawImage() method
============================================

 The **`CanvasRenderingContext2D.drawImage()`** method of the
 Canvas 2D API provides different ways to draw an image onto the canvas.

Syntax
------

```js
drawImage(image, dx, dy)
drawImage(image, dx, dy, dWidth, dHeight)
drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight)
```

![drawImage](/en-US/docs/Web/API/CanvasRenderingContext2D/drawImage/canvas_drawimage.jpg)

### Parameters

`image`

 An element to draw into the context. The specification permits any canvas image
 source, specifically,
 an `HTMLImageElement`,
 an `SVGImageElement`,
 an `HTMLVideoElement`,
 an `HTMLCanvasElement`,
 an `ImageBitmap`,
 an `OffscreenCanvas`,
 or a `VideoFrame`.

`sx` Optional

 The x-axis coordinate of the top left corner of the sub-rectangle of the source
 `image` to draw into the destination context. Use the 3- or 5-argument syntax
 to omit this argument.

`sy` Optional

 The y-axis coordinate of the top left corner of the sub-rectangle of the source
 `image` to draw into the destination context. Use the 3- or 5-argument syntax
 to omit this argument.

`sWidth` Optional

 The width of the sub-rectangle of the source `image` to draw into the
 destination context. If not specified, the entire rectangle from the coordinates
 specified by `sx` and `sy` to the bottom-right corner of the
 image is used. Use the 3- or 5-argument syntax to omit this argument.
 A negative value will flip the image.

`sHeight` Optional

 The height of the sub-rectangle of the source `image` to draw into the
 destination context. Use the 3- or 5-argument syntax to omit this argument.
 A negative value will flip the image.

`dx`

 The x-axis coordinate in the destination canvas at which to place the top-left
 corner of the source `image`.

`dy`

 The y-axis coordinate in the destination canvas at which to place the top-left
 corner of the source `image`.

`dWidth`

 The width to draw the `image` in the destination canvas. This allows
 scaling of the drawn image. If not specified, the image is not scaled in width when
 drawn. Note that this argument is not included in the 3-argument syntax.

`dHeight`

 The height to draw the `image` in the destination canvas. This allows
 scaling of the drawn image. If not specified, the image is not scaled in height when
 drawn. Note that this argument is not included in the 3-argument syntax.

### Return value

None (`undefined`).

### Exceptions

`InvalidStateError` `DOMException`

Thrown when the image has no image data or if the canvas or source rectangle width or height is zero.

`TypeMismatchError` `DOMException`

Thrown when a `null` or `undefined` image is passed as parameter.

Examples
--------

### Drawing an image to the canvas

This example draws an image to the canvas using the `drawImage()` method.

#### HTML

```html
<canvas id="canvas"></canvas>
<div style="display:none;">
  <img id="source" src="rhino.jpg" width="300" height="227" />
</div>
```

#### JavaScript

 The source image is taken from the coordinates (33, 71), with a width of 104 and a
 height of 124. It is drawn to the canvas at (21, 20), where it is given a width of 87
 and a height of 104.

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

image.addEventListener("load", (e) => {
  ctx.drawImage(image, 33, 71, 104, 124, 21, 20, 87, 104);
});
```

#### Result

### Understanding source element size

The `drawImage()` method uses the source element's *intrinsic size in CSS
pixels* when drawing.

 For example, if you load an `Image` and specify the optional size parameters
 in its constructor, you will
 have to use the `naturalWidth` and `naturalHeight` properties of
 the created instance to properly calculate things like crop and scale regions, rather
 than `element.width` and `element.height`. The same goes for
 `videoWidth` and `videoHeight` if the element is a
 `<video>` element, and so on.

#### HTML

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

#### JavaScript

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

const image = new Image(60, 45); // Using optional size for image
image.onload = drawImageActualSize; // Draw when image has loaded

// Load an image of intrinsic size 300x227 in CSS pixels
image.src = "rhino.jpg";

function drawImageActualSize() {
  // Use the intrinsic size of image in CSS pixels for the canvas element
  canvas.width = this.naturalWidth;
  canvas.height = this.naturalHeight;

  // Will draw the image as 300x227, ignoring the custom size of 60x45
  // given in the constructor
  ctx.drawImage(this, 0, 0);

  // To use the custom size we'll have to specify the scale parameters
  // using the element's width and height properties - lets draw one
  // on top in the corner:
  ctx.drawImage(this, 0, 0, this.width, this.height);
}
```

#### Result

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

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

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

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

Notes
-----

* `drawImage()` only works correctly on an `HTMLVideoElement`
 when its `HTMLMediaElement.readyState` is greater than 1 (i.e.,
 **seek** event fired after setting the `currentTime`
 property).
* `drawImage()` will always use the source element's *intrinsic size in
CSS pixels* when drawing, cropping, and/or scaling.
* In some older browser versions, `drawImage()` will ignore all EXIF
 metadata in images, including the Orientation. This behavior is especially troublesome
 on iOS devices. You should detect the Orientation yourself and use
 `rotate()` to make it right.
See also
--------

* The interface defining this method: `CanvasRenderingContext2D`


CanvasRenderingContext2D: letterSpacing property - Web APIs

CanvasRenderingContext2D: letterSpacing property
================================================

The **`CanvasRenderingContext2D.letterSpacing`** property of the Canvas API specifies the spacing between letters when drawing text.

This corresponds to the CSS `letter-spacing` property.

Value
-----

 The letter spacing as a string in the CSS `<length>` data format.
 The default is `0px`.

 The property can be used to get or set the spacing.
 The property value will remain unchanged if set to an invalid/unparsable value.

Examples
--------

 In this example we display the text "Hello World" three times, using the `letterSpacing` property to modify the letter spacing in each case.
 The spacing is also displayed for each case, using the value of the property.

### HTML

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

### JavaScript

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

ctx.font = "30px serif";

// Default letter spacing
ctx.fillText(`Hello world (default: ${ctx.letterSpacing})`, 10, 40);

// Custom letter spacing: 10px
ctx.letterSpacing = "10px";
ctx.fillText(`Hello world (${ctx.letterSpacing})`, 10, 90);

// Custom letter spacing: 20px
ctx.letterSpacing = "20px";
ctx.fillText(`Hello world (${ctx.letterSpacing})`, 10, 140);
```

### Result

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

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

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

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

See also
--------

* `CanvasRenderingContext2D.wordSpacing`


CanvasRenderingContext2D: arcTo() method - Web APIs

CanvasRenderingContext2D: arcTo() method
========================================

 The **`CanvasRenderingContext2D.arcTo()`** method of the Canvas 2D API adds a circular arc to the current sub-path, using the given control points and radius.
 The arc is automatically connected to the path's latest point with a straight line if necessary, for example if the starting point and control points are in a line.

This method is commonly used for making rounded corners.

**Note:** You may get unexpected results when using a
 relatively large radius: the arc's connecting line will go in whatever direction it
 must to meet the specified radius.

Syntax
------

```js
arcTo(x1, y1, x2, y2, radius)
```

### Parameters

`x1`

The x-axis coordinate of the first control point.

`y1`

The y-axis coordinate of the first control point.

`x2`

The x-axis coordinate of the second control point.

`y2`

The y-axis coordinate of the second control point.

`radius`

The arc's radius. Must be non-negative.

#### Usage notes

Assume *P0* is the point on the path when `arcTo()` is called, *P1* = (`x1`, `y1`) and *P2* = (`x2`, `y2`) are the first and second control points, respectively, and *r* is the `radius` specified in the call:

* If *r* is negative, an `IndexSizeError` exception is raised.
* If *r* is 0, `arcTo()` behaves as if *P0*, *P1*, and *P2* are collinear (in a line).
* In the case of all of the points being collinear, a line from *P0* to *P1* is drawn unless the points *P0* and *P1* are coincident (having the same coordinates), in which case nothing is drawn.

These conditions can be created in the Constructing an arcTo() path example below to see the results.

### Return value

None (`undefined`).

### Exceptions

`IndexSizeError` `DOMException`

Thrown if `radius` is a negative value.

Examples
--------

### How `arcTo()` works

 One way to think about `arcTo()` is to imagine two straight segments: one
 from the starting point to a first control point, and another from there to a second
 control point. Without `arcTo()`, these two segments would form a sharp
 corner: `arcTo()` creates a circular arc at this corner and smooths it
 out. In other words, the arc is tangential to both segments.

#### HTML

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

#### JavaScript

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

// Tangential lines
ctx.beginPath();
ctx.strokeStyle = "gray";
ctx.moveTo(200, 20);
ctx.lineTo(200, 130);
ctx.lineTo(50, 20);
ctx.stroke();

// Arc
ctx.beginPath();
ctx.strokeStyle = "black";
ctx.lineWidth = 5;
ctx.moveTo(200, 20);
ctx.arcTo(200, 130, 50, 20, 40);
ctx.stroke();

// Start point
ctx.beginPath();
ctx.fillStyle = "blue";
ctx.arc(200, 20, 5, 0, 2 \* Math.PI);
ctx.fill();

// Control points
ctx.beginPath();
ctx.fillStyle = "red";
ctx.arc(200, 130, 5, 0, 2 \* Math.PI); // Control point one
ctx.arc(50, 20, 5, 0, 2 \* Math.PI); // Control point two
ctx.fill();
```

#### Result

In this example, the path created by `arcTo()` is **thick and
black**. Tangent lines are gray, control points are red, and the start point is blue.

### Creating a rounded corner

 This example creates a rounded corner using `arcTo()`. This is one of the
 method's most common uses.

#### HTML

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

#### JavaScript

 The arc begins at the point specified by `moveTo()`: (230, 20). It is shaped
 to fit control points at (90, 130) and (20, 20), and has a radius of 50. The
 `lineTo()` method connects the arc to (20, 20) with a straight line. Note
 that the arc's second control point and the point specified by `lineTo()` are
 the same, which produces a totally smooth corner.

```js
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
const p0 = { x: 230, y: 20 };
const p1 = { x: 90, y: 130 };
const p2 = { x: 20, y: 20 };

const labelPoint = (p) => {
  const offset = 10;
  ctx.fillText(`(${p.x},${p.y})`, p.x + offset, p.y + offset);
};

ctx.beginPath();
ctx.lineWidth = 4;
ctx.font = "1em sans-serif";
ctx.moveTo(p0.x, p0.y);
ctx.arcTo(p1.x, p1.y, p2.x, p2.y, 50);
ctx.lineTo(p2.x, p2.y);

labelPoint(p0);
labelPoint(p1);
labelPoint(p2);

ctx.stroke();
```

#### Result

### Result of a large radius

 If you use a relatively large radius, the arc may appear in a place you didn't expect.
 In this example, the arc's connecting line goes above, instead of below, the coordinate
 specified by `moveTo()`. This happens because the radius is too large for the
 arc to fit entirely below the starting point.

#### HTML

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

#### JavaScript

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

ctx.beginPath();
ctx.moveTo(180, 90);
ctx.arcTo(180, 130, 110, 130, 130);
ctx.lineTo(110, 130);
ctx.stroke();
```

#### Result

### Constructing an arcTo() path

 The demo shows the semi-infinite lines and circle with center *C* tangent
 to the lines at *T1* and *T2* used to
 determine the path rendered by `arcTo()`.

 Note that `arcTo` will create a straight line from *P0*
 to *P1* when all points are in a line. Additionally,
 nothing is drawn by `arcTo` if *P0* and
 *P1* have the same coordinates.

 Besides being able to set the arc radius with the slider, the initial point
 *P0* and control points *P1* and
 *P2* can be moved by dragging them with the mouse with the
 left button down. The numeric values can also be edited, and the arrow keys
 can be used to change an underlined element that is in focus.
```

<div>
  <label for="arc-radius">arc radius <em>r</em></label>
  <input name="arc-radius" type="range" id="radius-slider" min="0" />
  <label
 for="arc-radius"
 id="value-r"
 class="input"
 contenteditable="true"></label>
</div>
<div>
  <span id="value-P0" class="input" tabindex="0">
    <em>P<sub>0</sub></em>
  </span>
  = (<span id="value-P0x" class="input" contenteditable="true"></span>,
  <span id="value-P0y" class="input" contenteditable="true"></span>)

  <span id="value-P1" class="input" tabindex="0">
    <em>P<sub>1</sub></em>
  </span>
  = (<span id="value-P1x" class="input" contenteditable="true"></span>,
  <span id="value-P1y" class="input" contenteditable="true"></span>)

  <span id="value-P2" class="input" tabindex="0">
    <em>P<sub>2</sub></em>
  </span>
  = (<span id="value-P2x" class="input" contenteditable="true"></span>,
  <span id="value-P2y" class="input" contenteditable="true"></span>)
</div>
<canvas id="canvas"></canvas>
<div>
  <em>T<sub>1</sub></em> = <span id="value-T1"></span>
</div>
<div>
  <em>T<sub>2</sub></em> = <span id="value-T2"></span>
</div>
<div><em>C</em> = <span id="value-C"></span></div>

```

```
label {
  margin: 10px;
}
.input {
  color: #00f;
  text-decoration: underline;
}
#canvas {
  border: 1px solid #000;
}
```

### Animating `arcTo()` drawing

 For this example, you can play around with the arc radius to see how
 the path changes. The path is drawn from the starting point *p0* using `arcTo()` with control points
 *p1* and *p2* and a radius that varies from 0 to the maximum radius selected with the slider.
 Then a `lineTo()` call completes the path to *p2*.

#### HTML

```html
<div>
  <label for="radius">Radius: </label>
  <input name="radius" type="range" id="radius" min="0" max="100" value="50" />
  <label for="radius" id="radius-output">50</label>
</div>
<canvas id="canvas"></canvas>
```

#### JavaScript

```js
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
const controlOut = document.getElementById("radius-output");
const control = document.getElementById("radius");
control.oninput = () => {
  controlOut.textContent = radius = control.value;
};

const p1 = { x: 100, y: 100 };
const p2 = { x: 150, y: 50 };
const p3 = { x: 200, y: 100 };
let radius = control.value; // match with init control value

function labelPoint(p, offset, i = 0) {
  const { x, y } = offset;
  ctx.beginPath();
  ctx.arc(p.x, p.y, 2, 0, Math.PI \* 2);
  ctx.fill();
  ctx.fillText(`${i}:(${p.x}, ${p.y})`, p.x + x, p.y + y);
}

function drawPoints(points) {
  points.forEach((p, i) => {
    labelPoint(p, { x: 0, y: -20 }, `p${i}`);
  });
}

// Draw arc
function drawArc([p0, p1, p2], r) {
  ctx.beginPath();
  ctx.moveTo(p0.x, p0.y);
  ctx.arcTo(p1.x, p1.y, p2.x, p2.y, r);
  ctx.lineTo(p2.x, p2.y);
  ctx.stroke();
}

function loop(t) {
  const angle = (t / 1000) % (2 \* Math.PI);
  const rr = Math.abs(Math.cos(angle) \* radius);

  ctx.clearRect(0, 0, canvas.width, canvas.height);

  drawArc([p1, p2, p3], rr);
  drawPoints([p1, p2, p3]);
  requestAnimationFrame(loop);
}

loop(0);
```

#### Result

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

| Specification |
| --- |
| HTML Standard # dom-context-2d-arcto-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: bezierCurveTo() method - Web APIs

CanvasRenderingContext2D: bezierCurveTo() method
================================================

 The
 **`CanvasRenderingContext2D.bezierCurveTo()`**
 method of the Canvas 2D API adds a cubic Bézier curve to the current
 sub-path. It requires three points: the first two are control points and the third 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 Bézier curve.

Syntax
------

```js
bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y)
```

### Parameters

`cp1x`

The x-axis coordinate of the first control point.

`cp1y`

The y-axis coordinate of the first control point.

`cp2x`

The x-axis coordinate of the second control point.

`cp2y`

The y-axis coordinate of the second 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 bezierCurveTo works

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

#### HTML

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

#### JavaScript

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

// Define the points as {x, y}
let start = { x: 50, y: 20 };
let cp1 = { x: 230, y: 30 };
let cp2 = { x: 150, y: 80 };
let end = { x: 250, y: 100 };

// Cubic Bézier curve
ctx.beginPath();
ctx.moveTo(start.x, start.y);
ctx.bezierCurveTo(cp1.x, cp1.y, cp2.x, cp2.y, end.x, end.y);
ctx.stroke();

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

// Control points
ctx.fillStyle = "red";
ctx.beginPath();
ctx.arc(cp1.x, cp1.y, 5, 0, 2 \* Math.PI); // Control point one
ctx.arc(cp2.x, cp2.y, 5, 0, 2 \* Math.PI); // Control point two
ctx.fill();
```

#### Result

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

### A simple Bézier curve

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

#### HTML

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

#### JavaScript

 The curve begins at the point specified by `moveTo()`: (30, 30). The first
 control point is placed at (120, 160), and the second at (180, 10). The curve ends at
 (220, 140).

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

ctx.beginPath();
ctx.moveTo(30, 30);
ctx.bezierCurveTo(120, 160, 180, 10, 220, 140);
ctx.stroke();
```

#### Result

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

| Specification |
| --- |
| HTML Standard # dom-context-2d-beziercurveto-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: resetTransform() method - Web APIs

CanvasRenderingContext2D: resetTransform() method
=================================================

 The
 **`CanvasRenderingContext2D.resetTransform()`**
 method of the Canvas 2D API resets the current transform to the identity matrix.

Syntax
------

```js
resetTransform()
```

Examples
--------

### Resetting the matrix

 This example draws a rotated rectangle after modifying the matrix, and then resets the
 matrix using the `resetTransform()` method.

#### HTML

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

#### JavaScript

 The `rotate()` method rotates the
 transformation matrix by 45°. The `fillRect()` method draws a filled rectangle, adjusted according to that matrix.

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

// Draw a rotated rectangle
ctx.rotate((45 \* Math.PI) / 180);
ctx.fillRect(60, 0, 100, 30);

// Reset transformation matrix to the identity matrix
ctx.resetTransform();
```

#### Result

### Continuing with a regular matrix

 Whenever you're done drawing transformed shapes, you should call
 `resetTransform()` before rendering anything else. In this example, the first
 two shapes are drawn with a skew transformation, and the last two are drawn with the
 identity (regular) transformation.

#### HTML

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

#### JavaScript

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

// Skewed rectangles
ctx.transform(1, 0, 1.7, 1, 0, 0);
ctx.fillStyle = "gray";
ctx.fillRect(40, 40, 50, 20);
ctx.fillRect(40, 90, 50, 20);

// Non-skewed rectangles
ctx.resetTransform();
ctx.fillStyle = "red";
ctx.fillRect(40, 40, 50, 20);
ctx.fillRect(40, 90, 50, 20);
```

#### Result

The skewed rectangles are gray, and the non-skewed rectangles are red.

Polyfill
--------

 You can also use the `setTransform()` method to reset the current transform to the identity matrix, like
 so:

```js
ctx.setTransform(1, 0, 0, 1, 0, 0);
```

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

| Specification |
| --- |
| HTML Standard # dom-context-2d-resettransform-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: beginPath() method - Web APIs

CanvasRenderingContext2D: beginPath() method
============================================

 The
 **`CanvasRenderingContext2D.beginPath()`**
 method of the Canvas 2D API starts a new path by emptying the list of sub-paths. Call
 this method when you want to create a new path.

**Note:** To create a new sub-path, i.e., one matching the current
 canvas state, you can use `CanvasRenderingContext2D.moveTo()`.

Syntax
------

```js
beginPath()
```

### Parameters

None.

### Return value

None (`undefined`).

Examples
--------

### Creating distinct paths

This example creates two paths, each of which contains a single line.

#### HTML

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

#### JavaScript

 The `beginPath()` method is called before beginning each line, so that they
 may be drawn with different colors.

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

// First path
ctx.beginPath();
ctx.strokeStyle = "blue";
ctx.moveTo(20, 20);
ctx.lineTo(200, 20);
ctx.stroke();

// Second path
ctx.beginPath();
ctx.strokeStyle = "green";
ctx.moveTo(20, 20);
ctx.lineTo(120, 120);
ctx.stroke();
```

#### Result

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

| Specification |
| --- |
| HTML Standard # dom-context-2d-beginpath-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.closePath()`


CanvasRenderingContext2D: transform() method - Web APIs

CanvasRenderingContext2D: transform() method
============================================

 The
 **`CanvasRenderingContext2D.transform()`**
 method of the Canvas 2D API multiplies the current transformation with the matrix
 described by the arguments of this method. This lets you scale, rotate, translate
 (move), and skew the context.

**Note:** See also the
 `setTransform()` method, which
 resets the current transform to the identity matrix and then invokes
 `transform()`.

Syntax
------

```js
transform(a, b, c, d, e, f)
```

The transformation matrix is described by:

[

a

c

e

b

d

f

0

0

1

]

 \left[ \begin{array}{ccc} a & c & e \ b & d
 & f \ 0 & 0 & 1 \end{array} \right]

### Parameters

`a` (`m11`)

The cell in the first row and first column of the matrix.

`b` (`m12`)

The cell in the second row and first column of the matrix.

`c` (`m21`)

The cell in the first row and second column of the matrix.

`d` (`m22`)

The cell in the second row and second column of the matrix.

`e` (`m41`)

The cell in the first row and third column of the matrix.

`f` (`m42`)

The cell in the second row and third column of the matrix.

If a point originally had coordinates

(
x
,
y
)

(x, y)

, then after the transformation it will have coordinates

(
a
x
+
c
y
+
e
,
b
x
+
d
y
+
f
)

(ax + cy + e, bx + dy + f)

. This means:

* `e` and `f` control the horizontal and vertical translation of the context.
* When `b` and `c` are `0`, `a` and `d` control the horizontal and vertical scaling of the context.
* When `a` and `d` are `1`, `b` and `c` control the horizontal and vertical skewing of the context.
### Return value

None (`undefined`).

Examples
--------

### Skewing a shape

 This example skews a rectangle both vertically (`.2`) and horizontally
 (`.8`). Scaling and translation remain unchanged.

#### HTML

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

#### JavaScript

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

ctx.transform(1, 0.2, 0.8, 1, 0, 0);
ctx.fillRect(0, 0, 100, 100);
```

#### Result

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

| Specification |
| --- |
| HTML Standard # dom-context-2d-transform-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.setTransform()`


CanvasRenderingContext2D: save() method - Web APIs

CanvasRenderingContext2D: save() method
=======================================

 The
 **`CanvasRenderingContext2D.save()`**
 method of the Canvas 2D API saves the entire state of the canvas by pushing the current
 state onto a stack.

### The drawing state

The drawing state that gets saved onto a stack consists of:

* The current transformation matrix.
* The current clipping region.
* The current dash list.
* The current values of the following attributes:
 `strokeStyle`,
 `fillStyle`,
 `globalAlpha`,
 `lineWidth`,
 `lineCap`,
 `lineJoin`,
 `miterLimit`,
 `lineDashOffset`,
 `shadowOffsetX`,
 `shadowOffsetY`,
 `shadowBlur`,
 `shadowColor`,
 `globalCompositeOperation`, `font`,
 `textAlign`,
 `textBaseline`,
 `direction`,
 `imageSmoothingEnabled`.
Syntax
------

```js
save()
```

### Parameters

None.

### Return value

None (`undefined`).

Examples
--------

### Saving the drawing state

 This example uses the `save()` method to save the current state and
 `restore()` to restore it later, so that you are able to draw a rect with the
 current state later.

#### HTML

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

#### JavaScript

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

// Save the current state
ctx.save();

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

// Restore to the state saved by the most recent call to save()
ctx.restore();

ctx.fillRect(150, 40, 100, 100);
```

#### Result

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

| Specification |
| --- |
| HTML Standard # dom-context-2d-save-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.restore()`


CanvasRenderingContext2D: fillRect() method - Web APIs

CanvasRenderingContext2D: fillRect() method
===========================================

 The
 **`CanvasRenderingContext2D.fillRect()`**
 method of the Canvas 2D API draws a rectangle that is filled according to the current
 `fillStyle`.

 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.

Syntax
------

```js
fillRect(x, y, width, height)
```

 The `fillRect()` method draws a filled rectangle whose starting point is at
 `(x, y)` and whose size is specified by `width` and
 `height`. The fill style is determined by the current `fillStyle`
 attribute.

### Parameters

`x`

The x-axis coordinate of the rectangle's starting point.

`y`

The y-axis coordinate of the rectangle's starting point.

`width`

The rectangle's width. Positive values are to the right, and negative to the left.

`height`

The rectangle's height. Positive values are down, and negative are up.

### Return value

None (`undefined`).

Examples
--------

### A simple filled rectangle

This example draws a filled green rectangle using the `fillRect()` method.

#### HTML

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

#### JavaScript

 The rectangle's top-left corner is at (20, 10). It has a width of 150 and a height of
 100.

```js
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
ctx.fillStyle = "green";
ctx.fillRect(20, 10, 150, 100);
```

#### Result

### Filling the whole canvas

 This code snippet fills the entire canvas with a rectangle. This is often useful for
 creating a background, on top of which other things may then be drawn. To achieve this,
 the dimensions of the rectangle are set to equal the `<canvas>` element's
 `width` and `height` attributes.

```js
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
ctx.fillRect(0, 0, canvas.width, canvas.height);
```

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

| Specification |
| --- |
| HTML Standard # dom-context-2d-fillrect-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.fillStyle`
* `CanvasRenderingContext2D.clearRect()`
* `CanvasRenderingContext2D.strokeRect()`


CanvasRenderingContext2D: wordSpacing property - Web APIs

CanvasRenderingContext2D: wordSpacing property
==============================================

The **`CanvasRenderingContext2D.wordSpacing`** property of the Canvas API specifies the spacing between words when drawing text.

This corresponds to the CSS `word-spacing` property.

Value
-----

 The word spacing as a string in the CSS `<length>` data format.
 The default is `0px`.

 The property can be used to get or set the spacing.
 The property value will remain unchanged if set to an invalid/unparsable value.

Examples
--------

 In this example we display the text "Hello World" three times, using the `wordSpacing` property to modify the spacing in each case.
 The spacing is also displayed for each case, using the value of the property.

### HTML

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

### JavaScript

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

ctx.font = "30px serif";

// Default word spacing
ctx.fillText(`Hello world (default: ${ctx.wordSpacing})`, 10, 40);

// Custom word spacing: 10px
ctx.wordSpacing = "10px";
ctx.fillText(`Hello world (${ctx.wordSpacing})`, 10, 90);

// Custom word spacing: 30px
ctx.wordSpacing = "30px";
ctx.fillText(`Hello world (${ctx.wordSpacing})`, 10, 140);
```

### Result

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

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

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

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

See also
--------

* `CanvasRenderingContext2D.letterSpacing`


CanvasRenderingContext2D: shadowBlur property - Web APIs

CanvasRenderingContext2D: shadowBlur property
=============================================

 The
 **`CanvasRenderingContext2D.shadowBlur`**
 property of the Canvas 2D API specifies the amount of blur applied to shadows. The
 default is `0` (no blur).

**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 non-negative float specifying the level of shadow blur, where `0` represents no blur and larger numbers represent increasingly more blur. This value doesn't correspond to a number of pixels, and is not affected by the current transformation matrix. The default value is `0`. Negative, `Infinity`, and `NaN` values are ignored.

Examples
--------

### Adding a shadow to a shape

 This example adds a blurred shadow to a rectangle. The `shadowColor`
 property sets its color, and `shadowBlur` sets its level of blurriness.

#### HTML

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

#### JavaScript

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

// Shadow
ctx.shadowColor = "red";
ctx.shadowBlur = 15;

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

#### Result

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

| Specification |
| --- |
| HTML Standard # dom-context-2d-shadowblur-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, the non-standard and deprecated method
 `ctx.setShadow()` is implemented besides this property.

```js
setShadow(width, height, blur, color, alpha);
setShadow(width, height, blur, graylevel, alpha);
setShadow(width, height, blur, r, g, b, a);
setShadow(width, height, blur, c, m, y, k, a);
```

See also
--------

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


CanvasRenderingContext2D: lineWidth property - Web APIs

CanvasRenderingContext2D: lineWidth property
============================================

 The
 **`CanvasRenderingContext2D.lineWidth`**
 property of the Canvas 2D API sets the thickness of lines.

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

Value
-----

A number specifying the line width, in coordinate space units. Zero, negative, `Infinity`, and `NaN` values are ignored. This value is `1.0` by default.

Examples
--------

### Changing line width

This example draws a line and a rectangle, using a line width of 15 units.

#### HTML

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

#### JavaScript

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

ctx.lineWidth = 15;

ctx.beginPath();
ctx.moveTo(20, 20);
ctx.lineTo(130, 130);
ctx.rect(40, 40, 70, 70);
ctx.stroke();
```

#### Result

### More examples

For more examples and explanation about this property, see Applying styles and color in the Canvas Tutorial.

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

| Specification |
| --- |
| HTML Standard # dom-context-2d-linewidth-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.lineCap`
* `CanvasRenderingContext2D.lineJoin`
* Applying styles and color


CanvasRenderingContext2D: imageSmoothingEnabled property - Web APIs

CanvasRenderingContext2D: imageSmoothingEnabled property
========================================================

 The **`imageSmoothingEnabled`** property of the
 `CanvasRenderingContext2D` interface, part of the Canvas API, determines whether scaled images
 are smoothed (`true`, default) or not (`false`). On getting the
 `imageSmoothingEnabled` property, the last value it was set to is returned.

 This property is useful for games and other apps that use pixel art. When enlarging
 images, the default resizing algorithm will blur the pixels. Set this property to
 `false` to retain the pixels' sharpness.

**Note:** You can adjust the smoothing quality with the
 `imageSmoothingQuality`
 property.

Value
-----

A boolean value indicating whether to smooth scaled images or not. The default value is `true`.

Examples
--------

### Disabling image smoothing

 This example compares three images. The first image is drawn at its natural size, the
 second is scaled to 3X and drawn with image smoothing enabled, and the third is scaled
 to 3X but drawn with image smoothing disabled.

#### HTML

```html
<canvas id="canvas" width="460" height="210"></canvas>
```

#### JavaScript

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

const ctx = canvas.getContext("2d");
ctx.font = "16px sans-serif";
ctx.textAlign = "center";

const img = new Image();
img.src =
  "https://interactive-examples.mdn.mozilla.net/media/examples/star.png";
img.onload = () => {
  const w = img.width,
    h = img.height;

  ctx.fillText("Source", w \* 0.5, 20);
  ctx.drawImage(img, 0, 24, w, h);

  ctx.fillText("Smoothing = TRUE", w \* 2.5, 20);
  ctx.imageSmoothingEnabled = true;
  ctx.drawImage(img, w, 24, w \* 3, h \* 3);

  ctx.fillText("Smoothing = FALSE", w \* 5.5, 20);
  ctx.imageSmoothingEnabled = false;
  ctx.drawImage(img, w \* 4, 24, w \* 3, h \* 3);
};
```

#### Result

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

| Specification |
| --- |
| HTML Standard # dom-context-2d-imagesmoothingenabled-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.imageSmoothingQuality`
* `image-rendering`


CanvasRenderingContext2D: setTransform() method - Web APIs

CanvasRenderingContext2D: setTransform() method
===============================================

 The
 **`CanvasRenderingContext2D.setTransform()`**
 method of the Canvas 2D API resets (overrides) the current transformation to the
 identity matrix, and then invokes a transformation described by the arguments of this
 method. This lets you scale, rotate, translate (move), and skew the context.

**Note:** See also the `transform()` method; instead of overriding the current transform matrix, it
 multiplies it with a given one.

Syntax
------

```js
setTransform(a, b, c, d, e, f)
setTransform(matrix)
```

The transformation matrix is described by:

[

a

c

e

b

d

f

0

0

1

]

 \left[ \begin{array}{ccc} a & c & e \ b & d
 & f \ 0 & 0 & 1 \end{array} \right]

This transformation matrix gets multiplied on the left of a column vector representing each point being drawn on the canvas, to produce the final coordinate used on the canvas.

### Parameters

`setTransform()` has two types of parameter that it can accept. The older
 type consists of several parameters representing the individual components of the
 transformation matrix to set:

`a` (`m11`)

The cell in the first row and first column of the matrix.

`b` (`m12`)

The cell in the second row and first column of the matrix.

`c` (`m21`)

The cell in the first row and second column of the matrix.

`d` (`m22`)

The cell in the second row and second column of the matrix.

`e` (`m41`)

The cell in the first row and third column of the matrix.

`f` (`m42`)

The cell in the second row and third column of the matrix.

Alternatively, you can pass a single parameter which is an object containing the values above as properties. The parameter names are the property keys, and if two synonymous names are both present (e.g. `m11` and `a`), they must be the same number value, or a `TypeError` will be thrown. Using the object form allows omitting some parameters — `a` and `d` default to `1`, while the rest default to `0`.

If a point originally had coordinates

(
x
,
y
)

(x, y)

, then after the transformation it will have coordinates

(
a
x
+
c
y
+
e
,
b
x
+
d
y
+
f
)

(ax + cy + e, bx + dy + f)

. This means:

* `e` and `f` control the horizontal and vertical translation of the context.
* When `b` and `c` are `0`, `a` and `d` control the horizontal and vertical scaling of the context.
* When `a` and `d` are `1`, `b` and `c` control the horizontal and vertical skewing of the context.
### Return value

None (`undefined`).

Examples
--------

### Skewing a shape

 This example skews a rectangle both vertically (`.2`) and horizontally
 (`.8`). Scaling and translation remain unchanged.

#### HTML

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

#### JavaScript

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

ctx.setTransform(1, 0.2, 0.8, 1, 0, 0);
ctx.fillRect(0, 0, 100, 100);
```

#### Result

### Retrieving and passing a DOMMatrix object

 In the following example, we have two `<canvas>` elements. We apply a
 transform to the first one's context using the first type of `setTransform()`
 and draw a square on it, then retrieve the matrix from it using
 `CanvasRenderingContext2D.getTransform()`.

 We then apply the retrieved matrix directly to the second canvas context by passing the
 `DOMMatrix` object directly to `setTransform()` (i.e. the second
 type), and draw a circle on it.

#### HTML

```html
<!-- First canvas (ctx1) -->
<canvas width="240"></canvas>
<!-- Second canvas (ctx2) -->
<canvas width="240"></canvas>
```

#### CSS

```css
canvas {
  border: 1px solid black;
}
```

#### JavaScript

```js
const canvases = document.querySelectorAll("canvas");
const ctx1 = canvases[0].getContext("2d");
const ctx2 = canvases[1].getContext("2d");

ctx1.setTransform(1, 0.2, 0.8, 1, 0, 0);
ctx1.fillRect(25, 25, 50, 50);

let storedTransform = ctx1.getTransform();
console.log(storedTransform);

ctx2.setTransform(storedTransform);
ctx2.beginPath();
ctx2.arc(50, 50, 50, 0, 2 \* Math.PI);
ctx2.fill();
```

#### Result

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

| Specification |
| --- |
| HTML Standard # dom-context-2d-settransform-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.transform()`


CanvasRenderingContext2D: fill() method - Web APIs

CanvasRenderingContext2D: fill() method
=======================================

 The
 **`CanvasRenderingContext2D.fill()`**
 method of the Canvas 2D API fills the current or given path with the current
 `fillStyle`.

Syntax
------

```js
fill()
fill(path)
fill(fillRule)
fill(path, fillRule)
```

### Parameters

`fillRule`

 The algorithm by which to determine if a point is inside or outside the filling
 region.
 Possible values:

`nonzero`

 The non-zero winding rule.
 Default rule.

`evenodd`

The even-odd winding rule.

`path`

A `Path2D` path to fill.

### Return value

None (`undefined`).

Examples
--------

### Filling a rectangle

This example fills a rectangle with the `fill()` method.

#### 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.fill();
```

#### Result

### Specifying a path and a fillRule

 This example saves some intersecting lines to a Path2D object. The `fill()`
 method is then used to render the object to the canvas. A hole is left unfilled in the
 object's center by using the `"evenodd"` rule; by default (with the
 `"nonzero"` rule), the hole would also be filled.

#### HTML

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

#### JavaScript

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

// Create path
let region = new Path2D();
region.moveTo(30, 90);
region.lineTo(110, 20);
region.lineTo(240, 130);
region.lineTo(60, 130);
region.lineTo(190, 20);
region.lineTo(270, 90);
region.closePath();

// Fill path
ctx.fillStyle = "green";
ctx.fill(region, "evenodd");
```

#### Result

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

| Specification |
| --- |
| HTML Standard # dom-context-2d-fill-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.fillStyle`


CanvasRenderingContext2D: strokeStyle property - Web APIs

CanvasRenderingContext2D: strokeStyle property
==============================================

 The **`CanvasRenderingContext2D.strokeStyle`** property of the
 Canvas 2D API specifies the color, gradient, or pattern to use for the strokes
 (outlines) around shapes. The default is `#000` (black).

**Note:** For more examples of stroke and fill styles, see Applying styles and color in the Canvas tutorial.

Value
-----

One of the following:

`color`

 A string parsed as CSS
`<color>` value.

`gradient`

A `CanvasGradient` object (a linear or radial gradient).

`pattern`

A `CanvasPattern` object (a repeating image).

Examples
--------

### Changing the stroke color of a shape

This example applies a blue stroke color to a rectangle.

#### HTML

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

#### JavaScript

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

ctx.strokeStyle = "blue";
ctx.strokeRect(10, 10, 100, 100);
```

#### Result

### Creating multiple stroke colors using loops

 In this example, we use two `for` loops and the
 `arc()` method to draw a grid of circles,
 each having a different stroke color. To achieve this, we use the two variables
 `i` and `j` to generate a unique RGB color for each circle, and
 only modify the green and blue values. (The red channel has a fixed value.)
```

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

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

for (let i = 0; i < 6; i++) {
  for (let j = 0; j < 6; j++) {
    ctx.strokeStyle = `rgb(
 0
 ${Math.floor(255 - 42.5 \* i)}
 ${Math.floor(255 - 42.5 \* j)})`;
    ctx.beginPath();
    ctx.arc(12.5 + j \* 25, 12.5 + i \* 25, 10, 0, Math.PI \* 2, true);
    ctx.stroke();
  }
}
```

The result looks like this:

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

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

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

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

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

### WebKit/Blink-specific note

 In WebKit- and Blink-based browsers, the non-standard and deprecated method
 `ctx.setStrokeColor()` is implemented in addition to this property.

```js
setStrokeColor(color);
setStrokeColor(color, alpha);
setStrokeColor(grayLevel);
setStrokeColor(grayLevel, alpha);
setStrokeColor(r, g, b, a);
setStrokeColor(c, m, y, k, a);
```

See also
--------

* The interface defining this property: `CanvasRenderingContext2D`
* `CanvasGradient`
* `CanvasPattern`


CanvasRenderingContext2D: textRendering property - Web APIs

CanvasRenderingContext2D: textRendering property
================================================

The **`CanvasRenderingContext2D.textRendering`** property of the Canvas API provides information to the rendering engine about what to optimize for when rendering text.

The values correspond to the SVG `text-rendering` attribute (and CSS `text-rendering` property).

Value
-----

 A text-rendering hint to the browser engine.
 This one of:

`auto`

The browser makes educated guesses about when to optimize for speed, legibility, and geometric precision while drawing text.

`optimizeSpeed`

 The browser emphasizes rendering speed over legibility and geometric precision when drawing text.
 It disables kerning and ligatures.

`optimizeLegibility`

 The browser emphasizes legibility over rendering speed and geometric precision.
 This enables kerning and optional ligatures.

`geometricPrecision`

 The browser emphasizes geometric precision over rendering speed and legibility.
 Certain aspects of fonts — such as kerning — don't scale linearly.
 For large scale factors, you might see less-than-beautiful text rendering, but the size is what you would expect (neither rounded up nor down to the nearest font size supported by the underlying operating system).

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

Examples
--------

 In this example we display the text "Hello World" using each of the supported values of the `textRendering` 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 (auto)
ctx.fillText(`Hello world (default: ${ctx.textRendering})`, 5, 20);

// Text rendering: optimizeSpeed
ctx.textRendering = "optimizeSpeed";
ctx.fillText(`Hello world (${ctx.textRendering})`, 5, 50);

// Text rendering: optimizeLegibility
ctx.textRendering = "optimizeLegibility";
ctx.fillText(`Hello world (${ctx.textRendering})`, 5, 80);

// Text rendering: geometricPrecision
ctx.textRendering = "geometricPrecision";
ctx.fillText(`Hello world (${ctx.textRendering})`, 5, 110);
```

### Result

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

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

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

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


CanvasRenderingContext2D: isPointInPath() method - Web APIs

CanvasRenderingContext2D: isPointInPath() method
================================================

 The
 **`CanvasRenderingContext2D.isPointInPath()`**
 method of the Canvas 2D API reports whether or not the specified point is contained in
 the current path.

Syntax
------

```js
isPointInPath(x, y)
isPointInPath(x, y, fillRule)
isPointInPath(path, x, y)
isPointInPath(path, x, y, fillRule)
```

### Parameters

`x`

 The x-axis coordinate of the point to check, unaffected by the current
 transformation of the context.

`y`

 The y-axis coordinate of the point to check, unaffected by the current
 transformation of the context.

`fillRule`

 The algorithm by which to determine if a point is inside or outside the path.
 Possible values:

`nonzero`

 The non-zero winding rule.
 Default rule.

`evenodd`

The even-odd winding rule.

`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 specified point is contained in the
 current or specified path, otherwise `false`.

Examples
--------

### Checking a point in the current path

 This example uses the `isPointInPath()` method to check if a point is within
 the current path.

#### HTML

```html
<canvas id="canvas"></canvas>
<p>In path: <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.fill();
result.innerText = ctx.isPointInPath(30, 70);
```

#### Result

### Checking a point in the specified path

 Whenever you move the mouse, this example checks whether the cursor is in a circular
 `Path2D` path. If yes, the circle 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 circle
const circle = new Path2D();
circle.arc(150, 75, 50, 0, 2 \* Math.PI);
ctx.fillStyle = "red";
ctx.fill(circle);

// Listen for mouse moves
canvas.addEventListener("mousemove", (event) => {
  // Check whether point is inside circle
  const isPointInPath = ctx.isPointInPath(circle, event.offsetX, event.offsetY);
  ctx.fillStyle = isPointInPath ? "green" : "red";

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

#### Result

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

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

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

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

### Gecko-specific note

* Prior to Gecko 7.0 (Firefox 7.0 / Thunderbird 7.0 / SeaMonkey 2.4), this method
 incorrectly failed to multiply the specified point's coordinates by the current
 transformation matrix before comparing it to the path. Now this method works correctly
 even if the context is rotated, scaled, or otherwise transformed.
See also
--------

* The interface defining this method: `CanvasRenderingContext2D`


CanvasRenderingContext2D: strokeText() method - Web APIs

CanvasRenderingContext2D: strokeText() method
=============================================

 The `CanvasRenderingContext2D` method
 **`strokeText()`**, part of the Canvas 2D API, strokes — that
 is, draws the outlines of — the characters of a text string at the specified
 coordinates. 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.

**Note:** Use the `fillText()` method to
 fill the text characters rather than having just their outlines drawn.

Syntax
------

```js
strokeText(text, x, y)
strokeText(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.

`y`

The y-axis coordinate of the point at which to begin drawing the text.

`maxWidth` Optional

 The maximum width 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 text outlines

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

#### HTML

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

```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.strokeText("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 `strokeText()` 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.strokeText("Hello world", 50, 90, 140);
```

#### Result

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

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

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

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

See also
--------

* Drawing text
* The interface defining this method: `CanvasRenderingContext2D`
* `CanvasRenderingContext2D.fillText()`


CanvasRenderingContext2D: moveTo() method - Web APIs

CanvasRenderingContext2D: moveTo() method
=========================================

 The
 **`CanvasRenderingContext2D.moveTo()`**
 method of the Canvas 2D API begins a new sub-path at the point specified by the given
 `(x, y)` coordinates.

Syntax
------

```js
moveTo(x, y)
```

### Parameters

`x`

The x-axis (horizontal) coordinate of the point.

`y`

The y-axis (vertical) coordinate of the point.

### Return value

None (`undefined`).

Examples
--------

### Creating multiple sub-paths

 This example uses `moveTo()` to create two sub-paths within a single path.
 Both sub-paths are then rendered with a single `stroke()` call.

#### HTML

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

#### JavaScript

 The first line begins at (50, 50) and ends at (200, 50). The second line begins at (50,
 90) and ends at (280, 120).

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

ctx.beginPath();
ctx.moveTo(50, 50); // Begin first sub-path
ctx.lineTo(200, 50);
ctx.moveTo(50, 90); // Begin second sub-path
ctx.lineTo(280, 120);
ctx.stroke();
```

#### Result

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

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


CanvasRenderingContext2D: fillStyle property - Web APIs

CanvasRenderingContext2D: fillStyle property
============================================

 The
 **`CanvasRenderingContext2D.fillStyle`**
 property of the Canvas 2D API specifies the
 color, gradient, or pattern to use inside shapes. The default style is `#000`
 (black).

**Note:** For more examples of fill and stroke styles, see Applying styles and color in the Canvas tutorial.

Value
-----

One of the following:

* A string parsed as CSS `<color>` value.
* A `CanvasGradient` object (a linear or radial gradient).
* A `CanvasPattern` object (a repeating image).
Examples
--------

### Changing the fill color of a shape

This example applies a blue fill color to a rectangle.

#### HTML

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

#### JavaScript

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

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

#### Result

### Creating multiple fill colors using loops

 In this example, we use two `for` loops to draw a grid of rectangles, each
 having a different fill color. To achieve this, we use the two variables `i`
 and `j` to generate a unique RGB color for each square, and only modify the
 red and green values. (The blue channel has a fixed value.) By modifying the channels,
 you can generate all kinds of palettes.
```

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

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

for (let i = 0; i < 6; i++) {
  for (let j = 0; j < 6; j++) {
    ctx.fillStyle = `rgb(
 ${Math.floor(255 - 42.5 \* i)}
 ${Math.floor(255 - 42.5 \* j)}
 0)`;
    ctx.fillRect(j \* 25, i \* 25, 25, 25);
  }
}
```

The result looks like this:

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

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

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

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

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

### WebKit/Blink-specific note

 In WebKit- and Blink-based browsers, the non-standard and deprecated method
 `ctx.setFillColor()` is implemented in addition to this property.

```js
setFillColor(color, /\* (optional) \*/ alpha);
setFillColor(grayLevel, /\* (optional) \*/ alpha);
setFillColor(r, g, b, a);
setFillColor(c, m, y, k, a);
```

See also
--------

* Canvas API
* The interface defining this property: `CanvasRenderingContext2D`
* Values used by this property:
    + `<color>` CSS data type
    + `CanvasGradient` object
    + `CanvasPattern` object


CanvasRenderingContext2D: fontStretch property - Web APIs

CanvasRenderingContext2D: fontStretch property
==============================================

The **`CanvasRenderingContext2D.fontStretch`** property of the Canvas API specifies how the font may be expanded or condensed when drawing text.

The property corresponds to the `font-stretch` CSS property when used with keywords (percentage values are not supported).

Value
-----

 The font stretch value as a string.
 This is one of: `ultra-condensed`, `extra-condensed`, `condensed`, `semi-condensed`, `normal` (default), `semi-expanded`, `expanded`, `extra-expanded`, `ultra-expanded`.

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

Examples
--------

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

### HTML

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

### JavaScript

First we get the canvas declared in the HTML file and use it to get the `CanvasRenderingContext2D` that will later be used for drawing text.

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

 The next step in the example is to load a variable font that can be varied in the width axis.
 This is needed because `fontStretch` can only stretch a font that contains information about how glyphs are drawn when stretched — otherwise text will be drawn using the closest available font stretch value for the font, which will often be the normal width.

 In this case we use `FontFace` to define a font face for the Inconsolata Google Font, which supports font widths from 50% to 200% (allowing us to demonstrate `fontStretch` values from `ultra-condensed` to `ultra-expanded`).
 We then add this to the document's `FontFaceSet` (`document.fonts`) so that it can be used for drawing.

```js
const fontFile = new FontFace(
  "Inconsolata",
  'url(https://fonts.gstatic.com/s/inconsolata/v31/QlddNThLqRwH-OJ1UHjlKENVzlm-WkL3GZQmAwPyya15.woff2) format("woff2")',
  { stretch: "50% 200%" },
);

document.fonts.add(fontFile);
```

 The code below then calls `FontFaceSet.load()` to fetch and load the Google Font.
 Note that this call sets the size of the font that is needed, and returns a promise that resolves when the font has been loaded.

 We then assign the font face we downloaded to the context, and use the context to draw text to the canvas at each of the keyword stretch levels.
 Note that again the size of the desired font is specified (this does not have to match the loaded font size).

```js
document.fonts.load("30px Inconsolata").then(
  () => {
    ctx.font = "30px 'Inconsolata'";
    // Default (normal)
    ctx.fillText(`Hello world (default: ${ctx.fontStretch})`, 5, 20);

    ctx.fontStretch = "ultra-condensed";
    ctx.fillText(`Hello world (${ctx.fontStretch})`, 5, 50);

    ctx.fontStretch = "extra-condensed";
    ctx.fillText(`Hello world (${ctx.fontStretch})`, 5, 80);

    ctx.fontStretch = "condensed";
    ctx.fillText(`Hello world (${ctx.fontStretch})`, 5, 110);

    ctx.fontStretch = "semi-condensed";
    ctx.fillText(`Hello world (${ctx.fontStretch})`, 5, 140);

    ctx.fontStretch = "extra-condensed";
    ctx.fillText(`Hello world (${ctx.fontStretch})`, 5, 170);

    ctx.fontStretch = "semi-expanded";
    ctx.fillText(`Hello world (${ctx.fontStretch})`, 5, 200);

    ctx.fontStretch = "expanded";
    ctx.fillText(`Hello world (${ctx.fontStretch})`, 5, 230);

    ctx.fontStretch = "extra-expanded";
    ctx.fillText(`Hello world (${ctx.fontStretch})`, 5, 260);

    ctx.fontStretch = "ultra-expanded";
    ctx.fillText(`Hello world (${ctx.fontStretch})`, 5, 290);
  },
  (err) => {
    console.error(err);
  },
);
```

### Result

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

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

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

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


CanvasRenderingContext2D: closePath() method - Web APIs

CanvasRenderingContext2D: closePath() method
============================================

 The
 **`CanvasRenderingContext2D.closePath()`**
 method of the Canvas 2D API attempts to add a straight line from the current point to
 the start of the current sub-path. If the shape has already been closed or has only one
 point, this function does nothing.

 This method doesn't draw anything to the canvas directly. You can render the path using
 the `stroke()` or
 `fill()` methods.

Syntax
------

```js
closePath()
```

### Parameters

None.

### Return value

None (`undefined`).

Examples
--------

### Closing a triangle

 This example creates the first two (diagonal) sides of a triangle using the
 `lineTo()` method. After that, the triangle's base is created with the
 `closePath()` method, which automatically connects the shape's first and last
 points.

#### HTML

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

#### JavaScript

The triangle's corners are at (20, 140), (120, 10), and (220, 140).

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

ctx.beginPath();
ctx.moveTo(20, 140); // Move pen to bottom-left corner
ctx.lineTo(120, 10); // Line to top corner
ctx.lineTo(220, 140); // Line to bottom-right corner
ctx.closePath(); // Line to bottom-left corner
ctx.stroke();
```

#### Result

### Closing just one sub-path

This example draws a smiley face consisting of three disconnected sub-paths.

**Note:** Although `closePath()` is called after all the arcs have been
 created, only the last arc (sub-path) gets closed.

#### HTML

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

#### JavaScript

The first two arcs create the face's eyes. The last arc creates the mouth.

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

ctx.beginPath();
ctx.arc(240, 20, 40, 0, Math.PI);
ctx.moveTo(100, 20);
ctx.arc(60, 20, 40, 0, Math.PI);
ctx.moveTo(215, 80);
ctx.arc(150, 80, 65, 0, Math.PI);
ctx.closePath();
ctx.lineWidth = 6;
ctx.stroke();
```

#### Result

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

| Specification |
| --- |
| HTML Standard # dom-context-2d-closepath-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.beginPath()`


CanvasRenderingContext2D: scale() method - Web APIs

CanvasRenderingContext2D: scale() method
========================================

 The
 **`CanvasRenderingContext2D.scale()`**
 method of the Canvas 2D API adds a scaling transformation to the canvas units
 horizontally and/or vertically.

 By default, one unit on the canvas is exactly one pixel. A scaling transformation
 modifies this behavior. For instance, a scaling factor of 0.5 results in a unit size of
 0.5 pixels; shapes are thus drawn at half the normal size. Similarly, a scaling factor
 of 2.0 increases the unit size so that one unit becomes two pixels; shapes are thus
 drawn at twice the normal size.

Syntax
------

```js
scale(x, y)
```

### Parameters

`x`

 Scaling factor in the horizontal direction. A negative value flips pixels across the
 vertical axis. A value of `1` results in no horizontal scaling.

`y`

 Scaling factor in the vertical direction. A negative value flips pixels across the
 horizontal axis. A value of `1` results in no vertical scaling.

### Return value

None (`undefined`).

Examples
--------

### Scaling a shape

 This example draws a scaled rectangle. A non-scaled rectangle is then drawn for
 comparison.

#### HTML

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

#### JavaScript

 The rectangle has a specified width of 8 and a height of 20. The transformation matrix
 scales it by 9x horizontally and by 3x vertically. Thus, its final size is a width of 72
 and a height of 60.

 Notice that its position on the canvas also changes. Since its specified corner is (10,
 10), its rendered corner becomes (90, 30).

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

// Scaled rectangle
ctx.scale(9, 3);
ctx.fillStyle = "red";
ctx.fillRect(10, 10, 8, 20);

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

// Non-scaled rectangle
ctx.fillStyle = "gray";
ctx.fillRect(10, 10, 8, 20);
```

#### Result

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

### Flipping things horizontally or vertically

 You can use `scale(-1, 1)` to flip the context horizontally and
 `scale(1, -1)` to flip it vertically. In this example, the words "Hello
 world!" are flipped horizontally.

 Note that the call to `fillText()`
 specifies a negative x coordinate. This is to adjust for the negative scaling factor:
 `-280 * -1` becomes `280`, and text is drawn leftwards from that
 point.

#### HTML

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

#### JavaScript

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

ctx.scale(-1, 1);
ctx.font = "48px serif";
ctx.fillText("Hello world!", -280, 90);
ctx.setTransform(1, 0, 0, 1, 0, 0);
```

#### Result

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

| Specification |
| --- |
| HTML Standard # dom-context-2d-scale-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: roundRect() method - Web APIs

CanvasRenderingContext2D: roundRect() method
============================================

The **`CanvasRenderingContext2D.roundRect()`** method of the Canvas 2D API adds a rounded rectangle to the current path.

The radii of the corners can be specified in much the same way as the CSS `border-radius` property.

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

Syntax
------

```js
roundRect(x, y, width, height, radii)
```

### Parameters

`x`

The x-axis coordinate of the rectangle's starting point, in pixels.

`y`

The y-axis coordinate of the rectangle's starting point, in pixels.

`width`

The rectangle's width. Positive values are to the right, and negative to the left.

`height`

The rectangle's height. Positive values are down, and negative are up.

`radii`

 A number or list specifying the radii of the circular arc to be used for the corners of the rectangle.
 The number and order of the radii function in the same way as the `border-radius` CSS property when `width` and `height` are *positive*:

* `all-corners`
* `[all-corners]`
* `[top-left-and-bottom-right, top-right-and-bottom-left]`
* `[top-left, top-right-and-bottom-left, bottom-right]`
* `[top-left, top-right, bottom-right, bottom-left]`

 If `width` is *negative* the rounded rectangle is flipped horizontally, so the radius values that normally apply to the left corners are used on the right and vice versa.
 Similarly, when `height` is negative, the rounded rect is flipped vertically.
 The specified radii may be scaled (reduced) if any of the edges are shorter than the combined radius of the vertices on either end.

The `radii` parameter can also be a `DOMPoint` or `DOMPointReadOnly` instance, or an object containing the same properties (`{x: 0, y: 0}`), or a list of such objects, or a list mixing numbers and such objects.

### Return value

None (`undefined`).

### Exceptions

`RangeError`

If `radii` is a list that has zero or more than four elements, or if one of its values is a negative number.

Examples
--------

### Drawing rectangles

 This example creates a number of rounded rectangular paths using the `roundRect()` method.
 The paths are then rendered using the `stroke()` method.

#### HTML

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

#### JavaScript

First we create a context for drawing our rounded rectangles.

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

 The code below draws two rectangles, both starting from the point (10, 20) and with a width of 150 and a height of 100.
 The first rectangle is drawn in red and specifies a zero radius for all the corners using a number as an argument.
 The second is drawn in blue, and specifies a 40px radius as a single element in a list.

```js
// Rounded rectangle with zero radius (specified as a number)
ctx.strokeStyle = "red";
ctx.beginPath();
ctx.roundRect(10, 20, 150, 100, 0);
ctx.stroke();

// Rounded rectangle with 40px radius (single element list)
ctx.strokeStyle = "blue";
ctx.beginPath();
ctx.roundRect(10, 20, 150, 100, [40]);
ctx.stroke();
```

Below the previous rectangle we draw another in orange that specifies the values of the radii of opposite corners.

```js
// Rounded rectangle with 2 different radii
ctx.strokeStyle = "orange";
ctx.beginPath();
ctx.roundRect(10, 150, 150, 100, [10, 40]);
ctx.stroke();
```

 Finally, we draw two rounded rectangles that have four values for the radii and the same starting point.
 The difference here is that the second is drawn with a negative width.

```js
// Rounded rectangle with four different radii
ctx.strokeStyle = "green";
ctx.beginPath();
ctx.roundRect(400, 20, 200, 100, [0, 30, 50, 60]);
ctx.stroke();

// Same rectangle drawn backwards
ctx.strokeStyle = "magenta";
ctx.beginPath();
ctx.roundRect(400, 150, -200, 100, [0, 30, 50, 60]);
ctx.stroke();
```

#### Result

 The result is shown below.
 For the two rectangles on the right, note how the bottom rectangle is drawn with a negative width, and how this flips the rectangle horizontally.

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

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

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.rect()`
* `CanvasRenderingContext2D.fillRect`
* `CanvasRenderingContext2D.strokeRect()`
* `CanvasRenderingContext2D.fill()`
* `CanvasRenderingContext2D.stroke()`


CanvasRenderingContext2D: translate() method - Web APIs

CanvasRenderingContext2D: translate() method
============================================

 The
 **`CanvasRenderingContext2D.translate()`**
 method of the Canvas 2D API adds a translation transformation to the current matrix.

Syntax
------

```js
translate(x, y)
```

 The `translate()` method adds a translation transformation to the current
 matrix by moving the canvas and its origin `x` units horizontally and
 `y` units vertically on the grid.

![A canvas's origin moved on the x and y axes based on the values of the translate method.](/en-US/docs/Web/API/CanvasRenderingContext2D/translate/canvas_grid_translate.png)

### Parameters

`x`

 Distance to move in the horizontal direction. Positive values are to the right, and
 negative to the left.

`y`

 Distance to move in the vertical direction. Positive values are down, and negative
 are up.

### Return value

None (`undefined`).

Examples
--------

### Moving a shape

 This example draws a square that is moved from its default position by the
 `translate()` method. An unmoved square of the same size is then drawn for
 comparison.

#### HTML

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

#### JavaScript

 The `translate()` method translates the context by 110 horizontally and 30
 vertically. The first square is shifted by those amounts from its default position.

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

// Moved square
ctx.translate(110, 30);
ctx.fillStyle = "red";
ctx.fillRect(0, 0, 80, 80);

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

// Unmoved square
ctx.fillStyle = "gray";
ctx.fillRect(0, 0, 80, 80);
```

#### Result

The moved square is red, and the unmoved square is gray.

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

| Specification |
| --- |
| HTML Standard # dom-context-2d-translate-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: miterLimit property - Web APIs

CanvasRenderingContext2D: miterLimit property
=============================================

 The **`CanvasRenderingContext2D.miterLimit`** property of the
 Canvas 2D API sets the miter limit ratio.

**Note:** For more info about miters, see Applying styles and color in the Canvas tutorial.

Value
-----

A number specifying the miter limit ratio, in coordinate space units. Zero, negative, `Infinity`, and `NaN` values are ignored. The default value is `10.0`.

Examples
--------

### Using the `miterLimit` property

See the chapter Applying styles and color in the Canvas tutorial for more information.

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

| Specification |
| --- |
| HTML Standard # dom-context-2d-miterlimit-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.lineCap`
* `CanvasRenderingContext2D.lineJoin`


CanvasRenderingContext2D: shadowOffsetX property - Web APIs

CanvasRenderingContext2D: shadowOffsetX property
================================================

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

**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 horizontally. Positive values are to the right, and negative to the left. The default value is `0` (no horizontal offset). `Infinity` and `NaN` values are ignored.

Examples
--------

### Moving a shadow horizontally

 This example adds a blurred shadow to a rectangle. The
 `shadowColor` property sets its
 color, `shadowOffsetX` sets its offset 25 units to the right, 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.shadowOffsetX = 25;
ctx.shadowBlur = 10;

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

#### Result

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

| Specification |
| --- |
| HTML Standard # dom-context-2d-shadowoffsetx-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.shadowOffsetY`
* `CanvasRenderingContext2D.shadowColor`
* `CanvasRenderingContext2D.shadowBlur`


CanvasRenderingContext2D: clip() method - Web APIs

CanvasRenderingContext2D: clip() method
=======================================

 The
 **`CanvasRenderingContext2D.clip()`**
 method of the Canvas 2D API turns the current or given path into the current clipping
 region. The previous clipping region, if any, is intersected with the current or given
 path to create the new clipping region.

 In the image below, the red outline represents a clipping region shaped like a star.
 Only those parts of the checkerboard pattern that are within the clipping region get
 drawn.

![Star-shaped clipping region](/en-US/docs/Web/API/CanvasRenderingContext2D/clip/canvas_clipping_path.png)

**Note:** Be aware that the clipping region is only constructed from
 shapes added to the path. It doesn't work with shape primitives drawn directly to the
 canvas, such as `fillRect()`.
 Instead, you'd have to use `rect()` to
 add a rectangular shape to the path before calling `clip()`.

**Note:** Clip paths cannot be reverted directly. You must save your canvas state using `save()` before calling `clip()`, and restore it once you have finished drawing in the clipped area using `restore()`.

Syntax
------

```js
clip()
clip(path)
clip(fillRule)
clip(path, fillRule)
```

### Parameters

`fillRule`

 The algorithm by which to determine if a point is inside or outside the clipping
 region. Possible values:

`nonzero`

 The non-zero winding rule.
 Default rule.

`evenodd`

The even-odd winding rule.

`path`

A `Path2D` path to use as the clipping region.

### Return value

None (`undefined`).

Examples
--------

### A simple clipping region

 This example uses the `clip()` method to create a clipping region according
 to the shape of a circular arc. Two rectangles are then drawn; only those parts within
 the clipping region are rendered.

#### HTML

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

#### JavaScript

The clipping region is a full circle, with its center at (100, 75), and a radius of 50.

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

// Create circular clipping region
ctx.beginPath();
ctx.arc(100, 75, 50, 0, Math.PI \* 2);
ctx.clip();

// Draw stuff that gets clipped
ctx.fillStyle = "blue";
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "orange";
ctx.fillRect(0, 0, 100, 100);
```

#### Result

### Specifying a path and a fillRule

 This example saves two rectangles to a Path2D object, which is then made the current
 clipping region using the `clip()` method. The `"evenodd"` rule
 creates a hole where the clipping rectangles intersect; by default (with the
 `"nonzero"` rule), there would be no hole.

#### HTML

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

#### JavaScript

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

// Create clipping path
let region = new Path2D();
region.rect(80, 10, 20, 130);
region.rect(40, 50, 100, 50);
ctx.clip(region, "evenodd");

// Draw stuff that gets clipped
ctx.fillStyle = "blue";
ctx.fillRect(0, 0, canvas.width, canvas.height);
```

#### Result

### Creating a complex clipping region

 This example uses two paths, a rectangle and a square to create a complex clipping
 region. The `clip()` method is called twice, first to set the current
 clipping region to the circle using a `Path2D` object, then again to
 intersect the circle clipping region with a square. The final clipping region is a shape
 representing the intersection of the circle and the square.

#### HTML

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

#### JavaScript

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

// Create two clipping paths
let circlePath = new Path2D();
circlePath.arc(150, 75, 75, 0, 2 \* Math.PI);
let squarePath = new Path2D();
squarePath.rect(85, 10, 130, 130);

// Set the clip to the circle
ctx.clip(circlePath);
// Set the clip to be the intersection of the circle and the square
ctx.clip(squarePath);

// Draw stuff that gets clipped
ctx.fillStyle = "blue";
ctx.fillRect(0, 0, canvas.width, canvas.height);
```

#### Result

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

| Specification |
| --- |
| HTML Standard # dom-context-2d-clip-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: getLineDash() method - Web APIs

CanvasRenderingContext2D: getLineDash() method
==============================================

 The **`getLineDash()`** method of the Canvas 2D API's
 `CanvasRenderingContext2D` interface gets the current line dash pattern.

Syntax
------

```js
getLineDash()
```

### Parameters

None.

### Return value

 An `Array` of numbers that specify distances to alternately draw a line and
 a gap (in coordinate space units). If the number, when setting the elements, is odd, the
 elements of the array get copied and concatenated. For example, setting the line dash to
 `[5, 15, 25]` will result in getting back
 `[5, 15, 25, 5, 15, 25]`.

Examples
--------

### Getting the current line dash setting

This example demonstrates the `getLineDash()` method.

#### HTML

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

#### JavaScript

 As set by `setLineDash()`,
 strokes consist of lines that are 10 units wide, with spaces of 20 units in between each
 line.

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

ctx.setLineDash([10, 20]);
console.log(ctx.getLineDash()); // [10, 20]

// Draw a dashed line
ctx.beginPath();
ctx.moveTo(0, 50);
ctx.lineTo(300, 50);
ctx.stroke();
```

#### Result

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

| Specification |
| --- |
| HTML Standard # dom-context-2d-getlinedash-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.setLineDash()`
* `CanvasRenderingContext2D.lineDashOffset`