Drawing text - Web APIs

Drawing text
============

* « Previous
* Next »

After having seen how to apply styles and colors in the previous chapter, we will now have a look at how to draw text onto the canvas.

Drawing text
------------

The canvas rendering context provides two methods to render text:

`fillText(text, x, y [, maxWidth])`

Fills a given text at the given (x,y) position. Optionally with a maximum width to draw.

`strokeText(text, x, y [, maxWidth])`

Strokes a given text at the given (x,y) position. Optionally with a maximum width to draw.

### A `fillText` example

The text is filled using the current `fillStyle`.

```js
function draw() {
  const ctx = document.getElementById("canvas").getContext("2d");
  ctx.font = "48px serif";
  ctx.fillText("Hello world", 10, 50);
}
```

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

```
draw();
```

### A `strokeText` example

The text is filled using the current `strokeStyle`.

```js
function draw() {
  const ctx = document.getElementById("canvas").getContext("2d");
  ctx.font = "48px serif";
  ctx.strokeText("Hello world", 10, 50);
}
```

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

```
draw();
```

Styling text
------------

In the examples above we are already making use of the `font` property to make the text a bit larger than the default size. There are some more properties which let you adjust the way the text gets displayed on the canvas:

`font = value`

The current text style being used when drawing text. This string uses the same syntax as the CSS `font` property. The default font is 10px sans-serif.

`textAlign = value`

Text alignment setting. Possible values: `start`, `end`, `left`, `right` or `center`. The default value is `start`.

`textBaseline = value`

Baseline alignment setting. Possible values: `top`, `hanging`, `middle`, `alphabetic`, `ideographic`, `bottom`. The default value is `alphabetic`.

`direction = value`

Directionality. Possible values: `ltr`, `rtl`, `inherit`. The default value is `inherit`.

These properties might be familiar to you, if you have worked with CSS before.

The following diagram from the WHATWG demonstrates the various baselines supported by the `textBaseline` property.
 ![The top of the em square is
roughly at the top of the glyphs in a font, the hanging baseline is
where some glyphs like आ are anchored, the middle is half-way
between the top of the em square and the bottom of the em square,
the alphabetic baseline is where characters like Á, ÿ,
f, and Ω are anchored, the ideographic baseline is
where glyphs like 私 and 達 are anchored, and the bottom
of the em square is roughly at the bottom of the glyphs in a
font. The top and bottom of the bounding box can be far from these
baselines, due to glyphs extending far outside the em square.](/en-US/docs/Web/API/Canvas_API/Tutorial/Drawing_text/baselines.png)

### A textBaseline example

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

<canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas>
<div class="playable-buttons">
  <input id="edit" type="button" value="Edit" />
  <input id="reset" type="button" value="Reset" />
</div>
<textarea id="code" class="playable-code">
ctx.font = "48px serif";
ctx.textBaseline = "hanging";
ctx.strokeText("Hello world", 0, 100);
</textarea>
```

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

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

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

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

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

Advanced text measurements
--------------------------

In the case you need to obtain more details about the text, the following method allows you to measure it.

`measureText()`

Returns a `TextMetrics` object containing the width, in pixels, that the specified text will be when drawn in the current text style.

The following code snippet shows how you can measure a text and get its width.

```js
function draw() {
  const ctx = document.getElementById("canvas").getContext("2d");
  const text = ctx.measureText("foo"); // TextMetrics object
  text.width; // 16;
}
```

Accessibility concerns
----------------------

The `<canvas>` element is just a bitmap and does not provide information about any drawn objects. Text written on canvas can cause legibility issues with users relying on screen magnification. The pixels within a canvas element do not scale and can become blurry with magnification. This is because they are not a vector but letter-shaped collection of pixels. When zooming in on it, the pixels become bigger.

Canvas content is not exposed to accessibility tools like semantic HTML is. In general, you should avoid using canvas in an accessible website or app. An alternative is to use HTML elements or SVG instead of canvas.

Gecko-specific notes
--------------------

In Gecko (the rendering engine of Firefox, Firefox OS and other Mozilla based applications), some prefixed APIs were implemented in earlier versions to draw text on a canvas. These are now deprecated and removed, and are no longer guaranteed to work.

* « Previous
* Next »


Drawing shapes with canvas - Web APIs

Drawing shapes with canvas
==========================

* « Previous
* Next »

Now that we have set up our canvas environment, we can get into the details of how to draw on the canvas. By the end of this article, you will have learned how to draw rectangles, triangles, lines, arcs and curves, providing familiarity with some of the basic shapes. Working with paths is essential when drawing objects onto the canvas and we will see how that can be done.

The grid
--------

Before we can start drawing, we need to talk about the canvas grid or **coordinate space**. Our HTML skeleton from the previous page had a canvas element 150 pixels wide and 150 pixels high.

![Canvas grid with a blue square demonstrating coordinates and axes.](/en-US/docs/Web/API/Canvas_API/Tutorial/Drawing_shapes/canvas_default_grid.png)

Normally 1 unit in the grid corresponds to 1 pixel on the canvas. The origin of this grid is positioned in the *top left* corner at coordinate (0,0). All elements are placed relative to this origin. So the position of the top left corner of the blue square becomes x pixels from the left and y pixels from the top, at coordinate (x,y). Later in this tutorial we'll see how we can translate the origin to a different position, rotate the grid and even scale it, but for now we'll stick to the default.

Drawing rectangles
------------------

Unlike SVG, `<canvas>` only supports two primitive shapes: rectangles and paths (lists of points connected by lines). All other shapes must be created by combining one or more paths. Luckily, we have an assortment of path drawing functions which make it possible to compose very complex shapes.

First let's look at the rectangle. There are three functions that draw rectangles on the canvas:

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

Draws a filled rectangle.

`strokeRect(x, y, width, height)`

Draws a rectangular outline.

`clearRect(x, y, width, height)`

Clears the specified rectangular area, making it fully transparent.

Each of these three functions takes the same parameters. `x` and `y` specify the position on the canvas (relative to the origin) of the top-left corner of the rectangle. `width` and `height` provide the rectangle's size.

Below is the `draw()` function from the previous page, but now it is making use of these three functions.

### Rectangular shape example
```

<html lang="en">
  <body>
    <canvas id="canvas" width="150" height="150"></canvas>
  </body>
</html>
```

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

    ctx.fillRect(25, 25, 100, 100);
    ctx.clearRect(45, 45, 60, 60);
    ctx.strokeRect(50, 50, 50, 50);
  }
}
```

```
draw();
```

This example's output is shown below.

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

The `fillRect()` function draws a large black square 100 pixels on each side. The `clearRect()` function then erases a 60x60 pixel square from the center, and then `strokeRect()` is called to create a rectangular outline 50x50 pixels within the cleared square.

In upcoming pages we'll see two alternative methods for `clearRect()`, and we'll also see how to change the color and stroke style of the rendered shapes.

Unlike the path functions we'll see in the next section, all three rectangle functions draw immediately to the canvas.

Drawing paths
-------------

Now let's look at paths. A path is a list of points, connected by segments of lines that can be of different shapes, curved or not, of different width and of different color. A path, or even a subpath, can be closed. To make shapes using paths, we take some extra steps:

1. First, you create the path.
2. Then you use drawing commands to draw into the path.
3. Once the path has been created, you can stroke or fill the path to render it.

Here are the functions used to perform these steps:

`beginPath()`

Creates a new path. Once created, future drawing commands are directed into the path and used to build the path up.

Path methods

Methods to set different paths for objects.

`closePath()`

Adds a straight line to the path, going to the start of the current sub-path.

`stroke()`

Draws the shape by stroking its outline.

`fill()`

Draws a solid shape by filling the path's content area.

The first step to create a path is to call the `beginPath()`. Internally, paths are stored as a list of sub-paths (lines, arcs, etc.) which together form a shape. Every time this method is called, the list is reset and we can start drawing new shapes.

**Note:** When the current path is empty, such as immediately after calling `beginPath()`, or on a newly created canvas, the first path construction command is always treated as a `moveTo()`, regardless of what it actually is. For that reason, you will almost always want to specifically set your starting position after resetting a path.

The second step is calling the methods that actually specify the paths to be drawn. We'll see these shortly.

The third, and an optional step, is to call `closePath()`. This method tries to close the shape by drawing a straight line from the current point to the start. If the shape has already been closed or there's only one point in the list, this function does nothing.

**Note:** When you call `fill()`, any open shapes are closed automatically, so you don't have to call `closePath()`. This is **not** the case when you call `stroke()`.

### Drawing a triangle

For example, the code for drawing a triangle would look something like this:
```

<html lang="en">
  <body>
    <canvas id="canvas" width="100" height="100"></canvas>
  </body>
</html>
```

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

    ctx.beginPath();
    ctx.moveTo(75, 50);
    ctx.lineTo(100, 75);
    ctx.lineTo(100, 25);
    ctx.fill();
  }
}
```

```
draw();
```

The result looks like this:

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

### Moving the pen

One very useful function, which doesn't actually draw anything but becomes part of the path list described above, is the `moveTo()` function. You can probably best think of this as lifting a pen or pencil from one spot on a piece of paper and placing it on the next.

`moveTo(x, y)`

Moves the pen to the coordinates specified by `x` and `y`.

When the canvas is initialized or `beginPath()` is called, you typically will want to use the `moveTo()` function to place the starting point somewhere else. We could also use `moveTo()` to draw unconnected paths. Take a look at the smiley face below.

To try this for yourself, you can use the code snippet below. Just paste it into the `draw()` function we saw earlier.
```

<html lang="en">
  <body>
    <canvas id="canvas" width="150" height="150"></canvas>
  </body>
</html>
```

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

    ctx.beginPath();
    ctx.arc(75, 75, 50, 0, Math.PI \* 2, true); // Outer circle
    ctx.moveTo(110, 75);
    ctx.arc(75, 75, 35, 0, Math.PI, false); // Mouth (clockwise)
    ctx.moveTo(65, 65);
    ctx.arc(60, 65, 5, 0, Math.PI \* 2, true); // Left eye
    ctx.moveTo(95, 65);
    ctx.arc(90, 65, 5, 0, Math.PI \* 2, true); // Right eye
    ctx.stroke();
  }
}
```

```
draw();
```

The result looks like this:

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

If you'd like to see the connecting lines, you can remove the lines that call `moveTo()`.

**Note:** To learn more about the `arc()` function, see the Arcs section below.

### Lines

For drawing straight lines, use the `lineTo()` method.

`lineTo(x, y)`

Draws a line from the current drawing position to the position specified by `x` and `y`.

This method takes two arguments, `x` and `y`, which are the coordinates of the line's end point. The starting point is dependent on previously drawn paths, where the end point of the previous path is the starting point for the following, etc. The starting point can also be changed by using the `moveTo()` method.

The example below draws two triangles, one filled and one outlined.
```

<html lang="en">
  <body>
    <canvas id="canvas" width="150" height="150"></canvas>
  </body>
</html>
```

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

    // Filled triangle
    ctx.beginPath();
    ctx.moveTo(25, 25);
    ctx.lineTo(105, 25);
    ctx.lineTo(25, 105);
    ctx.fill();

    // Stroked triangle
    ctx.beginPath();
    ctx.moveTo(125, 125);
    ctx.lineTo(125, 45);
    ctx.lineTo(45, 125);
    ctx.closePath();
    ctx.stroke();
  }
}
```

```
draw();
```

This starts by calling `beginPath()` to start a new shape path. We then use the `moveTo()` method to move the starting point to the desired position. Below this, two lines are drawn which make up two sides of the triangle.

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

You'll notice the difference between the filled and stroked triangle. This is, as mentioned above, because shapes are automatically closed when a path is filled, but not when they are stroked. If we left out the `closePath()` for the stroked triangle, only two lines would have been drawn, not a complete triangle.

### Arcs

To draw arcs or circles, we use the `arc()` or `arcTo()` methods.

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

Draws an arc which is centered at *(x, y)* position with radius *r* starting at *startAngle* and ending at *endAngle* going in the given direction indicated by *counterclockwise* (defaulting to clockwise).

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

Draws an arc with the given control points and radius, connected to the previous point by a straight line.

Let's have a more detailed look at the `arc` method, which takes six parameters: `x` and `y` are the coordinates of the center of the circle on which the arc should be drawn. `radius` is self-explanatory. The `startAngle` and `endAngle` parameters define the start and end points of the arc in radians, along the curve of the circle. These are measured from the x axis. The `counterclockwise` parameter is a Boolean value which, when `true`, draws the arc counterclockwise; otherwise, the arc is drawn clockwise.

**Note:** Angles in the `arc` function are measured in radians, not degrees. To convert degrees to radians you can use the following JavaScript expression: `radians = (Math.PI/180)*degrees`.

The following example is a little more complex than the ones we've seen above. It draws 12 different arcs all with different angles and fills.

The two `for` loops are for looping through the rows and columns of arcs. For each arc, we start a new path by calling `beginPath()`. In the code, each of the parameters for the arc is in a variable for clarity, but you wouldn't necessarily do that in real life.

The `x` and `y` coordinates should be clear enough. `radius` and `startAngle` are fixed. The `endAngle` starts at 180 degrees (half a circle) in the first column and is increased by steps of 90 degrees, culminating in a complete circle in the last column.

The statement for the `clockwise` parameter results in the first and third row being drawn as clockwise arcs and the second and fourth row as counterclockwise arcs. Finally, the `if` statement makes the top half stroked arcs and the bottom half filled arcs.

**Note:** This example requires a slightly larger canvas than the others on this page: 150 x 200 pixels.
```

<html lang="en">
  <body>
    <canvas id="canvas" width="150" height="200"></canvas>
  </body>
</html>
```

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

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

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

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

```
draw();
```

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

### Bezier and quadratic curves

The next type of paths available are Bézier curves, available in both cubic and quadratic varieties. These are generally used to draw complex organic shapes.

`quadraticCurveTo(cp1x, cp1y, x, y)`

Draws a quadratic Bézier curve from the current pen position to the end point specified by `x` and `y`, using the control point specified by `cp1x` and `cp1y`.

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

Draws a cubic Bézier curve from the current pen position to the end point specified by `x` and `y`, using the control points specified by (`cp1x`, `cp1y`) and (`cp2x`, `cp2y`).

 The difference between these is that a quadratic Bézier curve has a start and an end point (blue dots) and just one **control point** (indicated by the red dot) while a cubic Bézier curve uses two control points.

 ![Quadratic and Bezier curve comparison.](/en-US/docs/Web/API/Canvas_API/Tutorial/Drawing_shapes/canvas_curves.png)

The `x` and `y` parameters in both of these methods are the coordinates of the end point. `cp1x` and `cp1y` are the coordinates of the first control point, and `cp2x` and `cp2y` are the coordinates of the second control point.

Using quadratic and cubic Bézier curves can be quite challenging, because unlike vector drawing software like Adobe Illustrator, we don't have direct visual feedback as to what we're doing. This makes it pretty hard to draw complex shapes. In the following example, we'll be drawing some simple organic shapes, but if you have the time and, most of all, the patience, much more complex shapes can be created.

There's nothing very difficult in these examples. In both cases we see a succession of curves being drawn which finally result in a complete shape.

#### Quadratic Bezier curves

This example uses multiple quadratic Bézier curves to render a speech balloon.
```

<html lang="en">
  <body>
    <canvas id="canvas" width="150" height="150"></canvas>
  </body>
</html>
```

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

    // Quadratic curves example
    ctx.beginPath();
    ctx.moveTo(75, 25);
    ctx.quadraticCurveTo(25, 25, 25, 62.5);
    ctx.quadraticCurveTo(25, 100, 50, 100);
    ctx.quadraticCurveTo(50, 120, 30, 125);
    ctx.quadraticCurveTo(60, 120, 65, 100);
    ctx.quadraticCurveTo(125, 100, 125, 62.5);
    ctx.quadraticCurveTo(125, 25, 75, 25);
    ctx.stroke();
  }
}
```

```
draw();
```

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

#### Cubic Bezier curves

This example draws a heart using cubic Bézier curves.
```

<html lang="en">
  <body>
    <canvas id="canvas" width="150" height="150"></canvas>
  </body>
</html>
```

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

    // Cubic curves example
    ctx.beginPath();
    ctx.moveTo(75, 40);
    ctx.bezierCurveTo(75, 37, 70, 25, 50, 25);
    ctx.bezierCurveTo(20, 25, 20, 62.5, 20, 62.5);
    ctx.bezierCurveTo(20, 80, 40, 102, 75, 120);
    ctx.bezierCurveTo(110, 102, 130, 80, 130, 62.5);
    ctx.bezierCurveTo(130, 62.5, 130, 25, 100, 25);
    ctx.bezierCurveTo(85, 25, 75, 37, 75, 40);
    ctx.fill();
  }
}
```

```
draw();
```

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

### Rectangles

In addition to the three methods we saw in Drawing rectangles, which draw rectangular shapes directly to the canvas, there's also the `rect()` method, which adds a rectangular path to a currently open path.

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

Draws a rectangle whose top-left corner is specified by (`x`, `y`) with the specified `width` and `height`.

Before this method is executed, the `moveTo()` method is automatically called with the parameters (x,y). In other words, the current pen position is automatically reset to the default coordinates.

### Making combinations

So far, each example on this page has used only one type of path function per shape. However, there's no limitation to the number or types of paths you can use to create a shape. So in this final example, let's combine all of the path functions to make a set of very famous game characters.
```

<html lang="en">
  <body>
    <canvas id="canvas" width="150" height="150"></canvas>
  </body>
</html>
```

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

    roundedRect(ctx, 12, 12, 150, 150, 15);
    roundedRect(ctx, 19, 19, 150, 150, 9);
    roundedRect(ctx, 53, 53, 49, 33, 10);
    roundedRect(ctx, 53, 119, 49, 16, 6);
    roundedRect(ctx, 135, 53, 49, 33, 10);
    roundedRect(ctx, 135, 119, 25, 49, 10);

    ctx.beginPath();
    ctx.arc(37, 37, 13, Math.PI / 7, -Math.PI / 7, false);
    ctx.lineTo(31, 37);
    ctx.fill();

    for (let i = 0; i < 8; i++) {
      ctx.fillRect(51 + i \* 16, 35, 4, 4);
    }

    for (let i = 0; i < 6; i++) {
      ctx.fillRect(115, 51 + i \* 16, 4, 4);
    }

    for (let i = 0; i < 8; i++) {
      ctx.fillRect(51 + i \* 16, 99, 4, 4);
    }

    ctx.beginPath();
    ctx.moveTo(83, 116);
    ctx.lineTo(83, 102);
    ctx.bezierCurveTo(83, 94, 89, 88, 97, 88);
    ctx.bezierCurveTo(105, 88, 111, 94, 111, 102);
    ctx.lineTo(111, 116);
    ctx.lineTo(106.333, 111.333);
    ctx.lineTo(101.666, 116);
    ctx.lineTo(97, 111.333);
    ctx.lineTo(92.333, 116);
    ctx.lineTo(87.666, 111.333);
    ctx.lineTo(83, 116);
    ctx.fill();

    ctx.fillStyle = "white";
    ctx.beginPath();
    ctx.moveTo(91, 96);
    ctx.bezierCurveTo(88, 96, 87, 99, 87, 101);
    ctx.bezierCurveTo(87, 103, 88, 106, 91, 106);
    ctx.bezierCurveTo(94, 106, 95, 103, 95, 101);
    ctx.bezierCurveTo(95, 99, 94, 96, 91, 96);
    ctx.moveTo(103, 96);
    ctx.bezierCurveTo(100, 96, 99, 99, 99, 101);
    ctx.bezierCurveTo(99, 103, 100, 106, 103, 106);
    ctx.bezierCurveTo(106, 106, 107, 103, 107, 101);
    ctx.bezierCurveTo(107, 99, 106, 96, 103, 96);
    ctx.fill();

    ctx.fillStyle = "black";
    ctx.beginPath();
    ctx.arc(101, 102, 2, 0, Math.PI \* 2, true);
    ctx.fill();

    ctx.beginPath();
    ctx.arc(89, 102, 2, 0, Math.PI \* 2, true);
    ctx.fill();
  }
}

// A utility function to draw a rectangle with rounded corners.

function roundedRect(ctx, x, y, width, height, radius) {
  ctx.beginPath();
  ctx.moveTo(x, y + radius);
  ctx.arcTo(x, y + height, x + radius, y + height, radius);
  ctx.arcTo(x + width, y + height, x + width, y + height - radius, radius);
  ctx.arcTo(x + width, y, x + width - radius, y, radius);
  ctx.arcTo(x, y, x, y + radius, radius);
  ctx.stroke();
}
```

```
draw();
```

The resulting image looks like this:

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

We won't go over this in detail, since it's actually surprisingly simple. The most important things to note are the use of the `fillStyle` property on the drawing context, and the use of a utility function (in this case `roundedRect()`). Using utility functions for bits of drawing you do often can be very helpful and reduce the amount of code you need, as well as its complexity.

We'll take another look at `fillStyle`, in more detail, later in this tutorial. Here, all we're doing is using it to change the fill color for paths from the default color of black to white, and then back again.

### Shapes with holes

To draw a shape with a hole in it, we need to draw the hole in different clock directions as we draw the outer shape. We either draw the outer shape clockwise and the inner shape anticlockwise or the outer shape clockwise and the inner shape anticlockwise.
```

<html lang="en">
  <body>
    <canvas id="canvas" width="150" height="150"></canvas>
  </body>
</html>
```

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

    ctx.beginPath();

    // Outter shape clockwise ⟳
    ctx.moveTo(0, 0);
    ctx.lineTo(150, 0);
    ctx.lineTo(75, 129.9);

    // Inner shape anticlockwise ↺
    ctx.moveTo(75, 20);
    ctx.lineTo(50, 60);
    ctx.lineTo(100, 60);

    ctx.fill();
  }
}
```

```
draw();
```

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

In the example above the outer triangle goes clockwise (move to the top-left corner, then draw a line to the right-left corner, and finish at the bottom) and the inner triangle goes anticlockwise (move to the top, then line to the bottom-left corner, and finish at the bottom-right).

Path2D objects
--------------

 As we have seen in the last example, there can be a series of paths and drawing commands to draw objects onto your canvas. To simplify the code and to improve performance, the `Path2D` object, available in recent versions of browsers, lets you cache or record these drawing commands. You are able to play back your paths quickly.
 Let's see how we can construct a `Path2D` object:

`Path2D()`

The **`Path2D()`** constructor returns a newly instantiated `Path2D` object, optionally with another path as an argument (creates a copy), or optionally with a string consisting of SVG path data.

```js
new Path2D(); // empty path object
new Path2D(path); // copy from another Path2D object
new Path2D(d); // path from SVG path data
```

All path methods like `moveTo`, `rect`, `arc` or `quadraticCurveTo`, etc., which we got to know above, are available on `Path2D` objects.

The `Path2D` API also adds a way to combine paths using the `addPath` method. This can be useful when you want to build objects from several components, for example.

`Path2D.addPath(path [, transform])`

Adds a path to the current path with an optional transformation matrix.

### Path2D example

In this example, we are creating a rectangle and a circle. Both are stored as a `Path2D` object, so that they are available for later usage. With the new `Path2D` API, several methods got updated to optionally accept a `Path2D` object to use instead of the current path. Here, `stroke` and `fill` are used with a path argument to draw both objects onto the canvas, for example.
```

<html lang="en">
  <body>
    <canvas id="canvas" width="130" height="100"></canvas>
  </body>
</html>
```

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

    const rectangle = new Path2D();
    rectangle.rect(10, 10, 50, 50);

    const circle = new Path2D();
    circle.arc(100, 35, 25, 0, 2 \* Math.PI);

    ctx.stroke(rectangle);
    ctx.fill(circle);
  }
}
```

```
draw();
```

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

### Using SVG paths

Another powerful feature of the new canvas `Path2D` API is using SVG path data to initialize paths on your canvas. This might allow you to pass around path data and re-use them in both, SVG and canvas.

The path will move to point (`M10 10`) and then move horizontally 80 points to the right (`h 80`), then 80 points down (`v 80`), then 80 points to the left (`h -80`), and then back to the start (`z`). You can see this example on the `Path2D` constructor page.

```js
const p = new Path2D("M10 10 h 80 v 80 h -80 Z");
```

* « Previous
* Next »


CSSConditionRule: conditionText property - Web APIs

CSSConditionRule: conditionText property
========================================

 The **`conditionText`** property of
 the `CSSConditionRule` interface returns or sets the text of the CSS
 rule.

Value
-----

A string.

Examples
--------

 The following example demonstrates getting and setting the value of
 `conditionText` on a `CSSMediaRule` which implements the
 `CSSConditionRule` interface.

```css
@media (min-width: 500px) {
  body {
    color: blue;
  }
}
```

```js
let myRules = document.styleSheets[0].cssRules;
let text = myRules[0].conditionText;
console.log(text); // "(min-width: 500px)"
text = "(min-width: 400px)";
console.log(text); // "(min-width: 400px)"
```

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

| Specification |
| --- |
| CSS Conditional Rules Module Level 3 # dom-cssconditionrule-conditiontext |

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

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

See also
--------

* Using dynamic styling information


SVGMaskElement: width property - Web APIs

SVGMaskElement: width property
==============================

The read-only **`width`** property of the `SVGMaskElement` interface returns an `SVGAnimatedLength` object containing the value of the `width` attribute of the `<marker>`.

**Note:** Although this property is read-only, it is merely a container for two values you can modify, `baseVal` and `animVal`.

Value
-----

An `SVGAnimatedLength` object. The `baseVal` property of this object returns an `SVGLength`, the value of which returns the `width` value.

Examples
--------
```

html,
body,
svg {
  height: 100%;
}
```

```html
<div>
  <svg viewBox="-10 -10 120 120" width="100" height="100">
    <mask id="mask" x="0" maskUnits="objectBoundingBox">
      <!-- Everything under a white pixel will be visible -->
      <rect x="0" y="0" width="100" height="100" fill="white" />

      <!-- Everything under a black pixel will be invisible -->
      <path
 d="M10,35 A20,20,0,0,1,50,35 A20,20,0,0,1,90,35 Q90,65,50,95 Q10,65,10,35 Z"
 fill="black" />
      <animate
 attributeName="width"
 values="144;0;144"
 dur="5s"
 repeatCount="indefinite" />
    </mask>

    <polygon points="-10,110 110,110 110,-10" fill="orange" />

    <!-- with this mask applied, we "punch" a heart shape hole into the circle -->
    <circle cx="50" cy="50" r="50" mask="url(#mask)" />
  </svg>
</div>
<pre id="log"></pre>
```

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

function displayLog() {
  const animValue = mask.width.animVal.value;
  const baseValue = mask.width.baseVal.value;
  log.textContent = `The 'width.animVal' is ${animValue}.\n`;
  log.textContent += `The 'width.baseVal' is ${baseValue}.`;
  requestAnimationFrame(displayLog);
}
displayLog();
```

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

| Specification |
| --- |
| CSS Masking Module Level 1 # dom-svgmaskelement-width |

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

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


SVGMaskElement: x property - Web APIs

SVGMaskElement: x property
==========================

The read-only **`x`** property of the `SVGMaskElement` interface returns an `SVGAnimatedLength` object containing the value of the `x` attribute of the `<mask>`. It represents the x-axis coordinate of the *top-left* corner of the masking area.

**Note:** Although this property is read-only, it is merely a container for two values you can modify, `baseVal` and `animVal`.

Value
-----

An `SVGAnimatedLength` object in the coordinate system defined by `SVGMaskElement.maskUnits`. The `baseVal` property of this object returns an `SVGLength`, the value of which returns the initial `x` value.

Examples
--------
```

html,
body,
svg {
  height: 100%;
}
```

```html
<div>
  <svg viewBox="-10 -10 120 120" width="100" height="100">
    <mask id="mask" x="0" maskUnits="userSpaceOnUse">
      <!-- Everything under a white pixel will be visible -->
      <rect x="0" y="0" width="100" height="100" fill="white" />

      <!-- Everything under a black pixel will be invisible -->
      <path
 d="M10,35 A20,20,0,0,1,50,35 A20,20,0,0,1,90,35 Q90,65,50,95 Q10,65,10,35 Z"
 fill="black" />
      <animate
 attributeName="x"
 values="0;80;0"
 dur="5s"
 repeatCount="indefinite" />
    </mask>

    <polygon points="-10,110 110,110 110,-10" fill="orange" />

    <!-- with this mask applied, we "punch" a heart shape hole into the circle -->
    <circle cx="50" cy="50" r="50" mask="url(#mask)" />
  </svg>
</div>
<pre id="log"></pre>
```

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

function displayLog() {
  const animValue = mask.x.animVal.value;
  const baseValue = mask.x.baseVal.value;
  log.textContent = `The 'x.animVal' is ${animValue}.\n`;
  log.textContent += `The 'x.baseVal' is ${baseValue}.`;
  requestAnimationFrame(displayLog);
}
displayLog();
```

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

| Specification |
| --- |
| CSS Masking Module Level 1 # dom-svgmaskelement-x |

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

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


SVGMaskElement: y property - Web APIs

SVGMaskElement: y property
==========================

The read-only **`y`** property of the `SVGMaskElement` interface returns an `SVGAnimatedLength` object containing the value of the `y` attribute of the `<marker>`. It represents the y-axis coordinate of the *top-left* corner of the masking area.

**Note:** Although this property is read-only, it is merely a container for two values you can modify, `baseVal` and `animVal`.

Value
-----

An `SVGAnimatedLength` object. The `baseVal` property of this object returns an `SVGLength`, the value of which returns the `y` value.

Examples
--------
```

html,
body,
svg {
  height: 100%;
}
```

```html
<div>
  <svg viewBox="-10 -10 120 120" width="100" height="100">
    <mask id="mask" x="0" maskUnits="userSpaceOnUse">
      <!-- Everything under a white pixel will be visible -->
      <rect x="0" y="0" width="100" height="100" fill="white" />

      <!-- Everything under a black pixel will be invisible -->
      <path
 d="M10,35 A20,20,0,0,1,50,35 A20,20,0,0,1,90,35 Q90,65,50,95 Q10,65,10,35 Z"
 fill="black" />
      <animate
 attributeName="y"
 values="0;80;0"
 dur="5s"
 repeatCount="indefinite" />
    </mask>

    <polygon points="-10,110 110,110 110,-10" fill="orange" />

    <!-- with this mask applied, we "punch" a heart shape hole into the circle -->
    <circle cx="50" cy="50" r="50" mask="url(#mask)" />
  </svg>
</div>
<pre id="log"></pre>
```

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

function displayLog() {
  const animValue = mask.y.animVal.value;
  const baseValue = mask.y.baseVal.value;
  log.textContent = `The 'y.animVal' is ${animValue}.\n`;
  log.textContent += `The 'y.baseVal' is ${baseValue}.`;
  requestAnimationFrame(displayLog);
}
displayLog();
```

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

| Specification |
| --- |
| CSS Masking Module Level 1 # dom-svgmaskelement-y |

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

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


SVGMaskElement: maskContentUnits property - Web APIs

SVGMaskElement: maskContentUnits property
=========================================

The read-only **`maskContentUnits`** property of the `SVGMaskElement` interface reflects the `maskContentUnits` attribute. It indicates which coordinate system to use for the contents of the `<mask>` element.

**Note:** Although this property is read-only, it is merely a container for two values you can modify, `baseVal` and `animVal`.

Value
-----

An `SVGAnimatedEnumeration` representing the coordinate system. The possible values are defined in the `SVGUnitTypes` interface:

`0` (`SVG_UNIT_TYPE_UNKNOWN`)

The type is not one of the predefined types.

`1` (`SVG_UNIT_TYPE_USERSPACEONUSE`)

Corresponds to a value of `userSpaceOnUse` for the `maskContentUnits` attribute and means that all coordinates inside the element refer to the user coordinate system as defined when the mask was created. It is the default value.

`2` (`SVG_UNIT_TYPE_OBJECTBOUNDINGBOX`)

Corresponds to a value of `objectBoundingBox` for the attribute and means that all coordinates inside the element are relative to the bounding box of the element the mask is applied to. It means that the origin of the coordinate system is the top left corner of the object bounding box and the width and height of the object bounding box are considered to have a length of 1 unit value.

Examples
--------
```

html,
body,
svg {
  height: 100%;
}
```

```html
<div>
  <svg
 viewBox="0 0 100 100"
 width="150"
 height="150"
 xmlns="http://www.w3.org/2000/svg">
    <mask id="mask1" maskContentUnits="userSpaceOnUse">
      <rect fill="black" x="0" y="0" width="100%" height="100%" />
      <circle fill="white" cx="50" cy="50" r="35" />
    </mask>

    <mask id="mask2" maskContentUnits="objectBoundingBox">
      <rect fill="black" x="0" y="0" width="100%" height="100%" />
      <circle fill="white" cx=".5" cy=".5" r=".35" />
      <animate
 attributeName="maskContentUnits"
 values="objectBoundingBox;userSpaceOnUse"
 dur="1s"
 repeatCount="indefinite" />
    </mask>

    <!-- Some reference rect to materialized the mask -->
    <rect id="r1" x="0" y="0" width="45" height="45" />
    <rect id="r2" x="0" y="55" width="45" height="45" />
    <rect id="r3" x="55" y="55" width="45" height="45" />
    <rect id="r4" x="55" y="0" width="45" height="45" />

    <!-- The first 3 rect are masked with useSpaceOnUse units -->
    <use mask="url(#mask1)" href="#r1" fill="blue" />
    <use mask="url(#mask1)" href="#r2" fill="yellow" />
    <use mask="url(#mask1)" href="#r3" fill="green" />

    <!-- The last rect is masked with objectBoundingBox units -->
    <use mask="url(#mask2)" href="#r4" fill="lightblue" />
  </svg>
</div>
<pre id="log"></pre>
```

```js
const unitType = ["unknown", "userSpaceOnUse", "objectBoundingBox"];

const mask = document.getElementById("mask2");
const log = document.getElementById("log");

function displayLog() {
  const baseValue = unitType[mask.maskContentUnits.baseVal];
  const animValue = unitType[mask.maskContentUnits.animVal];
  log.textContent = `The top-right 'maskContentUnits.baseVal' coord system : ${baseValue}\n`;
  log.textContent += `The top-right 'maskContentUnits.animVal' coord system : ${animValue}`;
  requestAnimationFrame(displayLog);
}
displayLog();
```

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

| Specification |
| --- |
| CSS Masking Module Level 1 # dom-svgmaskelement-maskcontentunits |

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

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

See also
--------

* `maskContentUnits`
* `<mask>`


SVGMaskElement: maskUnits property - Web APIs

SVGMaskElement: maskUnits property
==================================

The read-only **`maskUnits`** property of the `SVGMaskElement` interface reflects the `maskUnits` attribute of a `<mask>` element which defines the coordinate system to use for the mask of the element.

**Note:** Although this property is read-only, it is merely a container for two values you can modify, `baseVal` and `animVal`.

Value
-----

An `SVGAnimatedEnumeration` representing the coordinate system. The possible values are defined in the `SVGUnitTypes` interface:

`0` (`SVG_UNIT_TYPE_UNKNOWN`)

The type is not one of the predefined types.

`1` (`SVG_UNIT_TYPE_USERSPACEONUSE`)

Corresponds to a value of `userSpaceOnUse` for the `maskUnits` attribute and means that all coordinates inside the element refer to the user coordinate system as defined when the mask was created. It is the default value.

`2` (`SVG_UNIT_TYPE_OBJECTBOUNDINGBOX`)

Corresponds to a value of `objectBoundingBox` for the attribute and means that all coordinates inside the element are relative to the bounding box of the element the mask is applied to. It means that the origin of the coordinate system is the top left corner of the object bounding box and the width and height of the object bounding box are considered to have a length of 1 unit value.

Examples
--------
```

html,
body,
svg {
  height: 100%;
}
```

```html
<div>
  <svg
 viewBox="0 0 100 100"
 height="200"
 width="200"
 xmlns="http://www.w3.org/2000/svg">
    <mask
 id="mask1"
 maskUnits="userSpaceOnUse"
 x="20%"
 y="20%"
 width="60%"
 height="60%">
      <rect fill="black" x="0" y="0" width="100%" height="100%" />
      <circle fill="white" cx="50" cy="50" r="35" />
    </mask>

    <mask
 id="mask2"
 maskUnits="objectBoundingBox"
 x="20%"
 y="20%"
 width="60%"
 height="60%">
      <rect fill="black" x="0" y="0" width="100%" height="100%" />
      <circle fill="white" cx="50" cy="50" r="35" />
      <animate
 attributeName="maskUnits"
 values="objectBoundingBox;userSpaceOnUse"
 dur="1s"
 repeatCount="indefinite" />
    </mask>

    <!-- Some reference rect to materialized the mask -->
    <rect id="r1" x="0" y="0" width="45" height="45" />
    <rect id="r2" x="0" y="55" width="45" height="45" />
    <rect id="r3" x="55" y="55" width="45" height="45" />
    <rect id="r4" x="55" y="0" width="45" height="45" />

    <!-- The first 3 rect are masked with useSpaceOnUse units -->
    <use mask="url(#mask1)" href="#r1" fill="blue" />
    <use mask="url(#mask1)" href="#r2" fill="green" />
    <use mask="url(#mask1)" href="#r3" fill="yellow" />

    <!-- The last rect is masked with objectBoundingBox units -->
    <use mask="url(#mask2)" href="#r4" fill="lightblue" />
  </svg>
</div>
<pre id="log"></pre>
```

```js
const unitType = ["unknown", "userSpaceOnUse", "objectBoundingBox"];

const mask = document.getElementById("mask2");
const log = document.getElementById("log");

function displayLog() {
  const baseValue = unitType[mask.maskUnits.baseVal];
  const animValue = unitType[mask.maskUnits.animVal];
  log.textContent = `The top-right 'maskUnits.baseVal' coord system : ${baseValue}\n`;
  log.textContent += `The top-right 'maskUnits.animVal' coord system : ${animValue}`;
  requestAnimationFrame(displayLog);
}
displayLog();
```

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

| Specification |
| --- |
| CSS Masking Module Level 1 # dom-svgmaskelement-maskunits |

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

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

See also
--------

* `maskUnits`
* `<mask>`


SVGMaskElement: height property - Web APIs

SVGMaskElement: height property
===============================

The read-only **`height`** property of the `SVGMaskElement` interface returns an `SVGAnimatedLength` object containing the value of the `height` attribute of the `<marker>`.

**Note:** Although this property is read-only, it is merely a container for two values you can modify, `baseVal` and `animVal`.

Value
-----

An `SVGAnimatedLength` object. The `baseVal` property of this object returns an `SVGLength`, the value of which returns the `height` value.

Examples
--------
```

html,
body,
svg {
  height: 100%;
}
```

```html
<div>
  <svg viewBox="-10 -10 120 120" width="100" height="100">
    <mask id="mask" x="0" maskUnits="objectBoundingBox">
      <!-- Everything under a white pixel will be visible -->
      <rect x="0" y="0" width="100" height="100" fill="white" />

      <!-- Everything under a black pixel will be invisible -->
      <path
 d="M10,35 A20,20,0,0,1,50,35 A20,20,0,0,1,90,35 Q90,65,50,95 Q10,65,10,35 Z"
 fill="black" />
      <animate
 attributeName="height"
 values="144;0;144"
 dur="5s"
 repeatCount="indefinite" />
    </mask>

    <polygon points="-10,110 110,110 110,-10" fill="orange" />

    <!-- with this mask applied, we "punch" a heart shape hole into the circle -->
    <circle cx="50" cy="50" r="50" mask="url(#mask)" />
  </svg>
</div>
<pre id="log"></pre>
```

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

function displayLog() {
  const animValue = mask.height.animVal.value;
  const baseValue = mask.height.baseVal.value;
  log.textContent = `The 'height.animVal' is ${animValue}.\n`;
  log.textContent += `The 'height.baseVal' is ${baseValue}.`;
  requestAnimationFrame(displayLog);
}
displayLog();
```

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

| Specification |
| --- |
| CSS Masking Module Level 1 # dom-svgmaskelement-height |

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

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


HTMLBaseElement: target property - Web APIs

HTMLBaseElement: target property
================================

The `target` property of the `HTMLBaseElement` interface is a string that represents the default target tab to show the resulting output for hyperlinks and form elements.

It reflects the `target` attribute of the `<base>` element.

Value
-----

A string representing the target. Its value can be:

* The name of a `<frame>`.
* One of the keyword with specific values:`_blank`, `_self`, `_parent`, or `_top`.
Example
-------

```html
<head>
  <base target="\_top" />
</head>
```

```js
const baseElement = document.getElementsByTagName("base")[0];
console.log(baseElement.target); // Output: '\_top'
```

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

| Specification |
| --- |
| HTML Standard # dom-base-target |

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

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

See also
--------

* `HTMLAnchorElement.target` property
* `HTMLAreaElement.target` property
* `HTMLFormElement.target` property


XRBoundedReferenceSpace: boundsGeometry property - Web APIs

XRBoundedReferenceSpace: boundsGeometry property
================================================

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

 The read-only `XRBoundedReferenceSpace`
 property **`boundsGeometry`** is an array of
 `DOMPointReadOnly` objects which specifies the points making up a polygon
 inside which the viewer is allowed to move. Each point is treated as a
 two-dimensional point, and must be located at ground level (that is,
 its `y` coordinate must be 0).

 This boundary is typically configured by the user, using the software that controls
 their XR hardware. This may be done by walking the border of the space they wish to use,
 or by drawing the shape of their room using their XR input device. Theoretically, a more
 advanced system might use sensors or other detection methods to determine the bounds of
 a dedicated XR room (notice how we carefully don't call it a holodeck?).

Value
-----

 The `boundsGeometry` property is an array of `DOMPointReadOnly`
 objects, each of which defines one vertex in a polygon inside which the viewer is
 required to remain. Each point must be at floor level, with
 its `y` coordinate's value set to 0. Additionally, the value
 of `w` is always 1 in every point in the array. Additionally, the
 points *must* be listed in clockwise order.

 Each entry in `boundsGeometry` is equal to an entry in the list of native
 bounds geometry points for the room, premultiplied by the inverse of the origin offset.
 In other words, the bounds are the physical limitations of the available space, shifted
 so that the reference space's bounds points are all defined relative to the
 `XRBoundedReferenceSpace`'s effective origin.

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

 Bounded reference spaces always have their origin located at ground level,
 where `y` is 0. As a general rule, with the origin
 for `x` and `z` located in or near the center of the space, and
 with the orientation set facing in a logical forward direction, as appropriate for the
 underlying platform or XR hardware.

 In order to reduce the risk of the room boundaries being used for fingerprinting
 purposes, each point in the `boundsGeometry` array may be rounded or adjusted
 by some amount. The specification recommends that browsers shift the points to the
 nearest 5 centimeters (while avoiding going outside the physical limitations of the
 hardware).

### Boundary size

`XRBoundedReferenceSpace` is not intended to be used for very large bounded
 areas. Instead, it's meant to be used for one-room spaces with no more than around 15
 meters of available movement space in any direction from the native origin. That said,
 the bounds extend upward indefinitely, since the bounds are defined in only two
 dimensions.

 If you need to create a multi-room space, or a space which is very large or needs to
 have varying floor levels, you should instead use an unbounded
 `XRReferenceSpace` and enforce the bounds on your own, as appropriate.

### Boundary shape

 The shape defined by `boundsGeometry` may be as simple as a square or as
 complex as is needed, potentially including concave and/or convex sections. However,
 you can't represent spaces with uneven floor levels
 using `XRBoundedReferenceSpace`. The ground is *always*
 at `y` = 0.

 It's important that your content not be designed to require the user to exit the bounds
 specified by `boundsGeometry`. However, if the user's surroundings permit
 them to move in such a way as to exit the defined bounds, your content must be able to
 gracefully handle the situation, which is not considered an error condition.

 Although some samples render a mesh or other shape to display the bounds to the user,
 in a real-world application, you shouldn't do this. The browser, however, should provide
 appropriate warnings to the user about any risks (such as the risk that they might run
 into a physical wall if they keep moving).

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

| Specification |
| --- |
| WebXR Device API # dom-xrboundedreferencespace-boundsgeometry |

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

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


CSSPerspective: length property - Web APIs

CSSPerspective: length property
===============================

 The **`length`** property of the
 `CSSPerspective` interface sets the distance from z=0.

 It is used to apply a perspective transform to the element and its content. If the
 value is 0 or a negative number, no perspective transform is applied.

Value
-----

A `CSSNumericValue`

Examples
--------

To Do

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

| Specification |
| --- |
| CSS Typed OM Level 1 # dom-cssperspective-length |

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

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


CSSPerspective: CSSPerspective() constructor - Web APIs

CSSPerspective: CSSPerspective() constructor
============================================

 The **`CSSPerspective()`** constructor creates
 a new `CSSPerspective` object representing the perspective() value of
 the individual `transform` property in CSS.

Syntax
------

```js
new CSSPerspective(length)
```

### Parameters

`length`

 A value for the distance from z=0 of the `CSSPerspective` object to be
 constructed. This must be a `<length>`.

### Exceptions

`TypeError`

 Raised if the value of `CSSPerspective.length` exists but is not a
 `<length>`.

Examples
--------

To do

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

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

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

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


SharedWorker: SharedWorker() constructor - Web APIs

SharedWorker: SharedWorker() constructor
========================================

 The **`SharedWorker()`** constructor creates a
 `SharedWorker` object that executes the script at the specified URL. This
 script must obey the same-origin policy.

**Note:** there is disagreement among browser manufacturers about
 whether a data URL is of the same origin or not. Although Firefox 10.0
 and later accept data URLs, that's not the case in all other
 browsers.

Syntax
------

```js
new SharedWorker(aURL)
new SharedWorker(aURL, name)
new SharedWorker(aURL, options)
```

### Parameters

`aURL`

 A string representing the URL of the script the worker will
 execute. It must obey the same-origin policy.

`name` Optional

 A string specifying an identifying name for the
 `SharedWorkerGlobalScope` representing the scope of the worker, which is useful for creating new instances of the same SharedWorker and debugging.

`options` Optional

 An object containing option properties that can set when creating the object
 instance. Available properties are as follows:

`type`

 A string specifying the type of worker to
 create. The value can be `classic` or `module`. If not
 specified, the default used is `classic`.

`credentials`

 A string specifying the type of
 credentials to use for the worker. The value can be `omit`,
 `same-origin`, or *`include`. If not
specified, or if type is `classic`, the default used is
`omit` (no credentials required).*

`name`

 A string specifying an
 identifying name for the `SharedWorkerGlobalScope` representing the
 scope of the worker, which is mainly useful for debugging purposes.

### Exceptions

`SecurityError` `DOMException`

Thrown if the document is not allowed to start workers, for example if the URL has an invalid syntax or if the same-origin policy is violated.

`NetworkError` `DOMException`

Thrown if the MIME type of the worker script is incorrect. It should *always* be `text/javascript` (for historical reasons other JavaScript MIME types may be accepted).

`SyntaxError` `DOMException`

Thrown if `aURL` cannot be parsed.

Examples
--------

 The following code snippet shows creation of a `SharedWorker` object using
 the `SharedWorker()` constructor and subsequent usage of the object:

```js
const myWorker = new SharedWorker("worker.js");

myWorker.port.start();

first.onchange = () => {
  myWorker.port.postMessage([first.value, second.value]);
  console.log("Message posted to worker");
};

second.onchange = () => {
  myWorker.port.postMessage([first.value, second.value]);
  console.log("Message posted to worker");
};

myWorker.port.onmessage = (e) => {
  result1.textContent = e.data;
  console.log("Message received from worker");
};
```

For a full example, see our Basic shared worker example (run shared worker.)

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

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

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

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

See also
--------

* The `SharedWorker` interface it belongs to.


SharedWorker: error event - Web APIs

SharedWorker: error event
=========================

The **`error`** event of the `SharedWorker` interface fires when an error occurs in the worker.

Syntax
------

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

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

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

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

A generic `Event`.

Example
-------

The following code snippet creates a `SharedWorker` object using the `SharedWorker()` constructor and sets up an `onerror` handler on the resulting object:

```js
const mySharedWorker = new SharedWorker("shared-worker.js");

mySharedWorker.onerror = (event) => {
  console.error("There is an error with your worker!");
};
```

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

| Specification |
| --- |
| HTML Standard # handler-abstractworker-onerror |

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

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


SharedWorker: port property - Web APIs

SharedWorker: port property
===========================

 The **`port`** property of the `SharedWorker`
 interface returns a `MessagePort` object used to communicate and control
 the shared worker.

Value
-----

A `MessagePort` object.

Examples
--------

 The following code snippet shows creation of a `SharedWorker` object using
 the `SharedWorker()` constructor. Multiple
 scripts can then access the worker through a `MessagePort` object accessed
 using the `SharedWorker.port` property — the port is started using its
 `start()` method:

```js
const myWorker = new SharedWorker("worker.js");
myWorker.port.start();
```

For a full example, see our Basic shared worker example (run shared worker.)

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

| Specification |
| --- |
| HTML Standard # dom-sharedworker-port-dev |

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

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

See also
--------

* `SharedWorker`


ReadableStreamBYOBReader: cancel() method - Web APIs

ReadableStreamBYOBReader: cancel() method
=========================================

 The **`cancel()`** method of the `ReadableStreamBYOBReader` interface returns a `Promise` that resolves when the stream is canceled.
 Calling this method signals a loss of interest in the stream by a consumer.

**Note:** If the reader is active, the `cancel()` method behaves the same as that for the associated stream (`ReadableStream.cancel()`).

Syntax
------

```js
cancel()
cancel(reason)
```

### Parameters

`reason` Optional

A human-readable reason for the cancellation. The underlying source may or may not use it.

### Return value

A `Promise`, which fulfills with the value given in the `reason` parameter.

### Exceptions

`TypeError`

The source object is not a `ReadableStreamBYOBReader`, or the stream has no owner.

Examples
--------

 This example code calls the `cancel()` method when a button is pressed, passing the string "user choice" as a reason.
 The promise resolves when cancellation completes.

```js
button.addEventListener("click", () => {
  reader.cancel("user choice").then(() => console.log(`cancel complete`));
});
```

Note that this code can be seen running in the Using readable byte streams example code (press the **Cancel stream** button).

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

| Specification |
| --- |
| Streams Standard # ref-for-generic-reader-cancel② |

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

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

See also
--------

* `ReadableStreamBYOBReader()` constructor
* Using readable byte stream


ReadableStreamBYOBReader: closed property - Web APIs

ReadableStreamBYOBReader: closed property
=========================================

The **`closed`** read-only property of the `ReadableStreamBYOBReader` interface returns a `Promise` that fulfills when the stream closes, or rejects if the stream throws an error or the reader's lock is released.

This property enables you to write code that responds to an end to the streaming process.

Value
-----

A `Promise`.

Examples
--------

The code below shows the pattern for handling the closed/error state of a BYOBReader.

```js
const reader = stream.getReader({ mode: "byob" });
reader.closed
  .then(() => {
    // Resolved - code to handle stream closing
  })
  .catch(() => {
    // Rejected - code to handle error
  });
```

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

| Specification |
| --- |
| Streams Standard # ref-for-generic-reader-closed② |

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

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

See also
--------

* `ReadableStreamBYOBReader()` constructor
* Using readable byte stream


ReadableStreamBYOBReader: releaseLock() method - Web APIs

ReadableStreamBYOBReader: releaseLock() method
==============================================

 The **`releaseLock()`** method of the `ReadableStreamBYOBReader` interface releases the reader's lock on the stream.
 After the lock is released, the reader is no longer active.

The reader will appear errored if the associated stream is errored when the lock is released; otherwise, the reader will appear closed.

 If the reader's lock is released while it still has pending read requests then the promises returned by the reader's `ReadableStreamBYOBReader.read()` method are immediately rejected with a `TypeError`.
 Unread chunks remain in the stream's internal queue and can be read later by acquiring a new reader.

Syntax
------

```js
releaseLock()
```

### Parameters

None.

### Return value

None (`undefined`).

### Exceptions

`TypeError`

Thrown if the source object is not a `ReadableStreamBYOBReader`.

Examples
--------

 A trivial examples is shown below.
 A lock is created as soon as the reader is created on the stream.

```js
const reader = stream.getReader({ mode: "byob" });
reader.releaseLock();
```

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

| Specification |
| --- |
| Streams Standard # ref-for-byob-reader-release-lock② |

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

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

See also
--------

* `ReadableStreamBYOBReader()` constructor
* Using readable byte stream


ReadableStreamBYOBReader: ReadableStreamBYOBReader() constructor - Web APIs

ReadableStreamBYOBReader: ReadableStreamBYOBReader() constructor
================================================================

The **`ReadableStreamBYOBReader()`** constructor creates and returns a `ReadableStreamBYOBReader` object instance.

**Note:** You generally wouldn't use this constructor manually;
 instead, you'd use the `ReadableStream.getReader()` method with the argument `"byob"`.

Syntax
------

```js
new ReadableStreamBYOBReader(stream)
```

### Parameters

`stream`

The `ReadableStream` to be read.

### Return value

An instance of the `ReadableStreamBYOBReader` object.

### Exceptions

`TypeError`

Thrown if the supplied `stream` parameter is not a `ReadableStream`, or it is already locked for reading by another reader, or its stream controller is not a `ReadableByteStreamController`.

Examples
--------

 The constructor is rarely called directly.
 Instead call `ReadableStream.getReader()` as shown:

```js
const reader = stream.getReader({ mode: "byob" });
```

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

| Specification |
| --- |
| Streams Standard # ref-for-byob-reader-constructor① |

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

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

See also
--------

* `ReadableStreamBYOBReader`
* Using readable byte stream


ReadableStreamBYOBReader: read() method - Web APIs

ReadableStreamBYOBReader: read() method
=======================================

 The **`read()`** method of the `ReadableStreamBYOBReader` interface is used to read data into a view on a user-supplied buffer from an associated readable byte stream.
 A request for data will be satisfied from the stream's internal queues if there is any data present.
 If the stream queues are empty, the request may be supplied as a zero-copy transfer from the underlying byte source.

 The method takes as an argument a view on a buffer that supplied data is to be read into, and returns a `Promise`.
 The promise fulfills with an object that has properties `value` and `done` when data comes available, or if the stream is cancelled.
 If the stream is errored, the promise will be rejected with the relevant error object.

 If a chunk of data is supplied, the `value` property will contain a new view.
 This will be a view over the same buffer/backing memory (and of the same type) as the original `view` passed to the `read()` method, now populated with the new chunk of data.
 Note that once the promise fulfills, the original `view` passed to the method will be detached and no longer usable.
 The promise will fulfill with a `value: undefined` if the stream has been cancelled.
 In this case the backing memory region of `view` is discarded and not returned to the caller (all previously read data in the view's buffer is lost).

 The `done` property indicates whether or not more data is expected.
 The value is set `true` if the stream is closed or cancelled, and `false` otherwise.

Syntax
------

```js
read(view)
```

### Parameters

`view`

The view that data is to be read into.

### Return value

A `Promise`, which fulfills/rejects with a result depending on the state of the stream.

The following are possible:

* If a chunk is available and the stream is still active, the promise fulfills with an object of the form:

```js
{ value: theChunk, done: false }
```

`theChunk` is a view containing the new data.
 This is a view of the same type and over the same backing memory as the `view` passed to the `read()` method.
 The original `view` will be detached and no longer usable.
* If the stream is closed, the promise fulfills with an object of the form (where `theChunk` has the same properties as above):

```js
{ value: theChunk, done: true }
```

* If the stream is cancelled, the promise fulfills with an object of the form:

```js
{ value: undefined, done: true }
```

In this case the backing memory is discarded.
* If the stream throws an error, the promise rejects with the relevant error.
### Exceptions

`TypeError`

The source object is not a `ReadableStreamBYOBReader`, the stream has no owner, the view is not an object or has become detached, the view's length is 0, or `ReadableStreamBYOBReader.releaseLock()` is called (when there's is a pending read request).

Examples
--------

The example code here is taken from the live examples in Using readable byte streams.

 First we create the reader using `ReadableStream.getReader()` on the stream, specifying `mode: "byob"` in the options parameter.
 We also need create an `ArrayBuffer`, which is the "backing memory" of the views that we will write into.

```js
const reader = stream.getReader({ mode: "byob" });
let buffer = new ArrayBuffer(4000);
```

 A function that uses the reader is shown below.
 This calls the `read()` method recursively to read data into the buffer.
 The method takes a `Uint8Array` typed array which is a view over the part of the original array buffer that has not yet been written.
 The parameters of the view are calculated from the data that was received in previous calls, which define an offset into the original array buffer.

```js
readStream(reader);

function readStream(reader) {
  let bytesReceived = 0;
  let offset = 0;

  while (offset < buffer.byteLength) {
    // read() returns a promise that fulfills when a value has been received
    reader
      .read(new Uint8Array(buffer, offset, buffer.byteLength - offset))
      .then(function processBytes({ done, value }) {
        // Result objects contain two properties:
        // done - true if the stream has already given all its data.
        // value - some data. 'undefined' if the reader is canceled.

        if (done) {
          // There is no more data in the stream
          return;
        }

        buffer = value.buffer;
        offset += value.byteLength;
        bytesReceived += value.byteLength;

        // Read some more, and call this function again
        // Note that here we create a new view over the original buffer.
        return reader
          .read(new Uint8Array(buffer, offset, buffer.byteLength - offset))
          .then(processBytes);
      });
  }
}
```

When there is no more data in the stream, the `read()` method fulfills with an object with the property `done` set to `true`, and the function returns.

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

| Specification |
| --- |
| Streams Standard # ref-for-byob-reader-read③ |

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

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

See also
--------

* `ReadableStreamBYOBReader()` constructor
* Using readable byte stream


ScreenOrientation: angle property - Web APIs

ScreenOrientation: angle property
=================================

 The **`angle`** read-only property of the
 `ScreenOrientation` interface returns the document's current orientation
 angle.

Value
-----

An unsigned short integer.

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

| Specification |
| --- |
| Screen Orientation # dom-screenorientation-angle |

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

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


ScreenOrientation: type property - Web APIs

ScreenOrientation: type property
================================

 The **`type`** read-only property of the
 `ScreenOrientation` interface returns the document's current orientation
 type, one of `portrait-primary`, `portrait-secondary`, `landscape-primary`, or
 `landscape-secondary`.

Value
-----

A `String`.

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

| Specification |
| --- |
| Screen Orientation # dom-screenorientation-type |

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

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


ScreenOrientation: change event - Web APIs

ScreenOrientation: change event
===============================

The **`change`** event of the `ScreenOrientation` interface fires when the orientation of the screen has changed, for example when a user rotates their mobile phone.

Syntax
------

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

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

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

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

A generic `Event`.

Example
-------

In the following example, the `change` callback prints the new screen orientation type and angle.

```js
screen.orientation.addEventListener("change", (event) => {
  const type = event.target.type;
  const angle = event.target.angle;
  console.log(`ScreenOrientation change: ${type}, ${angle} degrees.`);
});
```

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

| Specification |
| --- |
| Screen Orientation # dom-screenorientation-onchange |

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

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


ScreenOrientation: lock() method - Web APIs

ScreenOrientation: lock() method
================================

The **`lock()`** property of the `ScreenOrientation` interface locks the orientation of the containing document to the specified orientation.

 Typically orientation locking is only enabled on mobile devices, and when the browser context is full screen.
 If locking is supported, then it must work for all the parameter values listed below.

Syntax
------

```js
lock(orientation)
```

### Parameters

`orientation`

An orientation lock type. One of the following:

`"any"`

Any of `portrait-primary`, `portrait-secondary`, `landscape-primary` or `landscape-secondary`.

`"natural"`

The natural orientation of the screen from the underlying operating system: either `portrait-primary` or `landscape-primary`.

`"landscape"`

 An orientation where screen width is greater than the screen height.
 Depending on the platform convention, this may be `landscape-primary`, `landscape-secondary`, or both.

`"portrait"`

 An orientation where screen height is greater than the screen width.
 Depending on the platform convention, this may be `portrait-primary`, `portrait-secondary`, or both.

`"portrait-primary"`

 The "primary" portrait mode.
 If the natural orientation is a portrait mode (screen height is greater than width), this will be the same as the natural orientation, and correspond to an angle of 0 degrees.
 If the natural orientation is a landscape mode, then the user agent can choose either portrait orientation as the `portrait-primary` and `portrait-secondary`; one of those will be assigned the angle of 90 degrees and the other will have an angle of 270 degrees.

`"portrait-secondary"`

 The secondary portrait orientation.
 If the natural orientation is a portrait mode, this will have an angle of 180 degrees (in other words, the device is upside down relative to its natural orientation).
 If the natural orientation is a landscape mode, this can be either orientation as selected by the user agent: whichever was not selected for `portrait-primary`.

`"landscape-primary"`

 The "primary" landscape mode.
 If the natural orientation is a landscape mode (screen width is greater than height), this will be the same as the natural orientation, and correspond to an angle of 0 degrees.
 If the natural orientation is a portrait mode, then the user agent can choose either landscape orientation as the `landscape-primary` with an angle of either 90 or 270 degrees (`landscape-secondary` will be the other orientation and angle).

`"landscape-secondary"`

 The secondary landscape mode.
 If the natural orientation is a landscape mode, this orientation is upside down relative to the natural orientation, and will have an angle of 180 degrees.
 If the natural orientation is a portrait mode, this can be either orientation as selected by the user agent: whichever was not selected for `landscape-primary`.

### Return value

A `Promise` that resolves after locking succeeds.

### Exceptions

The promise may be rejected with the following exceptions:

`InvalidStateError` `DOMException`

Thrown if the document is not fully active.

`SecurityError` `DOMException`

Thrown if the document's visibility state is hidden or if the document is forbidden to use the feature (for example, by omitting the keyword `allow-orientation-lock` of the `sandbox` attribute of the `iframe` element).

`NotSupportedError` `DOMException`

Thrown if the user agent does not support locking the screen orientation of the specific orientation.

`AbortError` `DOMException`

Thrown if there is any other `lock()` method invoking.

Examples
--------

 This example shows how to lock the screen to the opposite orientation of the current one.
 Note that this example will only work on mobile devices and other devices that support orientation changes.

```html
<div id="example\_container">
  <button id="fullscreen\_button">Fullscreen</button>
  <button id="lock\_button">Lock</button>
  <button id="unlock\_button">Unlock</button>
  <textarea id="log" rows="7" cols="85"></textarea>
</div>
```

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

// Lock button: Lock the screen to the other orientation (rotated by 90 degrees)
const rotate_btn = document.querySelector("#lock\_button");
rotate_btn.addEventListener("click", () => {
  log.textContent += `Lock pressed \n`;

  const oppositeOrientation = screen.orientation.type.startsWith("portrait")
    ? "landscape"
    : "portrait";
  screen.orientation
    .lock(oppositeOrientation)
    .then(() => {
      log.textContent = `Locked to ${oppositeOrientation}\n`;
    })
    .catch((error) => {
      log.textContent += `${error}\n`;
    });
});

// Unlock button: Unlock the screen orientation (if locked)
const unlock_btn = document.querySelector("#unlock\_button");
unlock_btn.addEventListener("click", () => {
  log.textContent += "Unlock pressed \n";
  screen.orientation.unlock();
});

// Full screen button: Set the example to fullscreen.
const fullscreen_btn = document.querySelector("#fullscreen\_button");
fullscreen_btn.addEventListener("click", () => {
  log.textContent += "Fullscreen pressed \n";
  const container = document.querySelector("#example\_container");
  container.requestFullscreen().catch((error) => {
    log.textContent += `${error}\n`;
  });
});
```

 To test the example, first press the Fullscreen button.
 Once the example is full screen, press the Lock button to switch the orientation, and Unlock to return to the natural orientation.

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

| Specification |
| --- |
| Screen Orientation # dom-screenorientation-lock |

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

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


ScreenOrientation: unlock() method - Web APIs

ScreenOrientation: unlock() method
==================================

 The **`unlock()`** property of the
 `ScreenOrientation` interface unlocks the orientation of the containing
 document from its default orientation.

Syntax
------

```js
unlock()
```

### Parameters

None.

### Return value

None (`undefined`).

### Exceptions

The promise may be rejected with the following exceptions:

`InvalidStateError` `DOMException`

Thrown if the document is not fully active.

`SecurityError` `DOMException`

Thrown if the document's visibility state is hidden or if the document is forbidden to use the feature (for example, by omitting the keyword `allow-orientation-lock` of the `sandbox` attribute of the `iframe` element).

`AbortError` `DOMException`

Thrown if there is any other `lock()` method invoking.

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

| Specification |
| --- |
| Screen Orientation # dom-screenorientation-unlock |

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

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