recursal/MDN huggingface dataset:
CanvasRenderingContext2D: lineDashOffset property
=================================================

 The
 **`CanvasRenderingContext2D.lineDashOffset`**
 property of the Canvas 2D API sets the line dash offset, or "phase."


**Note:** Lines are drawn by calling the
 `stroke()` method.


Value
-----

A float specifying the amount of the line dash offset. The default value is `0.0`.

Examples
--------

### Offsetting a line dash

 This example draws two dashed lines. The first has no dash offset. The second has a
 dash offset of 4.

#### HTML


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


#### JavaScript


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

ctx.setLineDash([4, 16]);

// Dashed line with no offset
ctx.beginPath();
ctx.moveTo(0, 50);
ctx.lineTo(300, 50);
ctx.stroke();

// Dashed line with offset of 4
ctx.beginPath();
ctx.strokeStyle = "red";
ctx.lineDashOffset = 4;
ctx.moveTo(0, 100);
ctx.lineTo(300, 100);
ctx.stroke();
```


#### Result

The line with a dash offset is drawn in red.

### Marching ants

 The marching ants effect is
 an animation technique often found in selection tools of computer graphics programs. It
 helps the user to distinguish the selection border from the image background by
 animating the border.
```

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



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

function draw() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.setLineDash([4, 2]);
  ctx.lineDashOffset = -offset;
  ctx.strokeRect(10, 10, 100, 100);
}

function march() {
  offset++;
  if (offset > 5) {
    offset = 0;
  }
  draw();
  setTimeout(march, 20);
}

march();
```

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

| Specification |
| --- |
| HTML Standard # dom-context-2d-linedashoffset-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.getLineDash()`
* `CanvasRenderingContext2D.setLineDash()`
* Applying styles and color
CanvasRenderingContext2D: reset() method
========================================

The **`CanvasRenderingContext2D.reset()`** method of the Canvas 2D API resets the rendering context to its default state, allowing it to be reused for drawing something else without having to explicitly reset all the properties.

 Resetting clears the backing buffer, drawing state stack, any defined paths, and styles.
 This includes the current transformation matrix, compositing properties, clipping region, dash list, line styles, text styles, shadows, image smoothing, filters, and so on.

Syntax
------


```js
reset()
```

### Parameters

None.

### Return value

None (`undefined`).

Examples
--------

This example shows how we can use `reset()` to completely clear the context before redrawing.

First we define a button and a canvas.


```css
#toggle-reset {
  display: block;
}
```



```html
<button id="toggle-reset">Toggle</button>
<canvas id="my-house" width="500" height="200"></canvas>
```


 The code first gets a `2d` context for the canvas.
 It then defines functions that can use the context to draw a rectangle and a circle, respectively.


```js
// Get the 2d context
const canvas = document.getElementById("my-house");
const ctx = canvas.getContext("2d");

function drawRect() {
  // Set line width
  ctx.lineWidth = 10;

  // Stroke rect outline
  ctx.strokeRect(50, 50, 150, 100);

  // Create filled text
  ctx.font = "50px serif";
  ctx.fillText("Rect!", 70, 110);
}

function drawCircle() {
  // Set line width
  ctx.lineWidth = 5;

  // Stroke out circle
  ctx.beginPath();
  ctx.arc(300, 100, 50, 0, 2 \* Math.PI);
  ctx.stroke();

  // Create filled text
  ctx.font = "25px sans-serif";
  ctx.fillText("Circle!", 265, 100);
}
```


 We then draw the rectangle using its function.
 The button toggles drawing the circle and rectangle.
 Note how `reset()` is called before drawing to clear the context.


```js
drawRect();

// Toggle between circle and rectangle using button
let toggle = true;
const mybutton = document.getElementById("toggle-reset");

mybutton.addEventListener("click", () => {
  ctx.reset(); // Clear the context!
  if (toggle) {
    drawCircle();
  } else {
    drawRect();
  }
  toggle = !toggle;
});
```


The result looks like this:

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

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

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: getContextAttributes() method
=======================================================

The **`CanvasRenderingContext2D.getContextAttributes()`** method returns an object that contains attributes used by the context.

Note that context attributes may be requested when creating the context with `HTMLCanvasElement.getContext()`, but the attributes that are actually supported and used may differ.

Syntax
------


```js
getContextAttributes()
```

### Parameters

None.

### Return value

 A `CanvasRenderingContext2DSettings` object that contains the actual context parameters.
 It has the following members:

`alpha` Optional

 A Boolean indicating if the canvas contains an alpha channel.
 If `false`, the backdrop is always opaque, which can speed up drawing of transparent content and images.


`colorSpace` Optional

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

* `srgb`: denotes the sRGB color space
* `display-p3`: denotes the display-p3 color space

`desynchronized` Optional

A Boolean indicating the user agent reduced the latency by desynchronizing the canvas paint cycle from the event loop.

`willReadFrequently` Optional

A Boolean indicating whether or not this canvas uses software acceleration (instead of hardware acceleration) to support frequent read-back operations via`getImageData()`.

Examples
--------

This example shows how you can specify context attributes when creating a canvas context, and then call `getContextAttributes()` to read back the actual parameters that the browser used.
```

<pre id="log"></pre>
```


```
const logElement = document.getElementById("log");
function log(text) {
  logElement.innerText += text;
}
```


First we create a context using `HTMLCanvasElement.getContext()`, specifying just one context attribute.


```js
let canvas = document.createElement("canvas");
let ctx = canvas.getContext("2d", { alpha: false });
```


If the `getContextAttributes()` method is supported, we use it to read back the actual attributes used by the browser (including those we explicitly specified):


```js
if (ctx.getContextAttributes) {
  const attributes = ctx.getContextAttributes();
  log(JSON.stringify(attributes));
} else {
  log("CanvasRenderingContext2D.getContextAttributes() is not supported");
}
```


Depending on the attributes supported by the browser, the log below should display a string that looks something like: `{alpha: false, colorSpace: 'srgb', desynchronized: false, willReadFrequently: false}`

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

| Specification |
| --- |
| HTML Standard # 2dcontext:dom-context-2d-canvas-getcontextattributes-2 |

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

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

See also
--------

* `HTMLCanvasElement.getContext()`
* `WebGLRenderingContext.getContextAttributes()`
CanvasRenderingContext2D: setLineDash() method
==============================================

 The **`setLineDash()`** method of the Canvas 2D API's
 `CanvasRenderingContext2D` interface sets the line dash pattern used when
 stroking lines. It uses an array of values that specify alternating lengths of lines
 and gaps which describe the pattern.


**Note:** To return to using solid lines, set the line dash list to an
 empty array.


Syntax
------


```js
setLineDash(segments)
```

### Parameters

`segments`

 An `Array` of numbers that specify distances to alternately draw a
 line and a gap (in coordinate space units). If the number of elements in the array
 is odd, the elements of the array get copied and concatenated. For example,
 `[5, 15, 25]` will become `[5, 15, 25, 5, 15, 25]`. If the
 array is empty, the line dash list is cleared and line strokes return to being
 solid.


### Return value

None (`undefined`).

Examples
--------

### Basic example

 This example uses the `setLineDash()` method to draw a dashed line above a
 solid line.

#### HTML


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


#### JavaScript


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

// Dashed line
ctx.beginPath();
ctx.setLineDash([5, 15]);
ctx.moveTo(0, 50);
ctx.lineTo(300, 50);
ctx.stroke();

// Solid line
ctx.beginPath();
ctx.setLineDash([]);
ctx.moveTo(0, 100);
ctx.lineTo(300, 100);
ctx.stroke();
```


#### Result

### Some common patterns

This example illustrates a variety of common line dash patterns.

#### HTML


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


#### JavaScript

 The `drawDashedLine()` function created below makes the drawing of multiple
 dashed lines simple. It receives a pattern array as its only parameter.


```js
function drawDashedLine(pattern) {
  ctx.beginPath();
  ctx.setLineDash(pattern);
  ctx.moveTo(0, y);
  ctx.lineTo(300, y);
  ctx.stroke();
  y += 20;
}

const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
let y = 15;

drawDashedLine([]);
drawDashedLine([1, 1]);
drawDashedLine([10, 10]);
drawDashedLine([20, 5]);
drawDashedLine([15, 3, 3, 3]);
drawDashedLine([20, 3, 3, 3, 3, 3, 3, 3]);
drawDashedLine([12, 3, 3]); // Equals [12, 3, 3, 12, 3, 3]
```


#### Result

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

| Specification |
| --- |
| HTML Standard # dom-context-2d-setlinedash-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()`
* `CanvasRenderingContext2D.lineDashOffset`
CanvasRenderingContext2D: restore() method
==========================================

 The
 **`CanvasRenderingContext2D.restore()`**
 method of the Canvas 2D API restores the most recently saved canvas state by popping the
 top entry in the drawing state stack. If there is no saved state, this method does
 nothing.

For more information about the drawing state, see `CanvasRenderingContext2D.save()`.

Syntax
------


```js
restore()
```

### Parameters

None.

### Return value

None (`undefined`).

Examples
--------

### Restoring a saved 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-restore-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.save()`
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
==========================================

 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
====================================================

 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
===============================================

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()`