repo_id
stringlengths
22
103
file_path
stringlengths
41
147
content
stringlengths
181
193k
__index_level_0__
int64
0
0
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d/drawimage/index.md
--- title: "CanvasRenderingContext2D: drawImage() method" short-title: drawImage() slug: Web/API/CanvasRenderingContext2D/drawImage page-type: web-api-instance-method browser-compat: api.CanvasRenderingContext2D.drawImage --- {{APIRef}} The **`CanvasRenderingContext2D.drawImage()`** method of the Canvas 2D API provides different ways to draw an image onto the canvas. ## Syntax ```js-nolint drawImage(image, dx, dy) drawImage(image, dx, dy, dWidth, dHeight) drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight) ``` ![drawImage](canvas_drawimage.jpg) ### Parameters - `image` - : An element to draw into the context. The specification permits any canvas image source, specifically, an {{domxref("HTMLImageElement")}}, an {{domxref("SVGImageElement")}}, an {{domxref("HTMLVideoElement")}}, an {{domxref("HTMLCanvasElement")}}, an {{domxref("ImageBitmap")}}, an {{domxref("OffscreenCanvas")}}, or a {{domxref("VideoFrame")}}. - `sx` {{optional_inline}} - : The x-axis coordinate of the top left corner of the sub-rectangle of the source `image` to draw into the destination context. Use the 3- or 5-argument syntax to omit this argument. - `sy` {{optional_inline}} - : The y-axis coordinate of the top left corner of the sub-rectangle of the source `image` to draw into the destination context. Use the 3- or 5-argument syntax to omit this argument. - `sWidth` {{optional_inline}} - : The width of the sub-rectangle of the source `image` to draw into the destination context. If not specified, the entire rectangle from the coordinates specified by `sx` and `sy` to the bottom-right corner of the image is used. Use the 3- or 5-argument syntax to omit this argument. A negative value will flip the image. - `sHeight` {{optional_inline}} - : The height of the sub-rectangle of the source `image` to draw into the destination context. Use the 3- or 5-argument syntax to omit this argument. A negative value will flip the image. - `dx` - : The x-axis coordinate in the destination canvas at which to place the top-left corner of the source `image`. - `dy` - : The y-axis coordinate in the destination canvas at which to place the top-left corner of the source `image`. - `dWidth` - : The width to draw the `image` in the destination canvas. This allows scaling of the drawn image. If not specified, the image is not scaled in width when drawn. Note that this argument is not included in the 3-argument syntax. - `dHeight` - : The height to draw the `image` in the destination canvas. This allows scaling of the drawn image. If not specified, the image is not scaled in height when drawn. Note that this argument is not included in the 3-argument syntax. ### Return value None ({{jsxref("undefined")}}). ### Exceptions - `InvalidStateError` {{domxref("DOMException")}} - : Thrown when the image has no image data or if the canvas or source rectangle width or height is zero. - `TypeMismatchError` {{domxref("DOMException")}} - : Thrown when a `null` or `undefined` image is passed as parameter. ## Examples ### Drawing an image to the canvas This example draws an image to the canvas using the `drawImage()` method. #### HTML ```html <canvas id="canvas"></canvas> <div style="display:none;"> <img id="source" src="rhino.jpg" width="300" height="227" /> </div> ``` #### JavaScript The source image is taken from the coordinates (33, 71), with a width of 104 and a height of 124. It is drawn to the canvas at (21, 20), where it is given a width of 87 and a height of 104. ```js const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); const image = document.getElementById("source"); image.addEventListener("load", (e) => { ctx.drawImage(image, 33, 71, 104, 124, 21, 20, 87, 104); }); ``` #### Result {{ EmbedLiveSample('Drawing_an_image_to_the_canvas', 700, 180) }} ### Understanding source element size The `drawImage()` method uses the source element's _intrinsic size in CSS pixels_ when drawing. For example, if you load an `Image` and specify the optional size parameters in its [constructor](/en-US/docs/Web/API/HTMLImageElement/Image), you will have to use the `naturalWidth` and `naturalHeight` properties of the created instance to properly calculate things like crop and scale regions, rather than `element.width` and `element.height`. The same goes for `videoWidth` and `videoHeight` if the element is a {{htmlelement("video")}} element, and so on. #### HTML ```html <canvas id="canvas"></canvas> ``` #### JavaScript ```js const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); const image = new Image(60, 45); // Using optional size for image image.onload = drawImageActualSize; // Draw when image has loaded // Load an image of intrinsic size 300x227 in CSS pixels image.src = "rhino.jpg"; function drawImageActualSize() { // Use the intrinsic size of image in CSS pixels for the canvas element canvas.width = this.naturalWidth; canvas.height = this.naturalHeight; // Will draw the image as 300x227, ignoring the custom size of 60x45 // given in the constructor ctx.drawImage(this, 0, 0); // To use the custom size we'll have to specify the scale parameters // using the element's width and height properties - lets draw one // on top in the corner: ctx.drawImage(this, 0, 0, this.width, this.height); } ``` #### Result {{EmbedLiveSample('Understanding_source_element_size', 700, 260)}} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## Notes - `drawImage()` only works correctly on an {{domxref("HTMLVideoElement")}} when its {{domxref("HTMLMediaElement.readyState")}} is greater than 1 (i.e., **seek** event fired after setting the `currentTime` property). - `drawImage()` will always use the source element's _intrinsic size in CSS pixels_ when drawing, cropping, and/or scaling. - In some older browser versions, `drawImage()` will ignore all EXIF metadata in images, including the Orientation. This behavior is especially troublesome on iOS devices. You should detect the Orientation yourself and use `rotate()` to make it right. ## See also - The interface defining this method: {{domxref("CanvasRenderingContext2D")}}
0
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d/lineto/index.md
--- title: "CanvasRenderingContext2D: lineTo() method" short-title: lineTo() slug: Web/API/CanvasRenderingContext2D/lineTo page-type: web-api-instance-method browser-compat: api.CanvasRenderingContext2D.lineTo --- {{APIRef}} The {{domxref("CanvasRenderingContext2D")}} method **`lineTo()`**, part of the Canvas 2D API, adds a straight line to the current sub-path by connecting the sub-path's last point to the specified `(x, y)` coordinates. Like other methods that modify the current path, this method does not directly render anything. To draw the path onto a canvas, you can use the {{domxref("CanvasRenderingContext2D.fill", "fill()")}} or {{domxref("CanvasRenderingContext2D.stroke", "stroke()")}} methods. ## Syntax ```js-nolint lineTo(x, y) ``` ### Parameters - `x` - : The x-axis coordinate of the line's end point. - `y` - : The y-axis coordinate of the line's end point. ### Return value None ({{jsxref("undefined")}}). ## Examples ### Drawing a straight line This example draws a straight line using the `lineTo()` method. #### HTML ```html <canvas id="canvas"></canvas> ``` #### JavaScript The line begins at (30, 50) and ends at (150, 100). ```js const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); ctx.beginPath(); // Start a new path ctx.moveTo(30, 50); // Move the pen to (30, 50) ctx.lineTo(150, 100); // Draw a line to (150, 100) ctx.stroke(); // Render the path ``` #### Result {{ EmbedLiveSample('Drawing_a_straight_line', 700, 180) }} ### Drawing connected lines Each call of `lineTo()` (and similar methods) automatically adds to the current sub-path, which means that all the lines will all be stroked or filled together. This example draws a letter 'M' with a single contiguous line. #### HTML ```html <canvas id="canvas"></canvas> ``` #### JavaScript ```js const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); ctx.moveTo(90, 130); ctx.lineTo(95, 25); ctx.lineTo(150, 80); ctx.lineTo(205, 25); ctx.lineTo(210, 130); ctx.lineWidth = 15; ctx.stroke(); ``` #### Result {{ EmbedLiveSample('Drawing_connected_lines', 700, 180) }} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The interface defining this method: {{domxref("CanvasRenderingContext2D")}} - {{domxref("CanvasRenderingContext2D.moveTo()")}} - {{domxref("CanvasRenderingContext2D.stroke()")}}
0
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d/drawfocusifneeded/index.md
--- title: "CanvasRenderingContext2D: drawFocusIfNeeded() method" short-title: drawFocusIfNeeded() slug: Web/API/CanvasRenderingContext2D/drawFocusIfNeeded page-type: web-api-instance-method browser-compat: api.CanvasRenderingContext2D.drawFocusIfNeeded --- {{APIRef}} 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-nolint drawFocusIfNeeded(element) drawFocusIfNeeded(path, element) ``` ### Parameters - `element` - : The element to check whether it is focused or not. - `path` - : A {{domxref("Path2D")}} path to use. ### Return value None ({{jsxref("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 {{EmbedLiveSample('Managing_button_focus', 700, 180)}} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The interface defining this method: {{domxref("CanvasRenderingContext2D")}}
0
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d/wordspacing/index.md
--- title: "CanvasRenderingContext2D: wordSpacing property" short-title: wordSpacing slug: Web/API/CanvasRenderingContext2D/wordSpacing page-type: web-api-instance-property browser-compat: api.CanvasRenderingContext2D.wordSpacing --- {{APIRef}} The **`CanvasRenderingContext2D.wordSpacing`** property of the [Canvas API](/en-US/docs/Web/API/Canvas_API) specifies the spacing between words when drawing text. This corresponds to the CSS [`word-spacing`](/en-US/docs/Web/CSS/word-spacing) property. ## Value The word spacing as a string in the CSS {{cssxref("length")}} data format. The default is `0px`. The property can be used to get or set the spacing. The property value will remain unchanged if set to an invalid/unparsable value. ## Examples In this example we display the text "Hello World" three times, using the `wordSpacing` property to modify the spacing in each case. The spacing is also displayed for each case, using the value of the property. ### HTML ```html <canvas id="canvas" width="700"></canvas> ``` ### JavaScript ```js const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); ctx.font = "30px serif"; // Default word spacing ctx.fillText(`Hello world (default: ${ctx.wordSpacing})`, 10, 40); // Custom word spacing: 10px ctx.wordSpacing = "10px"; ctx.fillText(`Hello world (${ctx.wordSpacing})`, 10, 90); // Custom word spacing: 30px ctx.wordSpacing = "30px"; ctx.fillText(`Hello world (${ctx.wordSpacing})`, 10, 140); ``` ### Result {{ EmbedLiveSample('Examples', 700, 180) }} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("CanvasRenderingContext2D.letterSpacing")}}
0
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d/rect/index.md
--- title: "CanvasRenderingContext2D: rect() method" short-title: rect() slug: Web/API/CanvasRenderingContext2D/rect page-type: web-api-instance-method browser-compat: api.CanvasRenderingContext2D.rect --- {{APIRef}} 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 {{domxref("CanvasRenderingContext2D.fill", "fill()")}} or {{domxref("CanvasRenderingContext2D.stroke", "stroke()")}} methods. > **Note:** To both create and render a rectangle in one step, use the > {{domxref("CanvasRenderingContext2D.fillRect", "fillRect()")}} or > {{domxref("CanvasRenderingContext2D.strokeRect", "strokeRect()")}} methods. ## Syntax ```js-nolint 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 ({{jsxref("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 {{ EmbedLiveSample('Drawing_a_rectangle', 700, 180) }} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The interface defining this method: {{domxref("CanvasRenderingContext2D")}} - {{domxref("CanvasRenderingContext2D.fillRect")}} - {{domxref("CanvasRenderingContext2D.strokeRect()")}} - {{domxref("CanvasRenderingContext2D.fill()")}} - {{domxref("CanvasRenderingContext2D.stroke()")}}
0
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d/closepath/index.md
--- title: "CanvasRenderingContext2D: closePath() method" short-title: closePath() slug: Web/API/CanvasRenderingContext2D/closePath page-type: web-api-instance-method browser-compat: api.CanvasRenderingContext2D.closePath --- {{APIRef}} The **`CanvasRenderingContext2D.closePath()`** method of the Canvas 2D API attempts to add a straight line from the current point to the start of the current sub-path. If the shape has already been closed or has only one point, this function does nothing. This method doesn't draw anything to the canvas directly. You can render the path using the {{domxref("CanvasRenderingContext2D.stroke()", "stroke()")}} or {{domxref("CanvasRenderingContext2D.fill()", "fill()")}} methods. ## Syntax ```js-nolint closePath() ``` ### Parameters None. ### Return value None ({{jsxref("undefined")}}). ## Examples ### Closing a triangle This example creates the first two (diagonal) sides of a triangle using the `lineTo()` method. After that, the triangle's base is created with the `closePath()` method, which automatically connects the shape's first and last points. #### HTML ```html <canvas id="canvas"></canvas> ``` #### JavaScript The triangle's corners are at (20, 140), (120, 10), and (220, 140). ```js const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); ctx.beginPath(); ctx.moveTo(20, 140); // Move pen to bottom-left corner ctx.lineTo(120, 10); // Line to top corner ctx.lineTo(220, 140); // Line to bottom-right corner ctx.closePath(); // Line to bottom-left corner ctx.stroke(); ``` #### Result {{ EmbedLiveSample('Closing_a_triangle', 700, 180) }} ### Closing just one sub-path This example draws a smiley face consisting of three disconnected sub-paths. > **Note:** Although `closePath()` is called after all the arcs have been > created, only the last arc (sub-path) gets closed. #### HTML ```html <canvas id="canvas"></canvas> ``` #### JavaScript The first two arcs create the face's eyes. The last arc creates the mouth. ```js const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); ctx.beginPath(); ctx.arc(240, 20, 40, 0, Math.PI); ctx.moveTo(100, 20); ctx.arc(60, 20, 40, 0, Math.PI); ctx.moveTo(215, 80); ctx.arc(150, 80, 65, 0, Math.PI); ctx.closePath(); ctx.lineWidth = 6; ctx.stroke(); ``` #### Result {{ EmbedLiveSample('Closing_just_one_sub-path', 700, 180) }} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The interface defining this method: {{domxref("CanvasRenderingContext2D")}} - {{domxref("CanvasRenderingContext2D.beginPath()")}}
0
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d/save/index.md
--- title: "CanvasRenderingContext2D: save() method" short-title: save() slug: Web/API/CanvasRenderingContext2D/save page-type: web-api-instance-method browser-compat: api.CanvasRenderingContext2D.save --- {{APIRef}} The **`CanvasRenderingContext2D.save()`** method of the Canvas 2D API saves the entire state of the canvas by pushing the current state onto a stack. ### The drawing state The drawing state that gets saved onto a stack consists of: - The current transformation matrix. - The current clipping region. - The current dash list. - The current values of the following attributes: {{domxref("CanvasRenderingContext2D.strokeStyle", "strokeStyle")}}, {{domxref("CanvasRenderingContext2D.fillStyle", "fillStyle")}}, {{domxref("CanvasRenderingContext2D.globalAlpha", "globalAlpha")}}, {{domxref("CanvasRenderingContext2D.lineWidth", "lineWidth")}}, {{domxref("CanvasRenderingContext2D.lineCap", "lineCap")}}, {{domxref("CanvasRenderingContext2D.lineJoin", "lineJoin")}}, {{domxref("CanvasRenderingContext2D.miterLimit", "miterLimit")}}, {{domxref("CanvasRenderingContext2D.lineDashOffset", "lineDashOffset")}}, {{domxref("CanvasRenderingContext2D.shadowOffsetX", "shadowOffsetX")}}, {{domxref("CanvasRenderingContext2D.shadowOffsetY", "shadowOffsetY")}}, {{domxref("CanvasRenderingContext2D.shadowBlur", "shadowBlur")}}, {{domxref("CanvasRenderingContext2D.shadowColor", "shadowColor")}}, {{domxref("CanvasRenderingContext2D.globalCompositeOperation", "globalCompositeOperation")}}, {{domxref("CanvasRenderingContext2D.font", "font")}}, {{domxref("CanvasRenderingContext2D.textAlign", "textAlign")}}, {{domxref("CanvasRenderingContext2D.textBaseline", "textBaseline")}}, {{domxref("CanvasRenderingContext2D.direction", "direction")}}, {{domxref("CanvasRenderingContext2D.imageSmoothingEnabled", "imageSmoothingEnabled")}}. ## Syntax ```js-nolint save() ``` ### Parameters None. ### Return value None ({{jsxref("undefined")}}). ## Examples ### Saving the drawing state This example uses the `save()` method to save the current state and `restore()` to restore it later, so that you are able to draw a rect with the current state later. #### HTML ```html <canvas id="canvas"></canvas> ``` #### JavaScript ```js const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); // Save the current state ctx.save(); ctx.fillStyle = "green"; ctx.fillRect(10, 10, 100, 100); // Restore to the state saved by the most recent call to save() ctx.restore(); ctx.fillRect(150, 40, 100, 100); ``` #### Result {{ EmbedLiveSample('Saving_the_drawing_state', 700, 180) }} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The interface defining this method: {{domxref("CanvasRenderingContext2D")}} - {{domxref("CanvasRenderingContext2D.restore()")}}
0
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d/settransform/index.md
--- title: "CanvasRenderingContext2D: setTransform() method" short-title: setTransform() slug: Web/API/CanvasRenderingContext2D/setTransform page-type: web-api-instance-method browser-compat: api.CanvasRenderingContext2D.setTransform --- {{APIRef}} The **`CanvasRenderingContext2D.setTransform()`** method of the Canvas 2D API resets (overrides) the current transformation to the identity matrix, and then invokes a transformation described by the arguments of this method. This lets you scale, rotate, translate (move), and skew the context. > **Note:** See also the {{domxref("CanvasRenderingContext2D.transform()", "transform()")}} method; instead of overriding the current transform matrix, it > multiplies it with a given one. ## Syntax ```js-nolint setTransform(a, b, c, d, e, f) setTransform(matrix) ``` The transformation matrix is described by: <math><semantics><mrow><mo>[</mo> <mtable columnalign="center center center" rowspacing="0.5ex"><mtr><mtd><mi>a</mi> </mtd><mtd><mi>c</mi> </mtd><mtd><mi>e</mi> </mtd></mtr><mtr><mtd><mi>b</mi> </mtd><mtd><mi>d</mi> </mtd><mtd><mi>f</mi> </mtd></mtr><mtr><mtd><mn>0</mn> </mtd><mtd><mn>0</mn> </mtd><mtd><mn>1</mn> </mtd></mtr></mtable><mo>]</mo> </mrow><annotation encoding="TeX">\left[ \begin{array}{ccc} a &#x26; c &#x26; e \\ b &#x26; d &#x26; f \\ 0 &#x26; 0 &#x26; 1 \end{array} \right]</annotation></semantics></math> This transformation matrix gets multiplied on the left of a column vector representing each point being drawn on the canvas, to produce the final coordinate used on the canvas. ### Parameters `setTransform()` has two types of parameter that it can accept. The older type consists of several parameters representing the individual components of the transformation matrix to set: - `a` (`m11`) - : The cell in the first row and first column of the matrix. - `b` (`m12`) - : The cell in the second row and first column of the matrix. - `c` (`m21`) - : The cell in the first row and second column of the matrix. - `d` (`m22`) - : The cell in the second row and second column of the matrix. - `e` (`m41`) - : The cell in the first row and third column of the matrix. - `f` (`m42`) - : The cell in the second row and third column of the matrix. Alternatively, you can pass a single parameter which is an object containing the values above as properties. The parameter names are the property keys, and if two synonymous names are both present (e.g. `m11` and `a`), they must be the same number value, or a {{jsxref("TypeError")}} will be thrown. Using the object form allows omitting some parameters — `a` and `d` default to `1`, while the rest default to `0`. If a point originally had coordinates <math><semantics><mrow><mo>(</mo><mi>x</mi><mo>,</mo><mi>y</mi><mo>)</mo></mrow><annotation encoding="TeX">(x, y)</annotation></semantics></math>, then after the transformation it will have coordinates <math><semantics><mrow><mo>(</mo><mi>a</mi><mi>x</mi><mo>+</mo><mi>c</mi><mi>y</mi><mo>+</mo><mi>e</mi><mo>,</mo><mi>b</mi><mi>x</mi><mo>+</mo><mi>d</mi><mi>y</mi><mo>+</mo><mi>f</mi><mo>)</mo></mrow><annotation encoding="TeX">(ax + cy + e, bx + dy + f)</annotation></semantics></math>. This means: - `e` and `f` control the horizontal and vertical translation of the context. - When `b` and `c` are `0`, `a` and `d` control the horizontal and vertical scaling of the context. - When `a` and `d` are `1`, `b` and `c` control the horizontal and vertical skewing of the context. ### Return value None ({{jsxref("undefined")}}). ## Examples ### Skewing a shape This example skews a rectangle both vertically (`.2`) and horizontally (`.8`). Scaling and translation remain unchanged. #### HTML ```html <canvas id="canvas"></canvas> ``` #### JavaScript ```js const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); ctx.setTransform(1, 0.2, 0.8, 1, 0, 0); ctx.fillRect(0, 0, 100, 100); ``` #### Result {{ EmbedLiveSample('Skewing_a_shape', 700, 180) }} ### Retrieving and passing a DOMMatrix object In the following example, we have two {{htmlelement("canvas")}} elements. We apply a transform to the first one's context using the first type of `setTransform()` and draw a square on it, then retrieve the matrix from it using {{domxref("CanvasRenderingContext2D.getTransform()")}}. We then apply the retrieved matrix directly to the second canvas context by passing the `DOMMatrix` object directly to `setTransform()` (i.e. the second type), and draw a circle on it. #### HTML ```html <!-- First canvas (ctx1) --> <canvas width="240"></canvas> <!-- Second canvas (ctx2) --> <canvas width="240"></canvas> ``` #### CSS ```css canvas { border: 1px solid black; } ``` #### JavaScript ```js const canvases = document.querySelectorAll("canvas"); const ctx1 = canvases[0].getContext("2d"); const ctx2 = canvases[1].getContext("2d"); ctx1.setTransform(1, 0.2, 0.8, 1, 0, 0); ctx1.fillRect(25, 25, 50, 50); let storedTransform = ctx1.getTransform(); console.log(storedTransform); ctx2.setTransform(storedTransform); ctx2.beginPath(); ctx2.arc(50, 50, 50, 0, 2 * Math.PI); ctx2.fill(); ``` #### Result {{ EmbedLiveSample('Retrieving_and_passing_a_DOMMatrix_object', "100%", 180) }} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The interface defining this method: {{domxref("CanvasRenderingContext2D")}} - {{domxref("CanvasRenderingContext2D.transform()")}}
0
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d/miterlimit/index.md
--- title: "CanvasRenderingContext2D: miterLimit property" short-title: miterLimit slug: Web/API/CanvasRenderingContext2D/miterLimit page-type: web-api-instance-property browser-compat: api.CanvasRenderingContext2D.miterLimit --- {{APIRef}} The **`CanvasRenderingContext2D.miterLimit`** property of the Canvas 2D API sets the miter limit ratio. > **Note:** For more info about miters, see [Applying styles and color](/en-US/docs/Web/API/Canvas_API/Tutorial/Applying_styles_and_colors) in the [Canvas tutorial](/en-US/docs/Web/API/Canvas_API/Tutorial). ## Value A number specifying the miter limit ratio, in coordinate space units. Zero, negative, {{jsxref("Infinity")}}, and {{jsxref("NaN")}} values are ignored. The default value is `10.0`. ## Examples ### Using the `miterLimit` property See the chapter [Applying styles and color](/en-US/docs/Web/API/Canvas_API/Tutorial/Applying_styles_and_colors#a_demo_of_the_miterlimit_property) in the [Canvas tutorial](/en-US/docs/Web/API/Canvas_API/Tutorial) for more information. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The interface defining this property: {{domxref("CanvasRenderingContext2D")}} - {{domxref("CanvasRenderingContext2D.lineCap")}} - {{domxref("CanvasRenderingContext2D.lineJoin")}}
0
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d/putimagedata/index.md
--- title: "CanvasRenderingContext2D: putImageData() method" short-title: putImageData() slug: Web/API/CanvasRenderingContext2D/putImageData page-type: web-api-instance-method browser-compat: api.CanvasRenderingContext2D.putImageData --- {{APIRef}} The **`CanvasRenderingContext2D.putImageData()`** method of the Canvas 2D API paints data from the given {{domxref("ImageData")}} object onto the canvas. If a dirty rectangle is provided, only the pixels from that rectangle are painted. This method is not affected by the canvas transformation matrix. > **Note:** Image data can be retrieved from a canvas using the > {{domxref("CanvasRenderingContext2D.getImageData()", "getImageData()")}} method. You can find more information about `putImageData()` and general manipulation of canvas contents in the article [Pixel manipulation with canvas](/en-US/docs/Web/API/Canvas_API/Tutorial/Pixel_manipulation_with_canvas). ## Syntax ```js-nolint putImageData(imageData, dx, dy) putImageData(imageData, dx, dy, dirtyX, dirtyY, dirtyWidth, dirtyHeight) ``` ### Parameters - `imageData` - : An {{domxref("ImageData")}} object containing the array of pixel values. - `dx` - : Horizontal position (x coordinate) at which to place the image data in the destination canvas. - `dy` - : Vertical position (y coordinate) at which to place the image data in the destination canvas. - `dirtyX` {{optional_inline}} - : Horizontal position (x coordinate) of the top-left corner from which the image data will be extracted. Defaults to `0`. - `dirtyY` {{optional_inline}} - : Vertical position (y coordinate) of the top-left corner from which the image data will be extracted. Defaults to `0`. - `dirtyWidth` {{optional_inline}} - : Width of the rectangle to be painted. Defaults to the width of the image data. - `dirtyHeight` {{optional_inline}} - : Height of the rectangle to be painted. Defaults to the height of the image data. ### Return value None ({{jsxref("undefined")}}). ### Exceptions - `NotSupportedError` {{domxref("DOMException")}} - : Thrown if any of the arguments is infinite. - `InvalidStateError` {{domxref("DOMException")}} - : Thrown if the `ImageData` object's data has been detached. ## Examples ### Understanding putImageData To understand what this algorithm does under the hood, here is an implementation on top of {{domxref("CanvasRenderingContext2D.fillRect()")}}. #### HTML ```html <canvas id="canvas"></canvas> ``` #### JavaScript ```js const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); function putImageData( ctx, imageData, dx, dy, dirtyX, dirtyY, dirtyWidth, dirtyHeight, ) { const data = imageData.data; const height = imageData.height; const width = imageData.width; dirtyX = dirtyX || 0; dirtyY = dirtyY || 0; dirtyWidth = dirtyWidth !== undefined ? dirtyWidth : width; dirtyHeight = dirtyHeight !== undefined ? dirtyHeight : height; const limitBottom = dirtyY + dirtyHeight; const limitRight = dirtyX + dirtyWidth; for (let y = dirtyY; y < limitBottom; y++) { for (let x = dirtyX; x < limitRight; x++) { const pos = y * width + x; ctx.fillStyle = `rgb(${data[pos * 4 + 0]} ${data[pos * 4 + 1]} ${data[pos * 4 + 2]} / ${data[pos * 4 + 3] / 255})`; ctx.fillRect(x + dx, y + dy, 1, 1); } } } // Draw content onto the canvas ctx.fillRect(0, 0, 100, 100); // Create an ImageData object from it const imagedata = ctx.getImageData(0, 0, 100, 100); // use the putImageData function that illustrates how putImageData works putImageData(ctx, imagedata, 150, 0, 50, 50, 25, 25); ``` #### Result {{ EmbedLiveSample('Understanding_putImageData', 700, 180) }} ### Data loss due to browser optimization > **Warning:** Due to the lossy nature of converting to and from premultiplied alpha color values, > pixels that have just been set using `putImageData()` might be returned to > an equivalent `getImageData()` as different values. #### JavaScript ```js const canvas = document.createElement("canvas"); canvas.width = 1; canvas.height = 1; const context = canvas.getContext("2d"); const imgData = context.getImageData(0, 0, canvas.width, canvas.height); const pixels = imgData.data; pixels[0 + 0] = 1; pixels[0 + 1] = 127; pixels[0 + 2] = 255; pixels[0 + 3] = 1; console.log("before:", pixels); context.putImageData(imgData, 0, 0); const imgData2 = context.getImageData(0, 0, canvas.width, canvas.height); const pixels2 = imgData2.data; console.log("after:", pixels2); ``` The output might look like: ```plain before: Uint8ClampedArray(4) [ 1, 127, 255, 1 ] after: Uint8ClampedArray(4) [ 255, 255, 255, 1 ] ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The interface defining this method: {{domxref("CanvasRenderingContext2D")}} - {{domxref("ImageData")}} object - {{domxref("CanvasRenderingContext2D.getImageData()")}} - [Pixel manipulation with canvas](/en-US/docs/Web/API/Canvas_API/Tutorial/Pixel_manipulation_with_canvas)
0
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d/moveto/index.md
--- title: "CanvasRenderingContext2D: moveTo() method" short-title: moveTo() slug: Web/API/CanvasRenderingContext2D/moveTo page-type: web-api-instance-method browser-compat: api.CanvasRenderingContext2D.moveTo --- {{APIRef}} The **`CanvasRenderingContext2D.moveTo()`** method of the Canvas 2D API begins a new sub-path at the point specified by the given `(x, y)` coordinates. ## Syntax ```js-nolint moveTo(x, y) ``` ### Parameters - `x` - : The x-axis (horizontal) coordinate of the point. - `y` - : The y-axis (vertical) coordinate of the point. ### Return value None ({{jsxref("undefined")}}). ## Examples ### Creating multiple sub-paths This example uses `moveTo()` to create two sub-paths within a single path. Both sub-paths are then rendered with a single `stroke()` call. #### HTML ```html <canvas id="canvas"></canvas> ``` #### JavaScript The first line begins at (50, 50) and ends at (200, 50). The second line begins at (50, 90\) and ends at (280, 120). ```js const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); ctx.beginPath(); ctx.moveTo(50, 50); // Begin first sub-path ctx.lineTo(200, 50); ctx.moveTo(50, 90); // Begin second sub-path ctx.lineTo(280, 120); ctx.stroke(); ``` #### Result {{ EmbedLiveSample('Creating_multiple_sub-paths', 700, 180) }} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The interface defining this method: {{domxref("CanvasRenderingContext2D")}} - {{domxref("CanvasRenderingContext2D.lineTo()")}} - {{domxref("CanvasRenderingContext2D.stroke()")}}
0
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d/fillrect/index.md
--- title: "CanvasRenderingContext2D: fillRect() method" short-title: fillRect() slug: Web/API/CanvasRenderingContext2D/fillRect page-type: web-api-instance-method browser-compat: api.CanvasRenderingContext2D.fillRect --- {{APIRef}} The **`CanvasRenderingContext2D.fillRect()`** method of the Canvas 2D API draws a rectangle that is filled according to the current {{domxref("CanvasRenderingContext2D.fillStyle", "fillStyle")}}. This method draws directly to the canvas without modifying the current path, so any subsequent {{domxref("CanvasRenderingContext2D.fill()", "fill()")}} or {{domxref("CanvasRenderingContext2D.stroke()", "stroke()")}} calls will have no effect on it. ## Syntax ```js-nolint fillRect(x, y, width, height) ``` The `fillRect()` method draws a filled rectangle whose starting point is at `(x, y)` and whose size is specified by `width` and `height`. The fill style is determined by the current `fillStyle` attribute. ### Parameters - `x` - : The x-axis coordinate of the rectangle's starting point. - `y` - : The y-axis coordinate of the rectangle's starting point. - `width` - : The rectangle's width. Positive values are to the right, and negative to the left. - `height` - : The rectangle's height. Positive values are down, and negative are up. ### Return value None ({{jsxref("undefined")}}). ## Examples ### A simple filled rectangle This example draws a filled green rectangle using the `fillRect()` method. #### HTML ```html <canvas id="canvas"></canvas> ``` #### JavaScript The rectangle's top-left corner is at (20, 10). It has a width of 150 and a height of 100\. ```js const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); ctx.fillStyle = "green"; ctx.fillRect(20, 10, 150, 100); ``` #### Result {{ EmbedLiveSample('A_simple_filled_rectangle', 700, 180) }} ### Filling the whole canvas This code snippet fills the entire canvas with a rectangle. This is often useful for creating a background, on top of which other things may then be drawn. To achieve this, the dimensions of the rectangle are set to equal the {{HtmlElement("canvas")}} element's `width` and `height` attributes. ```js const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); ctx.fillRect(0, 0, canvas.width, canvas.height); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The interface defining this method: {{domxref("CanvasRenderingContext2D")}} - {{domxref("CanvasRenderingContext2D.fillStyle")}} - {{domxref("CanvasRenderingContext2D.clearRect()")}} - {{domxref("CanvasRenderingContext2D.strokeRect()")}}
0
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d/letterspacing/index.md
--- title: "CanvasRenderingContext2D: letterSpacing property" short-title: letterSpacing slug: Web/API/CanvasRenderingContext2D/letterSpacing page-type: web-api-instance-property browser-compat: api.CanvasRenderingContext2D.letterSpacing --- {{APIRef}} The **`CanvasRenderingContext2D.letterSpacing`** property of the [Canvas API](/en-US/docs/Web/API/Canvas_API) specifies the spacing between letters when drawing text. This corresponds to the CSS [`letter-spacing`](/en-US/docs/Web/CSS/letter-spacing) property. ## Value The letter spacing as a string in the CSS {{cssxref("length")}} data format. The default is `0px`. The property can be used to get or set the spacing. The property value will remain unchanged if set to an invalid/unparsable value. ## Examples In this example we display the text "Hello World" three times, using the `letterSpacing` property to modify the letter spacing in each case. The spacing is also displayed for each case, using the value of the property. ### HTML ```html <canvas id="canvas" width="700"></canvas> ``` ### JavaScript ```js const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); ctx.font = "30px serif"; // Default letter spacing ctx.fillText(`Hello world (default: ${ctx.letterSpacing})`, 10, 40); // Custom letter spacing: 10px ctx.letterSpacing = "10px"; ctx.fillText(`Hello world (${ctx.letterSpacing})`, 10, 90); // Custom letter spacing: 20px ctx.letterSpacing = "20px"; ctx.fillText(`Hello world (${ctx.letterSpacing})`, 10, 140); ``` ### Result {{ EmbedLiveSample('Examples', 700, 180) }} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("CanvasRenderingContext2D.wordSpacing")}}
0
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d/strokerect/index.md
--- title: "CanvasRenderingContext2D: strokeRect() method" short-title: strokeRect() slug: Web/API/CanvasRenderingContext2D/strokeRect page-type: web-api-instance-method browser-compat: api.CanvasRenderingContext2D.strokeRect --- {{APIRef}} The **`CanvasRenderingContext2D.strokeRect()`** method of the Canvas 2D API draws a rectangle that is stroked (outlined) according to the current {{domxref("CanvasRenderingContext2D.strokeStyle", "strokeStyle")}} and other context settings. This method draws directly to the canvas without modifying the current path, so any subsequent {{domxref("CanvasRenderingContext2D.fill()", "fill()")}} or {{domxref("CanvasRenderingContext2D.stroke()", "stroke()")}} calls will have no effect on it. ## Syntax ```js-nolint strokeRect(x, y, width, height) ``` The `strokeRect()` method draws a stroked rectangle 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 ({{jsxref("undefined")}}). ## Examples ### A simple stroked rectangle This example draws a rectangle with a green outline using the `strokeRect()` method. #### HTML ```html <canvas id="canvas"></canvas> ``` #### JavaScript The rectangle's top-left corner is at (20, 10). It has a width of 160 and a height of 100\. ```js const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); ctx.strokeStyle = "green"; ctx.strokeRect(20, 10, 160, 100); ``` #### Result {{ EmbedLiveSample('A_simple_stroked_rectangle', 700, 180) }} ### Applying various context settings This example draws a rectangle with a drop shadow and thick, beveled outlines. #### HTML ```html <canvas id="canvas"></canvas> ``` #### JavaScript ```js const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); ctx.shadowColor = "#d53"; ctx.shadowBlur = 20; ctx.lineJoin = "bevel"; ctx.lineWidth = 15; ctx.strokeStyle = "#38f"; ctx.strokeRect(30, 30, 160, 90); ``` #### Result {{ EmbedLiveSample('Applying_various_context_settings', 700, 180) }} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The interface defining this method: {{domxref("CanvasRenderingContext2D")}} - {{domxref("CanvasRenderingContext2D.strokeStyle")}} - {{domxref("CanvasRenderingContext2D.clearRect()")}} - {{domxref("CanvasRenderingContext2D.fillRect()")}}
0
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d/ispointinstroke/index.md
--- title: "CanvasRenderingContext2D: isPointInStroke() method" short-title: isPointInStroke() slug: Web/API/CanvasRenderingContext2D/isPointInStroke page-type: web-api-instance-method browser-compat: api.CanvasRenderingContext2D.isPointInStroke --- {{APIRef}} The **`CanvasRenderingContext2D.isPointInStroke()`** method of the Canvas 2D API reports whether or not the specified point is inside the area contained by the stroking of a path. ## Syntax ```js-nolint isPointInStroke(x, y) isPointInStroke(path, x, y) ``` ### Parameters - `x` - : The x-axis coordinate of the point to check. - `y` - : The y-axis coordinate of the point to check. - `path` - : A {{domxref("Path2D")}} path to check against. If unspecified, the current path is used. ### Return value - A boolean value - : A Boolean, which is `true` if the point is inside the area contained by the stroking of a path, otherwise `false`. ## Examples ### Checking a point in the current path This example uses the `isPointInStroke()` method to check if a point is within the area of the current path's stroke. #### HTML ```html <canvas id="canvas"></canvas> <p>In stroke: <code id="result">false</code></p> ``` #### JavaScript ```js const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); const result = document.getElementById("result"); ctx.rect(10, 10, 100, 100); ctx.stroke(); result.innerText = ctx.isPointInStroke(50, 10); ``` #### Result {{ EmbedLiveSample('Checking_a_point_in_the_current_path', 700, 220) }} ### Checking a point in the specified path Whenever you move the mouse, this example checks whether the cursor is in the stroke of an elliptical `Path2D` path. If yes, the ellipse's stroke becomes green, otherwise it is red. #### HTML ```html <canvas id="canvas"></canvas> ``` #### JavaScript ```js const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); // Create ellipse const ellipse = new Path2D(); ellipse.ellipse(150, 75, 40, 60, Math.PI * 0.25, 0, 2 * Math.PI); ctx.lineWidth = 25; ctx.strokeStyle = "red"; ctx.fill(ellipse); ctx.stroke(ellipse); // Listen for mouse moves canvas.addEventListener("mousemove", (event) => { // Check whether point is inside ellipse's stroke const isPointInStroke = ctx.isPointInStroke( ellipse, event.offsetX, event.offsetY, ); ctx.strokeStyle = isPointInStroke ? "green" : "red"; // Draw ellipse ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.fill(ellipse); ctx.stroke(ellipse); }); ``` #### Result {{ EmbedLiveSample('Checking_a_point_in_the_specified_path', 700, 180) }} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The interface defining this method: {{domxref("CanvasRenderingContext2D")}}
0
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d/stroke/index.md
--- title: "CanvasRenderingContext2D: stroke() method" short-title: stroke() slug: Web/API/CanvasRenderingContext2D/stroke page-type: web-api-instance-method browser-compat: api.CanvasRenderingContext2D.stroke --- {{APIRef}} The **`CanvasRenderingContext2D.stroke()`** method of the Canvas 2D API strokes (outlines) the current or given path with the current stroke style. Strokes are aligned to the center of a path; in other words, half of the stroke is drawn on the inner side, and half on the outer side. The stroke is drawn using the [non-zero winding rule](https://en.wikipedia.org/wiki/Nonzero-rule), which means that path intersections will still get filled. ## Syntax ```js-nolint stroke() stroke(path) ``` ### Parameters - `path` - : A {{domxref("Path2D")}} path to stroke. ### Return value None ({{jsxref("undefined")}}). ## Examples ### A simple stroked rectangle This example creates a rectangle using the `rect()` method, and then draws it to the canvas using `stroke()`. #### HTML ```html <canvas id="canvas"></canvas> ``` #### JavaScript ```js const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); ctx.rect(10, 10, 150, 100); ctx.stroke(); ``` #### Result {{ EmbedLiveSample('A_simple_stroked_rectangle', 700, 180) }} ### Re-stroking paths Typically, you'll want to call {{domxref("CanvasRenderingContext2D.beginPath()", "beginPath()")}} for each new thing you want to stroke. If you don't, the previous sub-paths will remain part of the current path, and get stroked every time you call the `stroke()` method. In some cases, however, this may be the desired effect. #### HTML ```html <canvas id="canvas"></canvas> ``` #### JavaScript This code strokes the first path three times, the second path two times, and the third path only once. ```js const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); // First sub-path ctx.lineWidth = 26; ctx.strokeStyle = "orange"; ctx.moveTo(20, 20); ctx.lineTo(160, 20); ctx.stroke(); // Second sub-path ctx.lineWidth = 14; ctx.strokeStyle = "green"; ctx.moveTo(20, 80); ctx.lineTo(220, 80); ctx.stroke(); // Third sub-path ctx.lineWidth = 4; ctx.strokeStyle = "pink"; ctx.moveTo(20, 140); ctx.lineTo(280, 140); ctx.stroke(); ``` #### Result {{ EmbedLiveSample('Re-stroking_paths', 700, 180) }} ### Stroking and filling If you want to both stroke and fill a path, the order in which you perform these actions will determine the result. In this example, the square on the left is drawn with the stroke on top of the fill. The square on the right is drawn with the fill on top of the stroke. #### HTML ```html <canvas id="canvas"></canvas> ``` #### JavaScript ```js const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); ctx.lineWidth = 16; ctx.strokeStyle = "red"; // Stroke on top of fill ctx.beginPath(); ctx.rect(25, 25, 100, 100); ctx.fill(); ctx.stroke(); // Fill on top of stroke ctx.beginPath(); ctx.rect(175, 25, 100, 100); ctx.stroke(); ctx.fill(); ``` #### Result {{ EmbedLiveSample('Stroking_and_filling', 700, 180) }} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The interface defining this method: {{domxref("CanvasRenderingContext2D")}}
0
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d/textbaseline/index.md
--- title: "CanvasRenderingContext2D: textBaseline property" short-title: textBaseline slug: Web/API/CanvasRenderingContext2D/textBaseline page-type: web-api-instance-property browser-compat: api.CanvasRenderingContext2D.textBaseline --- {{APIRef}} The **`CanvasRenderingContext2D.textBaseline`** property of the Canvas 2D API specifies the current text baseline used when drawing text. ## Value Possible values: - `"top"` - : The text baseline is the top of the em square. - `"hanging"` - : The text baseline is the hanging baseline. (Used by Tibetan and other Indic scripts.) - `"middle"` - : The text baseline is the middle of the em square. - `"alphabetic"` - : The text baseline is the normal alphabetic baseline. Default value. - `"ideographic"` - : The text baseline is the ideographic baseline; this is the bottom of the body of the characters, if the main body of characters protrudes beneath the alphabetic baseline. (Used by Chinese, Japanese, and Korean scripts.) - `"bottom"` - : The text baseline is the bottom of the bounding box. This differs from the ideographic baseline in that the ideographic baseline doesn't consider descenders. The default value is `"alphabetic"`. ## Examples ### Comparison of property values This example demonstrates the various `textBaseline` property values. #### HTML ```html <canvas id="canvas" width="550" height="500"></canvas> ``` #### JavaScript ```js const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); const baselines = [ "top", "hanging", "middle", "alphabetic", "ideographic", "bottom", ]; ctx.font = "36px serif"; ctx.strokeStyle = "red"; baselines.forEach((baseline, index) => { ctx.textBaseline = baseline; const y = 75 + index * 75; ctx.beginPath(); ctx.moveTo(0, y + 0.5); ctx.lineTo(550, y + 0.5); ctx.stroke(); ctx.fillText(`Abcdefghijklmnop (${baseline})`, 0, y); }); ``` #### Result {{ EmbedLiveSample('Comparison_of_property_values', 700, 550) }} ### Comparison of property values on the same line As with the previous example, this example demonstrates the various `textBaseline` property values, but in this case with all of them lined up horizontally along the same line — to make it easier to see how they differ from each other. #### HTML ```html <canvas id="canvas" width="724" height="160"></canvas> ``` #### JavaScript ```js const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); const baselines = [ "top", "hanging", "middle", "alphabetic", "ideographic", "bottom", ]; ctx.font = "20px serif"; ctx.strokeStyle = "red"; ctx.beginPath(); ctx.moveTo(0, 100); ctx.lineTo(840, 100); ctx.moveTo(0, 55); ctx.stroke(); baselines.forEach((baseline, index) => { ctx.save(); ctx.textBaseline = baseline; let x = index * 120 + 10; ctx.fillText("Abcdefghijk", x, 100); ctx.restore(); ctx.fillText(baseline, x + 5, 50); }); ``` #### Result {{ EmbedLiveSample('Comparison of property values on the same line', 900, 200) }} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The interface defining this property: {{domxref("CanvasRenderingContext2D")}}
0
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d/createradialgradient/index.md
--- title: "CanvasRenderingContext2D: createRadialGradient() method" short-title: createRadialGradient() slug: Web/API/CanvasRenderingContext2D/createRadialGradient page-type: web-api-instance-method browser-compat: api.CanvasRenderingContext2D.createRadialGradient --- {{APIRef}} The **`CanvasRenderingContext2D.createRadialGradient()`** method of the Canvas 2D API creates a radial gradient using the size and coordinates of two circles. This method returns a {{domxref("CanvasGradient")}}. To be applied to a shape, the gradient must first be assigned to the {{domxref("CanvasRenderingContext2D.fillStyle", "fillStyle")}} or {{domxref("CanvasRenderingContext2D.strokeStyle", "strokeStyle")}} properties. > **Note:** Gradient coordinates are global, i.e., relative to the current > coordinate space. When applied to a shape, the coordinates are NOT relative to the > shape's coordinates. ## Syntax ```js-nolint createRadialGradient(x0, y0, r0, x1, y1, r1) ``` The `createRadialGradient()` method is specified by six parameters, three defining the gradient's start circle, and three defining the end circle. ### Parameters - `x0` - : The x-axis coordinate of the start circle. - `y0` - : The y-axis coordinate of the start circle. - `r0` - : The radius of the start circle. Must be non-negative and finite. - `x1` - : The x-axis coordinate of the end circle. - `y1` - : The y-axis coordinate of the end circle. - `r1` - : The radius of the end circle. Must be non-negative and finite. ### Return value A radial {{domxref("CanvasGradient")}} initialized with the two specified circles. ### Exceptions - `NotSupportedError` {{domxref("DOMException")}} - : Thrown when non-finite values are passed in parameter. - `IndexSizeError` {{domxref("DOMException")}} - : Thrown when a negative radius is passed in parameter. ## Examples ### Filling a rectangle with a radial gradient This example initializes a radial gradient using the `createRadialGradient()` method. Three color stops between the gradient's two circles are then created. Finally, the gradient is assigned to the canvas context, and is rendered to a filled rectangle. #### HTML ```html <canvas id="canvas" width="200" height="200"></canvas> ``` #### JavaScript ```js const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); // Create a radial gradient // The inner circle is at x=110, y=90, with radius=30 // The outer circle is at x=100, y=100, with radius=70 const gradient = ctx.createRadialGradient(110, 90, 30, 100, 100, 70); // Add three color stops gradient.addColorStop(0, "pink"); gradient.addColorStop(0.9, "white"); gradient.addColorStop(1, "green"); // Set the fill style and draw a rectangle ctx.fillStyle = gradient; ctx.fillRect(20, 20, 160, 160); ``` #### Result {{ EmbedLiveSample('Filling_a_rectangle_with_a_radial_gradient', 700, 240) }} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The interface defining this method: {{domxref("CanvasRenderingContext2D")}} - {{domxref("CanvasRenderingContext2D.createLinearGradient()")}} - {{domxref("CanvasRenderingContext2D.createConicGradient()")}}
0
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d/fontkerning/index.md
--- title: "CanvasRenderingContext2D: fontKerning property" short-title: fontKerning slug: Web/API/CanvasRenderingContext2D/fontKerning page-type: web-api-instance-property browser-compat: api.CanvasRenderingContext2D.fontKerning --- {{APIRef}} The **`CanvasRenderingContext2D.fontKerning`** property of the [Canvas API](/en-US/docs/Web/API/Canvas_API) specifies how font kerning information is used. Kerning adjusts how adjacent letters are spaced in a proportional font, allowing them to edge into each other's visual area if there is space available. For example, in well-kerned fonts, the characters `AV`, `Ta` and `We` nest together and make character spacing more uniform and pleasant to read than the equivalent text without kerning. The property corresponds to the [`font-kerning`](/en-US/docs/Web/CSS/font-kerning) CSS property. ## Value The property can be used to get or set the value. Allowed values are: - `auto` - : The browser determines whether font kerning should be used or not. For example, some browsers will disable kerning on small fonts, since applying it could harm the readability of text. - `normal` - : Font kerning information stored in the font must be applied. - `none` - : Font kerning information stored in the font is disabled. ## Examples In this example we display the text "AVA Ta We" using each of the supported values of the `textRendering` property. ### HTML ```html <canvas id="canvas" width="700" height="140"></canvas> ``` ### JavaScript ```js const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); ctx.font = "30px serif"; // Default (auto) ctx.fillText(`AVA Ta We (default: ${ctx.fontKerning})`, 5, 30); // Font kerning: normal ctx.fontKerning = "normal"; ctx.fillText(`AVA Ta We (${ctx.fontKerning})`, 5, 70); // Font kerning: none ctx.fontKerning = "none"; ctx.fillText(`AVA Ta We (${ctx.fontKerning})`, 5, 110); ``` ### Result Note that the last string has font kerning disabled, so adjacent characters are evenly spread. {{ EmbedLiveSample('Examples', 700, 150) }} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d/transform/index.md
--- title: "CanvasRenderingContext2D: transform() method" short-title: transform() slug: Web/API/CanvasRenderingContext2D/transform page-type: web-api-instance-method browser-compat: api.CanvasRenderingContext2D.transform --- {{APIRef}} The **`CanvasRenderingContext2D.transform()`** method of the Canvas 2D API multiplies the current transformation with the matrix described by the arguments of this method. This lets you scale, rotate, translate (move), and skew the context. > **Note:** See also the > {{domxref("CanvasRenderingContext2D.setTransform()", "setTransform()")}} method, which > resets the current transform to the identity matrix and then invokes > `transform()`. ## Syntax ```js-nolint transform(a, b, c, d, e, f) ``` The transformation matrix is described by: <math><semantics><mrow><mo>[</mo> <mtable columnalign="center center center" rowspacing="0.5ex"><mtr><mtd><mi>a</mi> </mtd><mtd><mi>c</mi> </mtd><mtd><mi>e</mi> </mtd></mtr><mtr><mtd><mi>b</mi> </mtd><mtd><mi>d</mi> </mtd><mtd><mi>f</mi> </mtd></mtr><mtr><mtd><mn>0</mn> </mtd><mtd><mn>0</mn> </mtd><mtd><mn>1</mn> </mtd></mtr></mtable><mo>]</mo> </mrow><annotation encoding="TeX">\left[ \begin{array}{ccc} a &#x26; c &#x26; e \\ b &#x26; d &#x26; f \\ 0 &#x26; 0 &#x26; 1 \end{array} \right]</annotation></semantics></math> ### Parameters - `a` (`m11`) - : The cell in the first row and first column of the matrix. - `b` (`m12`) - : The cell in the second row and first column of the matrix. - `c` (`m21`) - : The cell in the first row and second column of the matrix. - `d` (`m22`) - : The cell in the second row and second column of the matrix. - `e` (`m41`) - : The cell in the first row and third column of the matrix. - `f` (`m42`) - : The cell in the second row and third column of the matrix. If a point originally had coordinates <math><semantics><mrow><mo>(</mo><mi>x</mi><mo>,</mo><mi>y</mi><mo>)</mo></mrow><annotation encoding="TeX">(x, y)</annotation></semantics></math>, then after the transformation it will have coordinates <math><semantics><mrow><mo>(</mo><mi>a</mi><mi>x</mi><mo>+</mo><mi>c</mi><mi>y</mi><mo>+</mo><mi>e</mi><mo>,</mo><mi>b</mi><mi>x</mi><mo>+</mo><mi>d</mi><mi>y</mi><mo>+</mo><mi>f</mi><mo>)</mo></mrow><annotation encoding="TeX">(ax + cy + e, bx + dy + f)</annotation></semantics></math>. This means: - `e` and `f` control the horizontal and vertical translation of the context. - When `b` and `c` are `0`, `a` and `d` control the horizontal and vertical scaling of the context. - When `a` and `d` are `1`, `b` and `c` control the horizontal and vertical skewing of the context. ### Return value None ({{jsxref("undefined")}}). ## Examples ### Skewing a shape This example skews a rectangle both vertically (`.2`) and horizontally (`.8`). Scaling and translation remain unchanged. #### HTML ```html <canvas id="canvas"></canvas> ``` #### JavaScript ```js const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); ctx.transform(1, 0.2, 0.8, 1, 0, 0); ctx.fillRect(0, 0, 100, 100); ``` #### Result {{ EmbedLiveSample('Skewing_a_shape', 700, 180) }} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The interface defining this method: {{domxref("CanvasRenderingContext2D")}} - {{domxref("CanvasRenderingContext2D.setTransform()")}}
0
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d/shadowoffsetx/index.md
--- title: "CanvasRenderingContext2D: shadowOffsetX property" short-title: shadowOffsetX slug: Web/API/CanvasRenderingContext2D/shadowOffsetX page-type: web-api-instance-property browser-compat: api.CanvasRenderingContext2D.shadowOffsetX --- {{APIRef}} The **`CanvasRenderingContext2D.shadowOffsetX`** property of the Canvas 2D API specifies the distance that shadows will be offset horizontally. > **Note:** Shadows are only drawn if the > {{domxref("CanvasRenderingContext2D.shadowColor", "shadowColor")}} property is set to > a non-transparent value. One of the {{domxref("CanvasRenderingContext2D.shadowBlur", "shadowBlur")}}, `shadowOffsetX`, or > {{domxref("CanvasRenderingContext2D.shadowOffsetY", "shadowOffsetY")}} properties must > be non-zero, as well. ## Value A float specifying the distance that shadows will be offset horizontally. Positive values are to the right, and negative to the left. The default value is `0` (no horizontal offset). {{jsxref("Infinity")}} and {{jsxref("NaN")}} values are ignored. ## Examples ### Moving a shadow horizontally This example adds a blurred shadow to a rectangle. The {{domxref("CanvasRenderingContext2D.shadowColor", "shadowColor")}} property sets its color, `shadowOffsetX` sets its offset 25 units to the right, and {{domxref("CanvasRenderingContext2D.shadowBlur", "shadowBlur")}} gives it a blur level of 10. #### HTML ```html <canvas id="canvas"></canvas> ``` #### JavaScript ```js const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); // Shadow ctx.shadowColor = "red"; ctx.shadowOffsetX = 25; ctx.shadowBlur = 10; // Rectangle ctx.fillStyle = "blue"; ctx.fillRect(20, 20, 150, 100); ``` #### Result {{ EmbedLiveSample('Moving_a_shadow_horizontally', 700, 180) }} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The interface defining this property: {{domxref("CanvasRenderingContext2D")}} - {{domxref("CanvasRenderingContext2D.shadowOffsetY")}} - {{domxref("CanvasRenderingContext2D.shadowColor")}} - {{domxref("CanvasRenderingContext2D.shadowBlur")}}
0
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d/createconicgradient/index.md
--- title: "CanvasRenderingContext2D: createConicGradient() method" short-title: createConicGradient() slug: Web/API/CanvasRenderingContext2D/createConicGradient page-type: web-api-instance-method browser-compat: api.CanvasRenderingContext2D.createConicGradient --- {{APIRef}} The **`CanvasRenderingContext2D.createConicGradient()`** method of the Canvas 2D API creates a gradient around a point with given coordinates. This method returns a conic {{domxref("CanvasGradient")}}. To be applied to a shape, the gradient must first be assigned to the {{domxref("CanvasRenderingContext2D.fillStyle", "fillStyle")}} or {{domxref("CanvasRenderingContext2D.strokeStyle", "strokeStyle")}} properties. > **Note:** Gradient coordinates are global, i.e., relative to the current coordinate space. When applied to a shape, the coordinates are NOT relative to the shape's coordinates. ## Syntax ```js-nolint createConicGradient(startAngle, x, y) ``` ### Parameters - `startAngle` - : The angle at which to begin the gradient, in radians. The angle starts from a line going horizontally right from the center, and proceeds clockwise. - `x` - : The x-axis coordinate of the center of the gradient. - `y` - : The y-axis coordinate of the center of the gradient. ### Return value - {{domxref("CanvasGradient")}} - : A conic `CanvasGradient`. ## Examples ### Filling a rectangle with a conic gradient This example initializes a conic gradient using the `createConicGradient()` method. Five color stops between around the center coordinate are then created. Finally, the gradient is assigned to the canvas context, and is rendered to a filled rectangle. #### HTML ```html <canvas id="canvas" width="240" height="240"></canvas> ``` #### JavaScript ```js const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); // Create a conic gradient // The start angle is 0 // The center position is 100, 100 const gradient = ctx.createConicGradient(0, 100, 100); // Add five color stops gradient.addColorStop(0, "red"); gradient.addColorStop(0.25, "orange"); gradient.addColorStop(0.5, "yellow"); gradient.addColorStop(0.75, "green"); gradient.addColorStop(1, "blue"); // Set the fill style and draw a rectangle ctx.fillStyle = gradient; ctx.fillRect(20, 20, 200, 200); ``` #### Rectangle result {{ EmbedLiveSample('Filling_a_rectangle_with_a_conic_gradient', 240, 240) }} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The interface defining this method: {{domxref("CanvasRenderingContext2D")}} - {{domxref("CanvasGradient")}} - {{domxref("CanvasRenderingContext2D.createLinearGradient()")}} - {{domxref("CanvasRenderingContext2D.createRadialGradient()")}}
0
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d/arcto/index.md
--- title: "CanvasRenderingContext2D: arcTo() method" short-title: arcTo() slug: Web/API/CanvasRenderingContext2D/arcTo page-type: web-api-instance-method browser-compat: api.CanvasRenderingContext2D.arcTo --- {{APIRef}} The **`CanvasRenderingContext2D.arcTo()`** method of the Canvas 2D API adds a circular arc to the current sub-path, using the given control points and radius. The arc is automatically connected to the path's latest point with a straight line if necessary, for example if the starting point and control points are in a line. This method is commonly used for making rounded corners. > **Note:** You may get unexpected results when using a > relatively large radius: the arc's connecting line will go in whatever direction it > must to meet the specified radius. ## Syntax ```js-nolint arcTo(x1, y1, x2, y2, radius) ``` ### Parameters - `x1` - : The x-axis coordinate of the first control point. - `y1` - : The y-axis coordinate of the first control point. - `x2` - : The x-axis coordinate of the second control point. - `y2` - : The y-axis coordinate of the second control point. - `radius` - : The arc's radius. Must be non-negative. #### Usage notes Assume <em>P<sub>0</sub></em> is the point on the path when `arcTo()` is called, <em>P<sub>1</sub></em> = (`x1`, `y1`) and <em>P<sub>2</sub></em> = (`x2`, `y2`) are the first and second control points, respectively, and _r_ is the `radius` specified in the call: - If _r_ is negative, an `IndexSizeError` [exception](#exceptions) is raised. - If _r_ is 0, `arcTo()` behaves as if <em>P<sub>0</sub></em>, <em>P<sub>1</sub></em>, and <em>P<sub>2</sub></em> are collinear (in a line). - In the case of all of the points being collinear, a line from <em>P<sub>0</sub></em> to <em>P<sub>1</sub></em> is drawn unless the points <em>P<sub>0</sub></em> and <em>P<sub>1</sub></em> are coincident (having the same coordinates), in which case nothing is drawn. These conditions can be created in the [Constructing an arcTo() path](#constructing_an_arcto_path) example below to see the results. ### Return value None ({{jsxref("undefined")}}). ### Exceptions - `IndexSizeError` {{domxref("DOMException")}} - : Thrown if `radius` is a negative value. ## Examples ### How `arcTo()` works One way to think about `arcTo()` is to imagine two straight segments: one from the starting point to a first control point, and another from there to a second control point. Without `arcTo()`, these two segments would form a sharp corner: `arcTo()` creates a circular arc at this corner and smooths it out. In other words, the arc is tangential to both segments. #### HTML ```html <canvas id="canvas"></canvas> ``` #### JavaScript ```js const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); // Tangential lines ctx.beginPath(); ctx.strokeStyle = "gray"; ctx.moveTo(200, 20); ctx.lineTo(200, 130); ctx.lineTo(50, 20); ctx.stroke(); // Arc ctx.beginPath(); ctx.strokeStyle = "black"; ctx.lineWidth = 5; ctx.moveTo(200, 20); ctx.arcTo(200, 130, 50, 20, 40); ctx.stroke(); // Start point ctx.beginPath(); ctx.fillStyle = "blue"; ctx.arc(200, 20, 5, 0, 2 * Math.PI); ctx.fill(); // Control points ctx.beginPath(); ctx.fillStyle = "red"; ctx.arc(200, 130, 5, 0, 2 * Math.PI); // Control point one ctx.arc(50, 20, 5, 0, 2 * Math.PI); // Control point two ctx.fill(); ``` #### Result In this example, the path created by `arcTo()` is **thick and black**. Tangent lines are gray, control points are red, and the start point is blue. {{ EmbedLiveSample('How_arcTo_works', 315, 170) }} ### Creating a rounded corner This example creates a rounded corner using `arcTo()`. This is one of the method's most common uses. #### HTML ```html <canvas id="canvas"></canvas> ``` #### JavaScript The arc begins at the point specified by `moveTo()`: (230, 20). It is shaped to fit control points at (90, 130) and (20, 20), and has a radius of 50. The `lineTo()` method connects the arc to (20, 20) with a straight line. Note that the arc's second control point and the point specified by `lineTo()` are the same, which produces a totally smooth corner. ```js const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); const p0 = { x: 230, y: 20 }; const p1 = { x: 90, y: 130 }; const p2 = { x: 20, y: 20 }; const labelPoint = (p) => { const offset = 10; ctx.fillText(`(${p.x},${p.y})`, p.x + offset, p.y + offset); }; ctx.beginPath(); ctx.lineWidth = 4; ctx.font = "1em sans-serif"; ctx.moveTo(p0.x, p0.y); ctx.arcTo(p1.x, p1.y, p2.x, p2.y, 50); ctx.lineTo(p2.x, p2.y); labelPoint(p0); labelPoint(p1); labelPoint(p2); ctx.stroke(); ``` #### Result {{ EmbedLiveSample('Creating_a_rounded_corner', 315, 165) }} ### Result of a large radius If you use a relatively large radius, the arc may appear in a place you didn't expect. In this example, the arc's connecting line goes above, instead of below, the coordinate specified by `moveTo()`. This happens because the radius is too large for the arc to fit entirely below the starting point. #### HTML ```html <canvas id="canvas"></canvas> ``` #### JavaScript ```js const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); ctx.beginPath(); ctx.moveTo(180, 90); ctx.arcTo(180, 130, 110, 130, 130); ctx.lineTo(110, 130); ctx.stroke(); ``` #### Result {{ EmbedLiveSample('Result_of_a_large_radius', 315, 165) }} ### Constructing an arcTo() path The demo shows the semi-infinite lines and circle with center _C_ tangent to the lines at <em>T<sub>1</sub></em> and <em>T<sub>2</sub></em> used to determine the path rendered by `arcTo()`. Note that `arcTo` will create a straight line from <em>P<sub>0</sub></em> to <em>P<sub>1</sub></em> when all points are in a line. Additionally, nothing is drawn by `arcTo` if <em>P<sub>0</sub></em> and <em>P<sub>1</sub></em> have the same coordinates. Besides being able to set the arc radius with the slider, the initial point <em>P<sub>0</sub></em> and control points <em>P<sub>1</sub></em> and <em>P<sub>2</sub></em> can be moved by dragging them with the mouse with the left button down. The numeric values can also be edited, and the arrow keys can be used to change an underlined element that is in focus. ```html hidden <div> <label for="arc-radius">arc radius <em>r</em></label> <input name="arc-radius" type="range" id="radius-slider" min="0" /> <label for="arc-radius" id="value-r" class="input" contenteditable="true"></label> </div> <div> <span id="value-P0" class="input" tabindex="0"> <em>P<sub>0</sub></em> </span> = (<span id="value-P0x" class="input" contenteditable="true"></span>, <span id="value-P0y" class="input" contenteditable="true"></span>) &nbsp;&nbsp; <span id="value-P1" class="input" tabindex="0"> <em>P<sub>1</sub></em> </span> = (<span id="value-P1x" class="input" contenteditable="true"></span>, <span id="value-P1y" class="input" contenteditable="true"></span>) &nbsp;&nbsp; <span id="value-P2" class="input" tabindex="0"> <em>P<sub>2</sub></em> </span> = (<span id="value-P2x" class="input" contenteditable="true"></span>, <span id="value-P2y" class="input" contenteditable="true"></span>) </div> <canvas id="canvas"></canvas> <div> <em>T<sub>1</sub></em> = <span id="value-T1"></span> </div> <div> <em>T<sub>2</sub></em> = <span id="value-T2"></span> </div> <div><em>C</em> = <span id="value-C"></span></div> <script> /* arcTo() demo * Note: there are browser issues at least in Chrome regarding cursor * updates. See * https://stackoverflow.com/questions/37462132/update-mouse-cursor-without-moving-mouse-with-changed-css-cursor-property * * Cursor problems were also seen when text was selected before entering * the canvas. Additional tests which may appear to be redundant in the * code minimized these issues. */ "use strict"; /* Parameters for demo */ const param = { canvasWidth: 300, // canvas size canvasHeight: 300, hitDistance: 5, // mouse distance to be considered a hit errorTolCenter: 1e-4, // limit on circle center differences radiusMax: 250, // largest allowed radius P0x: 50, // initial point P0y: 50, P1x: 275, // First control point P1y: 150, P2x: 50, // Second control point P2y: 275, radius: 75, // radius of arc }; /* Some math for 2-D vectors */ class Math2D { /* Create new point */ static point(x = 0, y = 0) { return { x: x, y: y }; } /* Create new vector */ static vector(x = 0, y = 0) { return this.point(x, y); } /* Subtraction: difference = minuend - subtrahend */ static subtract(difference, minuend, subtrahend) { difference.x = minuend.x - subtrahend.x; difference.y = minuend.y - subtrahend.y; } /* Find L2 norm */ static L2(a) { return Math.hypot(a.x, a.y); } /* Dot product */ static dot(a, b) { return a.x * b.x + a.y * b.y; } /* Find point on line defined parametrically by * L = P0 + t * direction */ static linePointAt(P0, t, dir) { return this.point(P0.x + t * dir.x, P0.y + t * dir.y); } } /* end of class Math2D */ /* Text values allowing alternate inputs */ class TextInput { #valueMax; #callbackKeydown; #callbackFocus; /* Mutation observer to watch the focused text input */ static mo = new MutationObserver(TextInput.processInput); static moOptions = { subtree: true, // character data in internal node characterData: true, }; /* Symbol to add index information to mutation observer */ static symbolTextInput = Symbol("textInput"); /* Handler for mutations of focused text input */ static processInput(mrs, mo) { /* Access textInput object associated with the mutations */ const textInput = mo[TextInput.symbolTextInput]; /* Find the character data mutation and update based on the input */ for (let i = 0, n = mrs.length; i < n; i++) { const mr = mrs[i]; if (mr.type === "characterData") { const target = mr.target; if (target.nodeType !== 3) { console.error( "Mutation record type CharacterData but " + "node type = " + target.nodeType, ); return; } /* Handle non-digits entered by parsing */ let value = parseInt(target.textContent); value = isNaN(value) ? 0 : value; textInput.updateFull(value); break; } } } constructor( idText, // id of element in document idControl, // id of control in element, if any (radius ony) valueMax, // allowed values from 0 to maxValue, inclusive getStateValue, // function to get value from state object setStateValue, ) { // function to set value on state object this.#valueMax = valueMax; this.elementText = document.getElementById(idText); this.elementControl = idControl === null ? null : document.getElementById(idControl); this.getStateValue = getStateValue; this.setStateValue = setStateValue; this.#callbackKeydown = (evt) => { let valueInput; switch (evt.keyCode) { case 13: // enter -- do not allow since adds <br> nodes evt.preventDefault(); return; case 38: // up arrow valueInput = Number(this.elementText.textContent) + 1; evt.preventDefault(); break; case 40: // down arrow valueInput = Number(this.elementText.textContent) - 1; evt.preventDefault(); break; default: // ignore all others return; } TextInput.mo.disconnect(); // suspend while changing value this.updateFull(valueInput); // do update const options = { subtree: true, characterData: true }; TextInput.mo.observe(this.elementText, TextInput.moOptions); // observe again }; this.#callbackFocus = (evt) => { /* Link mutation observer to the associated text input object */ TextInput.mo[TextInput.symbolTextInput] = this; /* Look for changes in the input. * subtree: true needed since text is in internal node(s) * childList: true needed since <enter> becomes a <br> node */ TextInput.mo.observe(this.elementText, TextInput.moOptions); /* Check for up and down arrows to increment/decrement values */ this.elementText.addEventListener("keydown", this.#callbackKeydown); /* When focus is lost, stop watching this input */ this.elementText.addEventListener("blur", () => { this.elementText.removeEventListener( "keydown", this.#callbackKeydown, ); TextInput.mo.disconnect(); }); }; this.elementText.addEventListener("focus", this.#callbackFocus); } // end of class TextInput /* Function to update based on input received from text input source */ updateFull(value) { /* Clamp value in range */ if (value > this.#valueMax) { value = this.#valueMax; } else if (value < 0) { value = 0; } /* Make consistent and update */ const valueTextPrev = this.elementText.textContent; const valueString = String(value); if (valueTextPrev !== valueString) { this.elementText.textContent = valueString; } if (this.elementControl) { const valueControlPrev = this.elementControl.value; if (valueControlPrev !== valueString) { this.elementControl.value = valueString; } } const valueStatePrev = this.getStateValue(); if (valueStatePrev !== value) { // input caused state change this.setStateValue(value); updateResults(); } } } /* end of class TextInput */ /* Given configuration parameters, initialize the state */ function initDemoState({ canvasWidth = 300, canvasHeight = 300, hitDistance = 5, errorTolCenter = 1e-4, radiusMax = 250, P0x = 0, P0y = 0, P1x = 0, P1y = 0, P2x = 0, P2y = 0, radius = 0, } = {}) { const s = {}; s.controlPoints = [ Math2D.point(P0x, P0y), Math2D.point(P1x, P1y), Math2D.point(P2x, P2y), ]; s.hitDistance = hitDistance; s.errorTolCenter = errorTolCenter; s.canvasSize = Math2D.point(canvasWidth, canvasHeight); if (radius > radiusMax) { /* limit param to allowed values */ radius = radiusMax; } s.radius = radius; s.radiusMax = radiusMax; [s.haveCircle, s.P0Inf, s.P2Inf, s.T1, s.T2, s.C] = findConstruction( s.controlPoints, s.radius, s.canvasSize, s.errorTolCenter, ); s.pointActiveIndex = -1; // no point currently active s.pointActiveMoving = false; // Active point hovering (false) or // moving (true) s.mouseDelta = Math2D.point(); // offset of mouse pointer //from point center return s; } function updateResults() { updateConstruction(); drawCanvas(); ConstructionPoints.print(state.T1, state.T2, state.C); } function updateConstruction() { [state.haveCircle, state.P0Inf, state.P2Inf, state.T1, state.T2, state.C] = findConstruction( state.controlPoints, state.radius, state.canvasSize, state.errorTolCenter, ); } /* Find the geometry that arcTo() uses to draw the path */ function findConstruction([P0, P1, P2], r, canvasSize, errorTolCenter) { /* Find the center of a circle of radius r having a point T with a * tangent in the direction d and the center on the same side of * the tangent as dirTan. */ function findCenter(T, d, r, dirTan) { /* Find direction of line normal to tangent line * Taking larger value to avoid division by 0. * a . n = 0. Set smaller component to 1 */ const dn = Math.abs(d.x) < Math.abs(d.y) ? Math2D.point(1, -d.x / d.y) : Math2D.point(-d.y / d.x, 1); /* The normal may be pointing towards center or away. * Make towards center if not */ if (Math2D.dot(dn, dirTan) < 0) { dn.x = -dn.x; dn.y = -dn.y; } /* Move a distance of the radius along line Tx + t * dn * to get to the center of the circle */ return Math2D.linePointAt(T, r / Math2D.L2(dn), dn); } /* Test for coincidence. Note that points will have small integer * coordinates, so there is no issue with checking for exact * equality */ const dir1 = Math2D.vector(P0.x - P1.x, P0.y - P1.y); // dir line 1 if (dir1.x === 0 && dir1.y === 0) { // P0 and P1 coincident return [false]; } const dir2 = Math2D.vector(P2.x - P1.x, P2.y - P1.y); // dir of line 2 if (dir2.x === 0 && dir2.y === 0) { // P2 and P1 coincident return [false]; } /* Magnitudes of direction vectors defining lines */ const dir1Mag = Math2D.L2(dir1); const dir2Mag = Math2D.L2(dir2); /* Make direction vectors unit length */ const dir1_unit = Math2D.vector(dir1.x / dir1Mag, dir1.y / dir1Mag); const dir2_unit = Math2D.vector(dir2.x / dir2Mag, dir2.y / dir2Mag); /* Angle between lines -- cos angle = a.b/(|a||b|) * Using unit vectors, so |a| = |b| = 1 */ const dp = Math2D.dot(dir1_unit, dir2_unit); /* Test for collinearity */ if (Math.abs(dp) > 0.999999) { /* Angle 0 or 180 degrees, or nearly so */ return [false]; } const angle = Math.acos(Math2D.dot(dir1_unit, dir2_unit)); /* Distance to tangent points from P1 -- * (T1, P1, C) form a right triangle (T2, P1, C) same triangle. * An angle of each triangle is half of the angle between the lines * tan(angle/2) = r / length(P1,T1) */ const distToTangent = r / Math.tan(0.5 * angle); /* Locate tangent points */ const T1 = Math2D.linePointAt(P1, distToTangent, dir1_unit); const T2 = Math2D.linePointAt(P1, distToTangent, dir2_unit); /* Center is along normal to tangent at tangent point at * a distance equal to the radius of the circle. * Locate center two ways. Should be equal */ const dirT2_T1 = Math2D.vector(T2.x - T1.x, T2.y - T1.y); const dirT1_T2 = Math2D.vector(-dirT2_T1.x, -dirT2_T1.y); const C1 = findCenter(T1, dir1_unit, r, dirT2_T1); const C2 = findCenter(T2, dir2_unit, r, dirT1_T2); /* Error in center calculations */ const deltaC = Math2D.vector(C2.x - C1.x, C2.y - C1.y); if (deltaC.x * deltaC.x + deltaC.y * deltaC.y > errorTolCenter) { console.error( `Programming or numerical error, ` + `P0(${P0.x},${P0.y}); ` + `P1(${P1.x},${P1.y}); ` + `P2(${P2.x},${P2.y}); ` + `r=${r};`, ); } /* Average the center values */ const C = Math2D.point(C1.x + 0.5 * deltaC.x, C1.y + 0.5 * deltaC.y); /* Find the "infinite values" of the two semi-infinite lines. * As a practical consideration, anything off the canvas is * infinite. A distance equal to the height + width of the canvas * is assured to be sufficiently far away and has the advantage of * being easily found. */ const distToInf = canvasSize.x + canvasSize.y; const L1inf = Math2D.linePointAt(P1, distToInf, dir1_unit); const L2inf = Math2D.linePointAt(P1, distToInf, dir2_unit); return [true, L1inf, L2inf, T1, T2, C]; } /* end of function findConstruction */ /* Finds index and distance delta of first point in an array that is * closest to the specified point or returns index of -1 if none */ function hitTestPoints(pointAt, points, hitDistance) { const n = points.length; const delta = Math2D.vector(); for (let i = 0; i < n; i++) { Math2D.subtract(delta, pointAt, points[i]); if (Math2D.L2(delta) <= hitDistance) { return [i, delta]; } } return [-1]; // no hit } /* Handle a mouse move for either a mousemove event or mouseentry */ function doMouseMove(pointCursor, rBtnDown) { /* Test for active move. If so, move accordingly based on the * cursor position. The right button down flag handles the case * where the cursor leaves the canvas with the right button down * and enters with it up (not moving) or down (moving). It * also helps to handle unreliable delivery of mouse events. */ if (state.pointActiveIndex >= 0 && state.pointActiveMoving && rBtnDown) { /* A point was moving and is moving more */ moveActivePointAndUpdate(pointCursor); return; } /* If there is not an active move with the right button down, * update active state based on hit testing. Mouse events have * been found to not be reliably delivered sometimes, particularly * with Chrome, so the programming must handle this issue */ state.pointActiveMoving = false; // not moving const [pointHitIndex, testDelta] = hitTestPoints( pointCursor, state.controlPoints, state.hitDistance, ); state.pointActiveIndex = pointHitIndex; canvas.style.cursor = pointHitIndex < 0 ? "auto" : "pointer"; return; } /* end of function doMouseMove */ class ConstructionPoints { static #vT1 = document.getElementById("value-T1"); static #vT2 = document.getElementById("value-T2"); static #vC = document.getElementById("value-C"); static print(T1, T2, C) { function prettyPoint(P) { return `(${P.x}, ${P.y})`; } if (state.haveCircle) { this.#vT1.textContent = prettyPoint(T1); this.#vT2.textContent = prettyPoint(T2); this.#vC.textContent = prettyPoint(C); } else { this.#vT1.textContent = "undefined"; this.#vT2.textContent = "undefined"; this.#vC.textContent = "undefined"; } } } /* Move the active point, which must exist when called, to * its new point based on the cursor location and the offset of * the cursor to the center of the point */ function moveActivePointAndUpdate(pointCursor) { let pointAdjusted = Math2D.point(); Math2D.subtract(pointAdjusted, pointCursor, state.mouseDelta); /* Adjust location to keep point on canvas */ if (pointAdjusted.x < 0) { pointAdjusted.x = 0; } else if (pointAdjusted.x >= state.canvasSize.x) { pointAdjusted.x = state.canvasSize.x; } if (pointAdjusted.y < 0) { pointAdjusted.y = 0; } else if (pointAdjusted.y >= state.canvasSize.y) { pointAdjusted.y = state.canvasSize.y; } /* Set point */ const index = state.pointActiveIndex; const pt = state.controlPoints[index]; let isPointChanged = false; let indexTextInput = 1 + 2 * index; if (pt.x !== pointAdjusted.x) { isPointChanged = true; pt.x = pointAdjusted.x; textInputs[indexTextInput].elementText.textContent = pointAdjusted.x; } if (pt.y !== pointAdjusted.y) { isPointChanged = true; pt.y = pointAdjusted.y; textInputs[indexTextInput + 1].elementText.textContent = pointAdjusted.y; } if (isPointChanged) { // Update results if x or y changed updateResults(); } } function drawCanvas() { const rPoint = 4; const colorConstruction = "#080"; const colorDragable = "#00F"; const [P0, P1, P2] = state.controlPoints; ctx.font = "italic 14pt sans-serif"; ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.lineWidth = 1; /* Draw construction information if present */ if (state.haveCircle) { ctx.strokeStyle = colorConstruction; ctx.fillStyle = colorConstruction; ctx.setLineDash([4, 6]); /* Draw the construction points */ const specialPoints = [state.C, state.T1, state.T2]; specialPoints.forEach((value) => { ctx.beginPath(); ctx.arc(value.x, value.y, rPoint, 0, 2 * Math.PI); ctx.fill(); }); /* Draw the semi-infinite lines, a radius, and the circle */ ctx.beginPath(); ctx.moveTo(state.P0Inf.x, state.P0Inf.y); ctx.lineTo(P1.x, P1.y); ctx.lineTo(state.P2Inf.x, state.P2Inf.y); ctx.stroke(); ctx.beginPath(); ctx.moveTo(state.C.x, state.C.y); ctx.lineTo(state.T1.x, state.T1.y); ctx.stroke(); ctx.beginPath(); ctx.arc(state.C.x, state.C.y, state.radius, 0, 2 * Math.PI); ctx.stroke(); ctx.fillStyle = "#000"; ctx.fillText("C", state.C.x, state.C.y - 15); ctx.fillText("T\u2081", state.T1.x, state.T1.y - 15); ctx.fillText("T\u2082", state.T2.x, state.T2.y - 15); ctx.fillText( " r", 0.5 * (state.T1.x + state.C.x), 0.5 * (state.T1.y + state.C.y), ); } else { // no circle ctx.beginPath(); ctx.moveTo(P0.x, P0.y); ctx.setLineDash([2, 6]); ctx.lineTo(P1.x, P1.y); ctx.lineTo(P2.x, P2.y); ctx.strokeStyle = colorConstruction; ctx.stroke(); } /* Draw initial point and control points */ state.controlPoints.forEach((value) => { ctx.beginPath(); ctx.arc(value.x, value.y, rPoint, 0, 2 * Math.PI); ctx.fillStyle = colorDragable; ctx.fill(); }); ctx.fillStyle = "#000"; ctx.fillText("P\u2080", P0.x, P0.y - 15); ctx.fillText("P\u2081", P1.x, P1.y - 15); ctx.fillText("P\u2082", P2.x, P2.y - 15); /* Draw the arcTo() result */ ctx.lineWidth = 3; ctx.beginPath(); ctx.moveTo(P0.x, P0.y); ctx.setLineDash([]); ctx.arcTo(P1.x, P1.y, P2.x, P2.y, state.radius); ctx.strokeStyle = "#000"; ctx.stroke(); } /* end of function drawCanvas */ function addPointArrowMoves() { [0, 1, 2].forEach((value) => addPointArrowMove(value)); } /* Allow arrow key presses on the point labels to move the point in * x and y directions */ function addPointArrowMove(indexPoint) { const elem = document.getElementById("value-P" + indexPoint); let indexTextInput = 2 * indexPoint + 1; elem.addEventListener("keydown", (evt) => { let valueNew; let indexActive = indexTextInput; switch (evt.keyCode) { case 37: // left arrow -- dec x by 1 valueNew = textInputs[indexActive].getStateValue() - 1; evt.preventDefault(); break; case 38: // up arrow -- dec y by 1 valueNew = textInputs[++indexActive].getStateValue() - 1; evt.preventDefault(); break; case 39: // right arrow -- inc x by 1 valueNew = textInputs[indexActive].getStateValue() + 1; evt.preventDefault(); break; case 40: // down arrow -- inc y by 1 valueNew = textInputs[++indexActive].getStateValue() + 1; evt.preventDefault(); break; default: // ignore all others return; } textInputs[indexActive].updateFull(valueNew); // do update }); } /* Set initial state based on parameters */ const state = initDemoState(param); /* Radius slider update */ const controlR = document.getElementById("radius-slider"); controlR.value = state.radius; // match initial value with state controlR.max = state.radiusMax; controlR.addEventListener("input", (evt) => { textInputs[0].elementText.textContent = controlR.value; state.radius = controlR.value; updateResults(); }); /* Create text inputs to set point locations and arc radius */ const textInputs = [ new TextInput( "value-r", "radius-slider", state.radiusMax, () => state.radius, (value) => (state.radius = value), ), new TextInput( "value-P0x", null, state.canvasSize.x, () => state.controlPoints[0].x, (value) => (state.controlPoints[0].x = value), ), new TextInput( "value-P0y", null, state.canvasSize.y, () => state.controlPoints[0].y, (value) => (state.controlPoints[0].y = value), ), new TextInput( "value-P1x", null, state.canvasSize.x, () => state.controlPoints[1].x, (value) => (state.controlPoints[1].x = value), ), new TextInput( "value-P1y", null, state.canvasSize.y, () => state.controlPoints[1].y, (value) => (state.controlPoints[1].y = value), ), new TextInput( "value-P2x", null, state.canvasSize.x, () => state.controlPoints[2].x, (value) => (state.controlPoints[2].x = value), ), new TextInput( "value-P2y", null, state.canvasSize.y, () => state.controlPoints[2].y, (value) => (state.controlPoints[2].y = value), ), ]; /* Allow arrow keystrokes to alter point location */ addPointArrowMoves(); /* Initialize the text inputs from the associated state values */ textInputs.forEach((ti) => (ti.elementText.textContent = ti.getStateValue())); /* Canvas setup */ const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); canvas.width = state.canvasSize.x; canvas.height = state.canvasSize.y; /* Mouse may move a moving point, move over and hover an unhovered * point, move across a hovered point, or move on other parts of * the canvas */ canvas.addEventListener("mousemove", (evt) => doMouseMove( Math2D.point(evt.offsetX, evt.offsetY), (evt.buttons & 1) === 1, ), ); /* Left mouse press on hovered point transitions to a moving point */ canvas.addEventListener("mousedown", (evt) => { if (evt.button !== 0) { // ignore all but left clicks return; } const [pointHitIndex, testDelta] = hitTestPoints( Math2D.point(evt.offsetX, evt.offsetY), state.controlPoints, state.hitDistance, ); if (pointHitIndex < 0) { // cursor over no point return; // nothing to do } /* Cursor over (hovered) point */ state.pointActiveMoving = true; // point now moving canvas.style.cursor = "move"; // Set to moving cursor state.mouseDelta = testDelta; // dist of cursor from point center }); /* Left mouse release if moving point transitions to a hovering point */ canvas.addEventListener("mouseup", (evt) => { if (evt.button !== 0) { // ignore all but left clicks return; } /* If there was a moving point, it transitions to a hovering * point */ if (state.pointActiveMoving) { state.pointActiveMoving = false; // point now hovering canvas.style.cursor = "pointer"; } }); /* Handle case that mouse reenters canvas with point moving. * If left button down on entry, continue move; otherwise stop * move. May also need to adjust hovering state */ canvas.addEventListener("mouseenter", (evt) => doMouseMove( Math2D.point(evt.offsetX, evt.offsetY), (evt.buttons & 1) === 1, ), ); drawCanvas(); // Draw initial canvas ConstructionPoints.print(state.T1, state.T2, state.C); // output pts </script> ``` ```css hidden label { margin: 10px; } .input { color: #00f; text-decoration: underline; } #canvas { border: 1px solid #000; } ``` {{ EmbedLiveSample("constructing_an_arcto_path", 350, 450) }} ### Animating `arcTo()` drawing For this example, you can play around with the arc radius to see how the path changes. The path is drawn from the starting point _p0_ using `arcTo()` with control points _p1_ and _p2_ and a radius that varies from 0 to the maximum radius selected with the slider. Then a `lineTo()` call completes the path to _p2_. #### HTML ```html <div> <label for="radius">Radius: </label> <input name="radius" type="range" id="radius" min="0" max="100" value="50" /> <label for="radius" id="radius-output">50</label> </div> <canvas id="canvas"></canvas> ``` #### JavaScript ```js const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); const controlOut = document.getElementById("radius-output"); const control = document.getElementById("radius"); control.oninput = () => { controlOut.textContent = radius = control.value; }; const p1 = { x: 100, y: 100 }; const p2 = { x: 150, y: 50 }; const p3 = { x: 200, y: 100 }; let radius = control.value; // match with init control value function labelPoint(p, offset, i = 0) { const { x, y } = offset; ctx.beginPath(); ctx.arc(p.x, p.y, 2, 0, Math.PI * 2); ctx.fill(); ctx.fillText(`${i}:(${p.x}, ${p.y})`, p.x + x, p.y + y); } function drawPoints(points) { points.forEach((p, i) => { labelPoint(p, { x: 0, y: -20 }, `p${i}`); }); } // Draw arc function drawArc([p0, p1, p2], r) { ctx.beginPath(); ctx.moveTo(p0.x, p0.y); ctx.arcTo(p1.x, p1.y, p2.x, p2.y, r); ctx.lineTo(p2.x, p2.y); ctx.stroke(); } function loop(t) { const angle = (t / 1000) % (2 * Math.PI); const rr = Math.abs(Math.cos(angle) * radius); ctx.clearRect(0, 0, canvas.width, canvas.height); drawArc([p1, p2, p3], rr); drawPoints([p1, p2, p3]); requestAnimationFrame(loop); } loop(0); ``` #### Result {{EmbedLiveSample('animating_arcto_drawing', 315, 200) }} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The interface defining this method: {{domxref("CanvasRenderingContext2D")}}
0
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d/measuretext/index.md
--- title: "CanvasRenderingContext2D: measureText() method" short-title: measureText() slug: Web/API/CanvasRenderingContext2D/measureText page-type: web-api-instance-method browser-compat: api.CanvasRenderingContext2D.measureText --- {{APIRef}} The `CanvasRenderingContext2D.measureText()` method returns a {{domxref("TextMetrics")}} object that contains information about the measured text (such as its width, for example). ## Syntax ```js-nolint measureText(text) ``` ### Parameters - `text` - : The text string to measure. ### Return value A {{domxref("TextMetrics")}} object. ## Examples Given this {{HTMLElement("canvas")}} element: ```html <canvas id="canvas"></canvas> ``` … you can get a {{domxref("TextMetrics")}} object using the following code: ```js const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); let text = ctx.measureText("Hello world"); console.log(text.width); // 56; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The interface defining this method: {{domxref("CanvasRenderingContext2D")}} - {{domxref("TextMetrics")}}
0
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d/setlinedash/index.md
--- title: "CanvasRenderingContext2D: setLineDash() method" short-title: setLineDash() slug: Web/API/CanvasRenderingContext2D/setLineDash page-type: web-api-instance-method browser-compat: api.CanvasRenderingContext2D.setLineDash --- {{APIRef}} The **`setLineDash()`** method of the Canvas 2D API's {{domxref("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-nolint setLineDash(segments) ``` ### Parameters - `segments` - : An {{jsxref("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 ({{jsxref("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 {{ EmbedLiveSample('Basic_example', 700, 180) }} ### 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 {{ EmbedLiveSample('Some_common_patterns', 700, 180) }} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The interface defining this method: {{domxref("CanvasRenderingContext2D")}} - {{domxref("CanvasRenderingContext2D.getLineDash()")}} - {{domxref("CanvasRenderingContext2D.lineDashOffset")}}
0
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d/shadowblur/index.md
--- title: "CanvasRenderingContext2D: shadowBlur property" short-title: shadowBlur slug: Web/API/CanvasRenderingContext2D/shadowBlur page-type: web-api-instance-property browser-compat: api.CanvasRenderingContext2D.shadowBlur --- {{APIRef}} The **`CanvasRenderingContext2D.shadowBlur`** property of the Canvas 2D API specifies the amount of blur applied to shadows. The default is `0` (no blur). > **Note:** Shadows are only drawn if the > {{domxref("CanvasRenderingContext2D.shadowColor", "shadowColor")}} property is set to > a non-transparent value. One of the `shadowBlur`, > {{domxref("CanvasRenderingContext2D.shadowOffsetX", "shadowOffsetX")}}, or > {{domxref("CanvasRenderingContext2D.shadowOffsetY", "shadowOffsetY")}} properties must > be non-zero, as well. ## Value A non-negative float specifying the level of shadow blur, where `0` represents no blur and larger numbers represent increasingly more blur. This value doesn't correspond to a number of pixels, and is not affected by the current transformation matrix. The default value is `0`. Negative, {{jsxref("Infinity")}}, and {{jsxref("NaN")}} values are ignored. ## Examples ### Adding a shadow to a shape This example adds a blurred shadow to a rectangle. The `shadowColor` property sets its color, and `shadowBlur` sets its level of blurriness. #### HTML ```html <canvas id="canvas"></canvas> ``` #### JavaScript ```js const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); // Shadow ctx.shadowColor = "red"; ctx.shadowBlur = 15; // Rectangle ctx.fillStyle = "blue"; ctx.fillRect(20, 20, 150, 100); ``` #### Result {{ EmbedLiveSample('Adding_a_shadow_to_a_shape', 700, 180) }} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ### WebKit/Blink-specific notes In WebKit- and Blink-based browsers, the non-standard and deprecated method `ctx.setShadow()` is implemented besides this property. ```js setShadow(width, height, blur, color, alpha); setShadow(width, height, blur, graylevel, alpha); setShadow(width, height, blur, r, g, b, a); setShadow(width, height, blur, c, m, y, k, a); ``` ## See also - The interface defining this property: {{domxref("CanvasRenderingContext2D")}} - {{domxref("CanvasRenderingContext2D.shadowColor")}}
0
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d/getlinedash/index.md
--- title: "CanvasRenderingContext2D: getLineDash() method" short-title: getLineDash() slug: Web/API/CanvasRenderingContext2D/getLineDash page-type: web-api-instance-method browser-compat: api.CanvasRenderingContext2D.getLineDash --- {{APIRef}} The **`getLineDash()`** method of the Canvas 2D API's {{domxref("CanvasRenderingContext2D")}} interface gets the current line dash pattern. ## Syntax ```js-nolint getLineDash() ``` ### Parameters None. ### Return value An {{jsxref("Array")}} of numbers that specify distances to alternately draw a line and a gap (in coordinate space units). If the number, when setting the elements, is odd, the elements of the array get copied and concatenated. For example, setting the line dash to `[5, 15, 25]` will result in getting back `[5, 15, 25, 5, 15, 25]`. ## Examples ### Getting the current line dash setting This example demonstrates the `getLineDash()` method. #### HTML ```html <canvas id="canvas"></canvas> ``` #### JavaScript As set by {{domxref("CanvasRenderingContext2D.setLineDash()", "setLineDash()")}}, strokes consist of lines that are 10 units wide, with spaces of 20 units in between each line. ```js const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); ctx.setLineDash([10, 20]); console.log(ctx.getLineDash()); // [10, 20] // Draw a dashed line ctx.beginPath(); ctx.moveTo(0, 50); ctx.lineTo(300, 50); ctx.stroke(); ``` #### Result {{ EmbedLiveSample('Getting_the_current_line_dash_setting', 700, 180) }} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The interface defining this method: {{domxref("CanvasRenderingContext2D")}} - {{domxref("CanvasRenderingContext2D.setLineDash()")}} - {{domxref("CanvasRenderingContext2D.lineDashOffset")}}
0
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d/shadowoffsety/index.md
--- title: "CanvasRenderingContext2D: shadowOffsetY property" short-title: shadowOffsetY slug: Web/API/CanvasRenderingContext2D/shadowOffsetY page-type: web-api-instance-property browser-compat: api.CanvasRenderingContext2D.shadowOffsetY --- {{APIRef}} The **`CanvasRenderingContext2D.shadowOffsetY`** property of the Canvas 2D API specifies the distance that shadows will be offset vertically. > **Note:** Shadows are only drawn if the > {{domxref("CanvasRenderingContext2D.shadowColor", "shadowColor")}} property is set to > a non-transparent value. One of the {{domxref("CanvasRenderingContext2D.shadowBlur", "shadowBlur")}}, > {{domxref("CanvasRenderingContext2D.shadowOffsetX", "shadowOffsetX")}}, or `shadowOffsetY` properties must be non-zero, as > well. ## Value A float specifying the distance that shadows will be offset vertically. Positive values are down, and negative are up. The default value is `0` (no vertical offset). {{jsxref("Infinity")}} and {{jsxref("NaN")}} values are ignored. ## Examples ### Moving a shadow vertically This example adds a blurred shadow to a rectangle. The {{domxref("CanvasRenderingContext2D.shadowColor", "shadowColor")}} property sets its color, `shadowOffsetY` sets its offset 25 units towards the bottom, and {{domxref("CanvasRenderingContext2D.shadowBlur", "shadowBlur")}} gives it a blur level of 10. #### HTML ```html <canvas id="canvas"></canvas> ``` #### JavaScript ```js const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); // Shadow ctx.shadowColor = "red"; ctx.shadowOffsetY = 25; ctx.shadowBlur = 10; // Rectangle ctx.fillStyle = "blue"; ctx.fillRect(20, 20, 150, 80); ``` #### Result {{ EmbedLiveSample('Moving_a_shadow_vertically', 700, 180) }} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The interface defining this property: {{domxref("CanvasRenderingContext2D")}} - {{domxref("CanvasRenderingContext2D.shadowOffsetX")}} - {{domxref("CanvasRenderingContext2D.shadowColor")}} - {{domxref("CanvasRenderingContext2D.shadowBlur")}}
0
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d/scale/index.md
--- title: "CanvasRenderingContext2D: scale() method" short-title: scale() slug: Web/API/CanvasRenderingContext2D/scale page-type: web-api-instance-method browser-compat: api.CanvasRenderingContext2D.scale --- {{APIRef}} The **`CanvasRenderingContext2D.scale()`** method of the Canvas 2D API adds a scaling transformation to the canvas units horizontally and/or vertically. By default, one unit on the canvas is exactly one pixel. A scaling transformation modifies this behavior. For instance, a scaling factor of 0.5 results in a unit size of 0.5 pixels; shapes are thus drawn at half the normal size. Similarly, a scaling factor of 2.0 increases the unit size so that one unit becomes two pixels; shapes are thus drawn at twice the normal size. ## Syntax ```js-nolint scale(x, y) ``` ### Parameters - `x` - : Scaling factor in the horizontal direction. A negative value flips pixels across the vertical axis. A value of `1` results in no horizontal scaling. - `y` - : Scaling factor in the vertical direction. A negative value flips pixels across the horizontal axis. A value of `1` results in no vertical scaling. ### Return value None ({{jsxref("undefined")}}). ## Examples ### Scaling a shape This example draws a scaled rectangle. A non-scaled rectangle is then drawn for comparison. #### HTML ```html <canvas id="canvas"></canvas> ``` #### JavaScript The rectangle has a specified width of 8 and a height of 20. The transformation matrix scales it by 9x horizontally and by 3x vertically. Thus, its final size is a width of 72 and a height of 60. Notice that its position on the canvas also changes. Since its specified corner is (10, 10\), its rendered corner becomes (90, 30). ```js const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); // Scaled rectangle ctx.scale(9, 3); ctx.fillStyle = "red"; ctx.fillRect(10, 10, 8, 20); // Reset current transformation matrix to the identity matrix ctx.setTransform(1, 0, 0, 1, 0, 0); // Non-scaled rectangle ctx.fillStyle = "gray"; ctx.fillRect(10, 10, 8, 20); ``` #### Result The scaled rectangle is red, and the non-scaled rectangle is gray. {{ EmbedLiveSample('Scaling_a_shape', 700, 180) }} ### Flipping things horizontally or vertically You can use `scale(-1, 1)` to flip the context horizontally and `scale(1, -1)` to flip it vertically. In this example, the words "Hello world!" are flipped horizontally. Note that the call to {{domxref("CanvasRenderingContext2D.fillText()", "fillText()")}} specifies a negative x coordinate. This is to adjust for the negative scaling factor: `-280 * -1` becomes `280`, and text is drawn leftwards from that point. #### HTML ```html <canvas id="canvas"></canvas> ``` #### JavaScript ```js const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); ctx.scale(-1, 1); ctx.font = "48px serif"; ctx.fillText("Hello world!", -280, 90); ctx.setTransform(1, 0, 0, 1, 0, 0); ``` #### Result {{ EmbedLiveSample('Flipping_things_horizontally_or_vertically', 700, 180) }} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The interface defining this method: {{domxref("CanvasRenderingContext2D")}}
0
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d/gettransform/index.md
--- title: "CanvasRenderingContext2D: getTransform() method" short-title: getTransform() slug: Web/API/CanvasRenderingContext2D/getTransform page-type: web-api-instance-method browser-compat: api.CanvasRenderingContext2D.getTransform --- {{APIRef}} The **`CanvasRenderingContext2D.getTransform()`** method of the Canvas 2D API retrieves the current transformation matrix being applied to the context. ## Syntax ```js-nolint getTransform() ``` ### Parameters None. ### Return value A {{domxref("DOMMatrix")}} object. The transformation matrix is described by: <math><semantics><mrow><mo>[</mo> <mtable columnalign="center center center" rowspacing="0.5ex"><mtr><mtd><mi>a</mi> </mtd><mtd><mi>c</mi> </mtd><mtd><mi>e</mi> </mtd></mtr><mtr><mtd><mi>b</mi> </mtd><mtd><mi>d</mi> </mtd><mtd><mi>f</mi> </mtd></mtr><mtr><mtd><mn>0</mn> </mtd><mtd><mn>0</mn> </mtd><mtd><mn>1</mn> </mtd></mtr></mtable><mo>]</mo> </mrow><annotation encoding="TeX">\left[ \begin{array}{ccc} a &#x26; c &#x26; e \\ b &#x26; d &#x26; f \\ 0 &#x26; 0 &#x26; 1 \end{array} \right]</annotation></semantics></math> > **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 {{htmlelement("canvas")}} elements. We apply a transform to the first one's context using {{domxref("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 {{ EmbedLiveSample('Examples', "100%", 180) }} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The interface defining this method: {{domxref("CanvasRenderingContext2D")}} - {{domxref("CanvasRenderingContext2D.transform()")}}
0
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d/arc/index.md
--- title: "CanvasRenderingContext2D: arc() method" short-title: arc() slug: Web/API/CanvasRenderingContext2D/arc page-type: web-api-instance-method browser-compat: api.CanvasRenderingContext2D.arc --- {{APIRef}} The **`CanvasRenderingContext2D.arc()`** method of the [Canvas 2D API](/en-US/docs/Web/API/CanvasRenderingContext2D) adds a circular arc to the current sub-path. ## Syntax ```js-nolint arc(x, y, radius, startAngle, endAngle) arc(x, y, radius, startAngle, endAngle, counterclockwise) ``` The `arc()` method creates a circular arc centered at `(x, y)` with a radius of `radius`. The path starts at `startAngle`, ends at `endAngle`, and travels in the direction given by `counterclockwise` (defaulting to clockwise). ### Parameters - `x` - : The horizontal coordinate of the arc's center. - `y` - : The vertical coordinate of the arc's center. - `radius` - : The arc's radius. Must be positive. - `startAngle` - : The angle at which the arc starts in radians, measured from the positive x-axis. - `endAngle` - : The angle at which the arc ends in radians, measured from the positive x-axis. - `counterclockwise` {{optional_inline}} - : An optional boolean value. If `true`, draws the arc counter-clockwise between the start and end angles. The default is `false` (clockwise). ### Return value None ({{jsxref("undefined")}}). ## Examples ### Drawing a full circle This example draws a complete circle with the `arc()` method. #### HTML ```html <canvas></canvas> ``` #### JavaScript The arc is given an x-coordinate of 100, a y-coordinate of 75, and a radius of 50. To make a full circle, the arc begins at an angle of 0 radians (0**°**), and ends at an angle of 2π radians (360**°**). ```js const canvas = document.querySelector("canvas"); const ctx = canvas.getContext("2d"); ctx.beginPath(); ctx.arc(100, 75, 50, 0, 2 * Math.PI); ctx.stroke(); ``` #### Result {{ EmbedLiveSample('Drawing_a_full_circle', 700, 180) }} ### Different shapes demonstrated This example draws various shapes to show what is possible with `arc()`. ```html hidden <canvas width="150" height="200"></canvas> ``` ```js const canvas = document.querySelector("canvas"); const ctx = canvas.getContext("2d"); // Draw shapes for (let i = 0; i <= 3; i++) { for (let j = 0; j <= 2; j++) { ctx.beginPath(); let x = 25 + j * 50; // x coordinate let y = 25 + i * 50; // y coordinate let radius = 20; // Arc radius let startAngle = 0; // Starting point on circle let endAngle = Math.PI + (Math.PI * j) / 2; // End point on circle let counterclockwise = i % 2 === 1; // Draw counterclockwise ctx.arc(x, y, radius, startAngle, endAngle, counterclockwise); if (i > 1) { ctx.fill(); } else { ctx.stroke(); } } } ``` #### Result {{ EmbedLiveSample('Different_shapes_demonstrated', 160, 210, "canvas_arc.png") }} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The interface defining this method: {{domxref("CanvasRenderingContext2D")}} - Use {{domxref("CanvasRenderingContext2D.ellipse()")}} to draw an elliptical arc.
0
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d/textrendering/index.md
--- title: "CanvasRenderingContext2D: textRendering property" short-title: textRendering slug: Web/API/CanvasRenderingContext2D/textRendering page-type: web-api-instance-property browser-compat: api.CanvasRenderingContext2D.textRendering --- {{APIRef}} The **`CanvasRenderingContext2D.textRendering`** property of the [Canvas API](/en-US/docs/Web/API/Canvas_API) provides information to the rendering engine about what to optimize for when rendering text. The values correspond to the SVG [`text-rendering`](/en-US/docs/Web/SVG/Attribute/text-rendering) attribute (and CSS [`text-rendering`](/en-US/docs/Web/CSS/text-rendering) property). ## Value A text-rendering hint to the browser engine. This one of: - `auto` - : The browser makes educated guesses about when to optimize for speed, legibility, and geometric precision while drawing text. - `optimizeSpeed` - : The browser emphasizes rendering speed over legibility and geometric precision when drawing text. It disables kerning and ligatures. - `optimizeLegibility` - : The browser emphasizes legibility over rendering speed and geometric precision. This enables kerning and optional ligatures. - `geometricPrecision` - : The browser emphasizes geometric precision over rendering speed and legibility. Certain aspects of fonts — such as kerning — don't scale linearly. For large scale factors, you might see less-than-beautiful text rendering, but the size is what you would expect (neither rounded up nor down to the nearest font size supported by the underlying operating system). The property can be used to get or set the value. ## Examples In this example we display the text "Hello World" using each of the supported values of the `textRendering` property. The value is also displayed for each case by reading the property. ### HTML ```html <canvas id="canvas" width="700" height="220"></canvas> ``` ### JavaScript ```js const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); ctx.font = "20px serif"; // Default (auto) ctx.fillText(`Hello world (default: ${ctx.textRendering})`, 5, 20); // Text rendering: optimizeSpeed ctx.textRendering = "optimizeSpeed"; ctx.fillText(`Hello world (${ctx.textRendering})`, 5, 50); // Text rendering: optimizeLegibility ctx.textRendering = "optimizeLegibility"; ctx.fillText(`Hello world (${ctx.textRendering})`, 5, 80); // Text rendering: geometricPrecision ctx.textRendering = "geometricPrecision"; ctx.fillText(`Hello world (${ctx.textRendering})`, 5, 110); ``` ### Result {{ EmbedLiveSample('Examples', 700, 230) }} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d/getcontextattributes/index.md
--- title: "CanvasRenderingContext2D: getContextAttributes() method" short-title: getContextAttributes() slug: Web/API/CanvasRenderingContext2D/getContextAttributes page-type: web-api-instance-method browser-compat: api.CanvasRenderingContext2D.getContextAttributes --- {{APIRef("WebGL")}} 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()`](/en-US/docs/Web/API/HTMLCanvasElement/getContext), but the attributes that are actually supported and used may differ. ## Syntax ```js-nolint getContextAttributes() ``` ### Parameters None. ### Return value A `CanvasRenderingContext2DSettings` object that contains the actual context parameters. It has the following members: - `alpha` {{optional_inline}} - : 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_inline}} - : Specifies the color space of the rendering context. Possible values are: - `srgb`: denotes the [sRGB color space](https://en.wikipedia.org/wiki/SRGB) - `display-p3`: denotes the [display-p3 color space](https://en.wikipedia.org/wiki/DCI-P3) - `desynchronized` {{optional_inline}} - : A Boolean indicating the user agent reduced the latency by desynchronizing the canvas paint cycle from the event loop. - `willReadFrequently` {{optional_inline}} - : A Boolean indicating whether or not this canvas uses software acceleration (instead of hardware acceleration) to support frequent read-back operations via{{domxref("CanvasRenderingContext2D.getImageData", "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. ```html hidden <pre id="log"></pre> ``` ```js hidden const logElement = document.getElementById("log"); function log(text) { logElement.innerText += text; } ``` First we create a context using [`HTMLCanvasElement.getContext()`](/en-US/docs/Web/API/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}` {{EmbedLiveSample('Examples','100%','50')}} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [`HTMLCanvasElement.getContext()`](/en-US/docs/Web/API/HTMLCanvasElement/getContext) - [`WebGLRenderingContext.getContextAttributes()`](/en-US/docs/Web/API/WebGLRenderingContext/getContextAttributes)
0
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d/translate/index.md
--- title: "CanvasRenderingContext2D: translate() method" short-title: translate() slug: Web/API/CanvasRenderingContext2D/translate page-type: web-api-instance-method browser-compat: api.CanvasRenderingContext2D.translate --- {{APIRef}} The **`CanvasRenderingContext2D.translate()`** method of the Canvas 2D API adds a translation transformation to the current matrix. ## Syntax ```js-nolint translate(x, y) ``` The `translate()` method adds a translation transformation to the current matrix by moving the canvas and its origin `x` units horizontally and `y` units vertically on the grid. ![A canvas's origin moved on the x and y axes based on the values of the translate method.](canvas_grid_translate.png) ### Parameters - `x` - : Distance to move in the horizontal direction. Positive values are to the right, and negative to the left. - `y` - : Distance to move in the vertical direction. Positive values are down, and negative are up. ### Return value None ({{jsxref("undefined")}}). ## Examples ### Moving a shape This example draws a square that is moved from its default position by the `translate()` method. An unmoved square of the same size is then drawn for comparison. #### HTML ```html <canvas id="canvas"></canvas> ``` #### JavaScript The `translate()` method translates the context by 110 horizontally and 30 vertically. The first square is shifted by those amounts from its default position. ```js const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); // Moved square ctx.translate(110, 30); ctx.fillStyle = "red"; ctx.fillRect(0, 0, 80, 80); // Reset current transformation matrix to the identity matrix ctx.setTransform(1, 0, 0, 1, 0, 0); // Unmoved square ctx.fillStyle = "gray"; ctx.fillRect(0, 0, 80, 80); ``` #### Result The moved square is red, and the unmoved square is gray. {{ EmbedLiveSample('Moving_a_shape', 700, 180) }} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The interface defining this method: {{domxref("CanvasRenderingContext2D")}}
0
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d/imagesmoothingquality/index.md
--- title: "CanvasRenderingContext2D: imageSmoothingQuality property" short-title: imageSmoothingQuality slug: Web/API/CanvasRenderingContext2D/imageSmoothingQuality page-type: web-api-instance-property browser-compat: api.CanvasRenderingContext2D.imageSmoothingQuality --- {{APIRef}} The **`imageSmoothingQuality`** property of the {{domxref("CanvasRenderingContext2D")}} interface, part of the [Canvas API](/en-US/docs/Web/API/Canvas_API), lets you set the quality of image smoothing. > **Note:** For this property to have an effect, > {{domxref("CanvasRenderingContext2D.imageSmoothingEnabled", "imageSmoothingEnabled")}} > must be `true`. ## Value One of the following: - `"low"` - : Low quality. - `"medium"` - : Medium quality. - `"high"` - : High quality. The default value is `"low"`. ## Examples ### Setting image smoothing quality This example uses the `imageSmoothingQuality` property with a scaled image. #### HTML ```html <canvas id="canvas"></canvas> ``` #### JavaScript ```js const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); let img = new Image(); img.src = "canvas_createpattern.png"; img.onload = () => { ctx.imageSmoothingQuality = "low"; ctx.drawImage(img, 0, 0, 300, 150); }; ``` #### Result {{ EmbedLiveSample('Setting_image_smoothing_quality', 700, 180) }} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The interface defining this property: {{domxref("CanvasRenderingContext2D")}} - {{domxref("CanvasRenderingContext2D.imageSmoothingEnabled")}} - {{cssxref("image-rendering")}}
0
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d/resettransform/index.md
--- title: "CanvasRenderingContext2D: resetTransform() method" short-title: resetTransform() slug: Web/API/CanvasRenderingContext2D/resetTransform page-type: web-api-instance-method browser-compat: api.CanvasRenderingContext2D.resetTransform --- {{APIRef}} The **`CanvasRenderingContext2D.resetTransform()`** method of the Canvas 2D API resets the current transform to the identity matrix. ## Syntax ```js-nolint resetTransform() ``` ## Examples ### Resetting the matrix This example draws a rotated rectangle after modifying the matrix, and then resets the matrix using the `resetTransform()` method. #### HTML ```html <canvas id="canvas"></canvas> ``` #### JavaScript The {{domxref("CanvasRenderingContext2D.rotate()", "rotate()")}} method rotates the transformation matrix by 45°. The {{domxref("CanvasRenderingContext2D.fillRect()", "fillRect()")}} method draws a filled rectangle, adjusted according to that matrix. ```js const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); // Draw a rotated rectangle ctx.rotate((45 * Math.PI) / 180); ctx.fillRect(60, 0, 100, 30); // Reset transformation matrix to the identity matrix ctx.resetTransform(); ``` #### Result {{ EmbedLiveSample('Resetting_the_matrix', 700, 180) }} ### Continuing with a regular matrix Whenever you're done drawing transformed shapes, you should call `resetTransform()` before rendering anything else. In this example, the first two shapes are drawn with a skew transformation, and the last two are drawn with the identity (regular) transformation. #### HTML ```html <canvas id="canvas"></canvas> ``` #### JavaScript ```js const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); // Skewed rectangles ctx.transform(1, 0, 1.7, 1, 0, 0); ctx.fillStyle = "gray"; ctx.fillRect(40, 40, 50, 20); ctx.fillRect(40, 90, 50, 20); // Non-skewed rectangles ctx.resetTransform(); ctx.fillStyle = "red"; ctx.fillRect(40, 40, 50, 20); ctx.fillRect(40, 90, 50, 20); ``` #### Result The skewed rectangles are gray, and the non-skewed rectangles are red. {{ EmbedLiveSample('Continuing_with_a_regular_matrix', 700, 180) }} ## Polyfill You can also use the {{domxref("CanvasRenderingContext2D.setTransform()", "setTransform()")}} method to reset the current transform to the identity matrix, like so: ```js ctx.setTransform(1, 0, 0, 1, 0, 0); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The interface defining this method: {{domxref("CanvasRenderingContext2D")}}
0
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d/direction/index.md
--- title: "CanvasRenderingContext2D: direction property" short-title: direction slug: Web/API/CanvasRenderingContext2D/direction page-type: web-api-instance-property browser-compat: api.CanvasRenderingContext2D.direction --- {{APIRef}} The **`CanvasRenderingContext2D.direction`** property of the Canvas 2D API specifies the current text direction used to draw text. ## Value Possible values: - `"ltr"` - : The text direction is left-to-right. - `"rtl"` - : The text direction is right-to-left. - `"inherit"` - : The text direction is inherited from the {{HTMLElement("canvas")}} element or the {{domxref("Document")}} as appropriate. Default value. The default value is `"inherit"`. ## Examples ### Changing text direction This example draws two pieces of text. The first one is left-to-right, and the second is right-to-left. Note that "Hi!" in `ltr` becomes "!Hi" in `rtl`. #### HTML ```html <canvas id="canvas"></canvas> ``` #### JavaScript ```js const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); ctx.font = "48px serif"; ctx.fillText("Hi!", 150, 50); ctx.direction = "rtl"; ctx.fillText("Hi!", 150, 130); ``` #### Result {{ EmbedLiveSample('Changing_text_direction', 700, 180) }} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The interface defining this property: {{domxref("CanvasRenderingContext2D")}}
0
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d/beziercurveto/index.md
--- title: "CanvasRenderingContext2D: bezierCurveTo() method" short-title: bezierCurveTo() slug: Web/API/CanvasRenderingContext2D/bezierCurveTo page-type: web-api-instance-method browser-compat: api.CanvasRenderingContext2D.bezierCurveTo --- {{APIRef}} The **`CanvasRenderingContext2D.bezierCurveTo()`** method of the Canvas 2D API adds a cubic [Bézier curve](/en-US/docs/Glossary/Bezier_curve) to the current sub-path. It requires three points: the first two are control points and the third one is the end point. The starting point is the latest point in the current path, which can be changed using {{domxref("CanvasRenderingContext2D.moveTo", "moveTo()")}} before creating the Bézier curve. ## Syntax ```js-nolint bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y) ``` ### Parameters - `cp1x` - : The x-axis coordinate of the first control point. - `cp1y` - : The y-axis coordinate of the first control point. - `cp2x` - : The x-axis coordinate of the second control point. - `cp2y` - : The y-axis coordinate of the second control point. - `x` - : The x-axis coordinate of the end point. - `y` - : The y-axis coordinate of the end point. ### Return value None ({{jsxref("undefined")}}). ## Examples ### How bezierCurveTo works This example shows how a cubic Bézier curve is drawn. #### HTML ```html <canvas id="canvas"></canvas> ``` #### JavaScript ```js // Define canvas and context const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); // Define the points as {x, y} let start = { x: 50, y: 20 }; let cp1 = { x: 230, y: 30 }; let cp2 = { x: 150, y: 80 }; let end = { x: 250, y: 100 }; // Cubic Bézier curve ctx.beginPath(); ctx.moveTo(start.x, start.y); ctx.bezierCurveTo(cp1.x, cp1.y, cp2.x, cp2.y, end.x, end.y); ctx.stroke(); // Start and end points ctx.fillStyle = "blue"; ctx.beginPath(); ctx.arc(start.x, start.y, 5, 0, 2 * Math.PI); // Start point ctx.arc(end.x, end.y, 5, 0, 2 * Math.PI); // End point ctx.fill(); // Control points ctx.fillStyle = "red"; ctx.beginPath(); ctx.arc(cp1.x, cp1.y, 5, 0, 2 * Math.PI); // Control point one ctx.arc(cp2.x, cp2.y, 5, 0, 2 * Math.PI); // Control point two ctx.fill(); ``` #### Result In this example, the control points are red and the start and end points are blue. {{ EmbedLiveSample('How_bezierCurveTo_works', 315, 165) }} ### A simple Bézier curve This example draws a simple Bézier curve using `bezierCurveTo()`. #### HTML ```html <canvas id="canvas"></canvas> ``` #### JavaScript The curve begins at the point specified by `moveTo()`: (30, 30). The first control point is placed at (120, 160), and the second at (180, 10). The curve ends at (220, 140). ```js const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); ctx.beginPath(); ctx.moveTo(30, 30); ctx.bezierCurveTo(120, 160, 180, 10, 220, 140); ctx.stroke(); ``` #### Result {{ EmbedLiveSample('A_simple_Bézier_curve', 700, 180) }} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The interface defining this method: {{domxref("CanvasRenderingContext2D")}} - [Bézier curve](/en-US/docs/Glossary/Bezier_curve)
0
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d/createlineargradient/index.md
--- title: "CanvasRenderingContext2D: createLinearGradient() method" short-title: createLinearGradient() slug: Web/API/CanvasRenderingContext2D/createLinearGradient page-type: web-api-instance-method browser-compat: api.CanvasRenderingContext2D.createLinearGradient --- {{APIRef}} The **`CanvasRenderingContext2D.createLinearGradient()`** method of the Canvas 2D API creates a gradient along the line connecting two given coordinates. ![The gradient transitions colors along the gradient line, starting at point x0, y0 and going to x1, y1, even if those points extend the gradient line beyond the edges of the element on which the gradient is drawn.](mdn-canvas-lineargradient.png) This method returns a linear {{domxref("CanvasGradient")}}. To be applied to a shape, the gradient must first be assigned to the {{domxref("CanvasRenderingContext2D.fillStyle", "fillStyle")}} or {{domxref("CanvasRenderingContext2D.strokeStyle", "strokeStyle")}} properties. > **Note:** Gradient coordinates are global, i.e., relative to the current > coordinate space. When applied to a shape, the coordinates are NOT relative to the > shape's coordinates. ## Syntax ```js-nolint createLinearGradient(x0, y0, x1, y1) ``` The `createLinearGradient()` method is specified by four parameters defining the start and end points of the gradient line. ### Parameters - `x0` - : The x-axis coordinate of the start point. - `y0` - : The y-axis coordinate of the start point. - `x1` - : The x-axis coordinate of the end point. - `y1` - : The y-axis coordinate of the end point. ### Return value A linear {{domxref("CanvasGradient")}} initialized with the specified line. ### Exceptions - `NotSupportedError` {{domxref("DOMException")}} - : Thrown when non-finite values are passed as parameters. ## Examples ### Filling a rectangle with a linear gradient This example initializes a linear gradient using the `createLinearGradient()` method. Three color stops between the gradient's start and end points are then created. Finally, the gradient is assigned to the canvas context, and is rendered to a filled rectangle. #### HTML ```html <canvas id="canvas"></canvas> ``` #### JavaScript ```js const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); // Create a linear gradient // The start gradient point is at x=20, y=0 // The end gradient point is at x=220, y=0 const gradient = ctx.createLinearGradient(20, 0, 220, 0); // Add three color stops gradient.addColorStop(0, "green"); gradient.addColorStop(0.5, "cyan"); gradient.addColorStop(1, "green"); // Set the fill style and draw a rectangle ctx.fillStyle = gradient; ctx.fillRect(20, 20, 200, 100); ``` #### Result {{ EmbedLiveSample('Filling_a_rectangle_with_a_linear_gradient', 700, 180) }} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The interface defining this method: {{domxref("CanvasRenderingContext2D")}} - {{domxref("CanvasRenderingContext2D.createRadialGradient()")}} - {{domxref("CanvasRenderingContext2D.createConicGradient()")}}
0
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d/fontvariantcaps/index.md
--- title: "CanvasRenderingContext2D: fontVariantCaps property" short-title: fontVariantCaps slug: Web/API/CanvasRenderingContext2D/fontVariantCaps page-type: web-api-instance-property browser-compat: api.CanvasRenderingContext2D.fontVariantCaps --- {{APIRef}} The **`CanvasRenderingContext2D.fontVariantCaps`** property of the [Canvas API](/en-US/docs/Web/API/Canvas_API) specifies an alternative capitalization of the rendered text. This corresponds to the CSS [`font-variant-caps`](/en-US/docs/Web/CSS/font-variant-caps) property. ## Value The font alternative capitalization value, which is one of: - `normal` (default) - : Deactivates of the use of alternate glyphs. - `small-caps` - : Enables display of small capitals (OpenType feature: `smcp`). Small-caps glyphs typically use the form of uppercase letters but are reduced to the size of lowercase letters. - `all-small-caps` - : Enables display of small capitals for both upper and lowercase letters (OpenType features: `c2sc`, `smcp`). - `petite-caps` - : Enables display of petite capitals (OpenType feature: `pcap`). - `all-petite-caps` - : Enables display of petite capitals for both upper and lowercase letters (OpenType features: `c2pc`, `pcap`). - `unicase` - : Enables display of mixture of small capitals for uppercase letters with normal lowercase letters (OpenType feature: `unic`). - `titling-caps` - : Enables display of titling capitals (OpenType feature: `titl`). Uppercase letter glyphs are often designed for use with lowercase letters. When used in all uppercase titling sequences they can appear too strong. Titling capitals are designed specifically for this situation. The property can be used to get or set the font capitalization value. Note that there are accessibility concerns with some of these, which are outlined in the corresponding [`font-variant-caps`](/en-US/docs/Web/CSS/font-variant-caps#accessibility_concerns) topic. ## Examples In this example we display the text "Hello World" using each of the supported values of the `fontVariantCaps` property. The value is also displayed for each case by reading the property. ### HTML ```html <canvas id="canvas" width="700" height="220"></canvas> ``` ### JavaScript ```js const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); ctx.font = "20px serif"; // Default (normal) ctx.fillText(`Hello world (default: ${ctx.fontVariantCaps})`, 5, 20); // Capitalization: small-caps ctx.fontVariantCaps = "small-caps"; ctx.fillText(`Hello world (${ctx.fontVariantCaps})`, 5, 50); // Capitalization: all-small-caps ctx.fontVariantCaps = "all-small-caps"; ctx.fillText(`Hello world (${ctx.fontVariantCaps})`, 5, 80); // Capitalization: petite-caps ctx.fontVariantCaps = "petite-caps"; ctx.fillText(`Hello world (${ctx.fontVariantCaps})`, 5, 110); // Capitalization: all-petite-caps ctx.fontVariantCaps = "all-petite-caps"; ctx.fillText(`Hello world (${ctx.fontVariantCaps})`, 5, 140); // Capitalization: unicase ctx.fontVariantCaps = "unicase"; ctx.fillText(`Hello world (${ctx.fontVariantCaps})`, 5, 170); // Capitalization: titling-caps ctx.fontVariantCaps = "titling-caps"; ctx.fillText(`Hello world (${ctx.fontVariantCaps})`, 5, 200); ``` ### Result {{ EmbedLiveSample('Examples', 700, 230) }} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d/font/index.md
--- title: "CanvasRenderingContext2D: font property" short-title: font slug: Web/API/CanvasRenderingContext2D/font page-type: web-api-instance-property browser-compat: api.CanvasRenderingContext2D.font --- {{APIRef}} The **`CanvasRenderingContext2D.font`** property of the Canvas 2D API specifies the current text style to use when drawing text. This string uses the same syntax as the [CSS font](/en-US/docs/Web/CSS/font) specifier. ## Value A string parsed as CSS {{cssxref("font")}} value. The default font is 10px sans-serif. ## Examples ### Using a custom font In this example we use the `font` property to specify a custom font weight, size, and family. #### HTML ```html <canvas id="canvas"></canvas> ``` #### JavaScript ```js const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); ctx.font = "bold 48px serif"; ctx.strokeText("Hello world", 50, 100); ``` #### Result {{ EmbedLiveSample('Using_a_custom_font', 700, 180) }} ### Loading fonts with the CSS Font Loading API With the help of the {{domxref("FontFace")}} API, you can explicitly load fonts before using them in a canvas. ```js let f = new FontFace("test", "url(x)"); f.load().then(() => { // Ready to use the font in a canvas context }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The interface defining this property: {{domxref("CanvasRenderingContext2D")}}
0
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d/linejoin/index.md
--- title: "CanvasRenderingContext2D: lineJoin property" short-title: lineJoin slug: Web/API/CanvasRenderingContext2D/lineJoin page-type: web-api-instance-property browser-compat: api.CanvasRenderingContext2D.lineJoin --- {{APIRef}} The **`CanvasRenderingContext2D.lineJoin`** property of the Canvas 2D API determines the shape used to join two line segments where they meet. This property has no effect wherever two connected segments have the same direction, because no joining area will be added in this case. Degenerate segments with a length of zero (i.e., with all endpoints and control points at the exact same position) are also ignored. > **Note:** Lines can be drawn with the > {{domxref("CanvasRenderingContext2D.stroke()", "stroke()")}}, > {{domxref("CanvasRenderingContext2D.strokeRect()", "strokeRect()")}}, > and {{domxref("CanvasRenderingContext2D.strokeText()", "strokeText()")}} methods. ## Value There are three possible values for this property: `"round"`, `"bevel"`, and `"miter"`. The default is `"miter"`. ![Three horizontal zigzag lines with round, bevel, and miter values, shown from top to bottom respectively.](canvas_linejoin.png) - `"round"` - : Rounds off the corners of a shape by filling an additional sector of disc centered at the common endpoint of connected segments. The radius for these rounded corners is equal to the line width. - `"bevel"` - : Fills an additional triangular area between the common endpoint of connected segments, and the separate outside rectangular corners of each segment. - `"miter"` - : Connected segments are joined by extending their outside edges to connect at a single point, with the effect of filling an additional lozenge-shaped area. This setting is affected by the {{domxref("CanvasRenderingContext2D.miterLimit", "miterLimit")}} property. Default value. ## Examples ### Changing the joins in a path This example applies rounded line joins to a path. #### HTML ```html <canvas id="canvas"></canvas> ``` #### JavaScript ```js const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); ctx.lineWidth = 20; ctx.lineJoin = "round"; ctx.beginPath(); ctx.moveTo(20, 20); ctx.lineTo(190, 100); ctx.lineTo(280, 20); ctx.lineTo(280, 150); ctx.stroke(); ``` #### Result {{ EmbedLiveSample('Changing_the_joins_in_a_path', 700, 180) }} ### Comparison of line joins The example below draws three different paths, demonstrating each of the three `lineJoin` options. ```html hidden <canvas id="canvas" width="150" height="150"></canvas> ``` ```js const ctx = document.getElementById("canvas").getContext("2d"); ctx.lineWidth = 10; ["round", "bevel", "miter"].forEach((join, i) => { ctx.lineJoin = join; ctx.beginPath(); ctx.moveTo(-5, 5 + i * 40); ctx.lineTo(35, 45 + i * 40); ctx.lineTo(75, 5 + i * 40); ctx.lineTo(115, 45 + i * 40); ctx.lineTo(155, 5 + i * 40); ctx.stroke(); }); ``` {{EmbedLiveSample("Comparison_of_line_joins", "180", "180", "canvas_linejoin.png")}} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ### WebKit/Blink-specific notes - In WebKit- and Blink-based Browsers, a non-standard and deprecated method `ctx.setLineJoin()` is implemented in addition to this property. ## See also - The interface defining this property: {{domxref("CanvasRenderingContext2D")}} - {{domxref("CanvasRenderingContext2D.lineCap")}} - {{domxref("CanvasRenderingContext2D.lineWidth")}} - [Applying styles and color](/en-US/docs/Web/API/Canvas_API/Tutorial/Applying_styles_and_colors)
0
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d/linecap/index.md
--- title: "CanvasRenderingContext2D: lineCap property" short-title: lineCap slug: Web/API/CanvasRenderingContext2D/lineCap page-type: web-api-instance-property browser-compat: api.CanvasRenderingContext2D.lineCap --- {{APIRef}} The **`CanvasRenderingContext2D.lineCap`** property of the Canvas 2D API determines the shape used to draw the end points of lines. > **Note:** Lines can be drawn with the > {{domxref("CanvasRenderingContext2D.stroke()", "stroke()")}}, {{domxref("CanvasRenderingContext2D.strokeRect()", "strokeRect()")}}, > and {{domxref("CanvasRenderingContext2D.strokeText()", "strokeText()")}} methods. ## Value One of the following: - `"butt"` - : The ends of lines are squared off at the endpoints. Default value. - `"round"` - : The ends of lines are rounded. - `"square"` - : The ends of lines are squared off by adding a box with an equal width and half the height of the line's thickness. ## Examples ### Changing the shape of line caps This example rounds the end caps of a straight line. #### HTML ```html <canvas id="canvas"></canvas> ``` #### JavaScript ```js const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); ctx.beginPath(); ctx.moveTo(20, 20); ctx.lineWidth = 15; ctx.lineCap = "round"; ctx.lineTo(100, 100); ctx.stroke(); ``` #### Result {{ EmbedLiveSample('Changing_the_shape_of_line_caps', 700, 180) }} ### Comparison of line caps In this example three lines are drawn, each with a different value for the `lineCap` property. Two guides to see the exact differences between the three are added. Each of these lines starts and ends exactly on these guides. The line on the left uses the default `"butt"` option. It's drawn completely flush with the guides. The second is set to use the `"round"` option. This adds a semicircle to the end that has a radius half the width of the line. The line on the right uses the `"square"` option. This adds a box with an equal width and half the height of the line thickness. ```html hidden <canvas id="canvas" width="150" height="150"></canvas> ``` ```js const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); // Draw guides ctx.strokeStyle = "#09f"; ctx.beginPath(); ctx.moveTo(10, 10); ctx.lineTo(140, 10); ctx.moveTo(10, 140); ctx.lineTo(140, 140); ctx.stroke(); // Draw lines ctx.strokeStyle = "black"; ["butt", "round", "square"].forEach((lineCap, i) => { ctx.lineWidth = 15; ctx.lineCap = lineCap; ctx.beginPath(); ctx.moveTo(25 + i * 50, 10); ctx.lineTo(25 + i * 50, 140); ctx.stroke(); }); ``` {{EmbedLiveSample("Comparison_of_line_caps", "180", "180", "canvas_linecap.png")}} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ### WebKit/Blink-specific notes - In WebKit- and Blink-based Browsers, a non-standard and deprecated method `ctx.setLineCap()` is implemented in addition to this property. ## See also - The interface defining this property: {{domxref("CanvasRenderingContext2D")}} - {{domxref("CanvasRenderingContext2D.lineWidth")}} - {{domxref("CanvasRenderingContext2D.lineJoin")}} - [Applying styles and color](/en-US/docs/Web/API/Canvas_API/Tutorial/Applying_styles_and_colors)
0
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d/strokestyle/index.md
--- title: "CanvasRenderingContext2D: strokeStyle property" short-title: strokeStyle slug: Web/API/CanvasRenderingContext2D/strokeStyle page-type: web-api-instance-property browser-compat: api.CanvasRenderingContext2D.strokeStyle --- {{APIRef}} The **`CanvasRenderingContext2D.strokeStyle`** property of the Canvas 2D API specifies the color, gradient, or pattern to use for the strokes (outlines) around shapes. The default is `#000` (black). > **Note:** For more examples of stroke and fill styles, see [Applying styles and color](/en-US/docs/Web/API/Canvas_API/Tutorial/Applying_styles_and_colors) in the [Canvas tutorial](/en-US/docs/Web/API/Canvas_API/Tutorial). ## Value One of the following: - `color` - : A string parsed as [CSS](/en-US/docs/Web/CSS) {{cssxref("&lt;color&gt;")}} value. - `gradient` - : A {{domxref("CanvasGradient")}} object (a linear or radial gradient). - `pattern` - : A {{domxref("CanvasPattern")}} object (a repeating image). ## Examples ### Changing the stroke color of a shape This example applies a blue stroke color to a rectangle. #### HTML ```html <canvas id="canvas"></canvas> ``` #### JavaScript ```js const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); ctx.strokeStyle = "blue"; ctx.strokeRect(10, 10, 100, 100); ``` #### Result {{ EmbedLiveSample('Changing_the_stroke_color_of_a_shape', 700, 160) }} ### Creating multiple stroke colors using loops In this example, we use two `for` loops and the {{domxref("CanvasRenderingContext2D.arc", "arc()")}} method to draw a grid of circles, each having a different stroke color. To achieve this, we use the two variables `i` and `j` to generate a unique RGB color for each circle, and only modify the green and blue values. (The red channel has a fixed value.) ```html hidden <canvas id="canvas" width="150" height="150"></canvas> ``` ```js const ctx = document.getElementById("canvas").getContext("2d"); for (let i = 0; i < 6; i++) { for (let j = 0; j < 6; j++) { ctx.strokeStyle = `rgb( 0 ${Math.floor(255 - 42.5 * i)} ${Math.floor(255 - 42.5 * j)})`; ctx.beginPath(); ctx.arc(12.5 + j * 25, 12.5 + i * 25, 10, 0, Math.PI * 2, true); ctx.stroke(); } } ``` The result looks like this: {{EmbedLiveSample("Creating_multiple_stroke_colors_using_loops", "180", "180", "canvas_strokestyle.png")}} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ### WebKit/Blink-specific note In WebKit- and Blink-based browsers, the non-standard and deprecated method `ctx.setStrokeColor()` is implemented in addition to this property. ```js setStrokeColor(color); setStrokeColor(color, alpha); setStrokeColor(grayLevel); setStrokeColor(grayLevel, alpha); setStrokeColor(r, g, b, a); setStrokeColor(c, m, y, k, a); ``` ## See also - The interface defining this property: {{domxref("CanvasRenderingContext2D")}} - {{domxref("CanvasGradient")}} - {{domxref("CanvasPattern")}}
0
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d/restore/index.md
--- title: "CanvasRenderingContext2D: restore() method" short-title: restore() slug: Web/API/CanvasRenderingContext2D/restore page-type: web-api-instance-method browser-compat: api.CanvasRenderingContext2D.restore --- {{APIRef}} 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](/en-US/docs/Web/API/CanvasRenderingContext2D/save#drawing_state), see {{domxref("CanvasRenderingContext2D.save()")}}. ## Syntax ```js-nolint restore() ``` ### Parameters None. ### Return value None ({{jsxref("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 {{ EmbedLiveSample('Restoring_a_saved_state', 700, 180) }} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The interface defining this method: {{domxref("CanvasRenderingContext2D")}} - {{domxref("CanvasRenderingContext2D.save()")}}
0
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d/clearrect/index.md
--- title: "CanvasRenderingContext2D: clearRect() method" short-title: clearRect() slug: Web/API/CanvasRenderingContext2D/clearRect page-type: web-api-instance-method browser-compat: api.CanvasRenderingContext2D.clearRect --- {{APIRef}} The **`CanvasRenderingContext2D.clearRect()`** method of the Canvas 2D API erases the pixels in a rectangular area by setting them to transparent black. > **Note:** Be aware that `clearRect()` may cause unintended > side effects if you're not [using paths properly](/en-US/docs/Web/API/Canvas_API/Tutorial/Drawing_shapes#drawing_paths). Make sure to call > {{domxref("CanvasRenderingContext2D.beginPath", "beginPath()")}} before starting to > draw new items after calling `clearRect()`. ## Syntax ```js-nolint clearRect(x, y, width, height) ``` The `clearRect()` method sets the pixels in a rectangular area to transparent black (`rgb(0 0 0 / 0%)`). The rectangle's top-left corner is at `(x, y)`, and its 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 ({{jsxref("undefined")}}). ## Examples ### Erasing the whole canvas This code snippet erases the entire canvas. This is commonly required at the start of each frame in an animation. The dimensions of the cleared area are set to equal the {{HtmlElement("canvas")}} element's `width` and `height` attributes. ```js const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); ctx.clearRect(0, 0, canvas.width, canvas.height); ``` ### Erasing part of a canvas This example draws a blue triangle on top of a yellowish background. The `clearRect()` method then erases part of the canvas. #### HTML ```html <canvas id="canvas"></canvas> ``` #### JavaScript The cleared area is rectangular in shape, with its top-left corner at (10, 10). The cleared area has a width of 120 and a height of 100. ```js const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); // Draw yellow background ctx.beginPath(); ctx.fillStyle = "#ff6"; ctx.fillRect(0, 0, canvas.width, canvas.height); // Draw blue triangle ctx.beginPath(); ctx.fillStyle = "blue"; ctx.moveTo(20, 20); ctx.lineTo(180, 20); ctx.lineTo(130, 130); ctx.closePath(); ctx.fill(); // Clear part of the canvas ctx.clearRect(10, 10, 120, 100); ``` #### Result {{EmbedLiveSample('Erasing_part_of_a_canvas', 700, 180)}} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The interface defining this method: {{domxref("CanvasRenderingContext2D")}} - {{domxref("CanvasRenderingContext2D.fillRect()")}} - {{domxref("CanvasRenderingContext2D.strokeRect()")}}
0
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d/createpattern/index.md
--- title: "CanvasRenderingContext2D: createPattern() method" short-title: createPattern() slug: Web/API/CanvasRenderingContext2D/createPattern page-type: web-api-instance-method browser-compat: api.CanvasRenderingContext2D.createPattern --- {{APIRef}} The **`CanvasRenderingContext2D.createPattern()`** method of the Canvas 2D API creates a pattern using the specified image and repetition. This method returns a {{domxref("CanvasPattern")}}. This method doesn't draw anything to the canvas directly. The pattern it creates must be assigned to the {{domxref("CanvasRenderingContext2D.fillStyle")}} or {{domxref("CanvasRenderingContext2D.strokeStyle")}} properties, after which it is applied to any subsequent drawing. ## Syntax ```js-nolint createPattern(image, repetition) ``` ### Parameters - `image` - : An image to be used as the pattern's image. It can be any of the following: - {{domxref("HTMLImageElement")}} ({{HTMLElement("img")}}) - {{domxref("SVGImageElement")}} ({{SVGElement("image")}}) - {{domxref("HTMLVideoElement")}} ({{HTMLElement("video")}}, by using the capture of the video) - {{domxref("HTMLCanvasElement")}} ({{HTMLElement("canvas")}}) - {{domxref("ImageBitmap")}} - {{domxref("OffscreenCanvas")}} - {{domxref("VideoFrame")}} - `repetition` - : A string indicating how to repeat the pattern's image. Possible values are: - `"repeat"` (both directions) - `"repeat-x"` (horizontal only) - `"repeat-y"` (vertical only) - `"no-repeat"` (neither direction) If `repetition` is specified as an empty string (`""`) or [`null`](/en-US/docs/Web/JavaScript/Reference/Operators/null) (but not {{jsxref("undefined")}}), a value of `"repeat"` will be used. ### Return value - {{domxref("CanvasPattern")}} - : An opaque object describing a pattern. If the `image` is not fully loaded ({{domxref("HTMLImageElement.complete")}} is `false`), then [`null`](/en-US/docs/Web/JavaScript/Reference/Operators/null) is returned. ## Examples ### Creating a pattern from an image This example uses the `createPattern()` method to create a {{domxref("CanvasPattern")}} with a repeating source image. Once created, the pattern is assigned to the canvas context's fill style and applied to a rectangle. The original image looks like this: ![A flowery pattern](canvas_createpattern.png) #### HTML ```html <canvas id="canvas" width="300" height="300"></canvas> ``` #### JavaScript ```js const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); const img = new Image(); img.src = "canvas_createpattern.png"; // Only use the image after it's loaded img.onload = () => { const pattern = ctx.createPattern(img, "repeat"); ctx.fillStyle = pattern; ctx.fillRect(0, 0, 300, 300); }; ``` {{ EmbedLiveSample('Creating_a_pattern_from_an_image', 700, 310) }} ### Creating a pattern from a canvas In this example we create a pattern from the contents of an offscreen canvas. We then apply it to the fill style of our primary canvas, and fill that canvas with the pattern. #### JavaScript ```js // Create a pattern, offscreen const patternCanvas = document.createElement("canvas"); const patternContext = patternCanvas.getContext("2d"); // Give the pattern a width and height of 50 patternCanvas.width = 50; patternCanvas.height = 50; // Give the pattern a background color and draw an arc patternContext.fillStyle = "#fec"; patternContext.fillRect(0, 0, patternCanvas.width, patternCanvas.height); patternContext.arc(0, 0, 50, 0, 0.5 * Math.PI); patternContext.stroke(); // Create our primary canvas and fill it with the pattern const canvas = document.createElement("canvas"); const ctx = canvas.getContext("2d"); const pattern = ctx.createPattern(patternCanvas, "repeat"); ctx.fillStyle = pattern; ctx.fillRect(0, 0, canvas.width, canvas.height); // Add our primary canvas to the webpage document.body.appendChild(canvas); ``` #### Result {{ EmbedLiveSample('Creating_a_pattern_from_a_canvas', 700, 160) }} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The interface defining this method: {{domxref("CanvasRenderingContext2D")}} - {{domxref("CanvasPattern")}}
0
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d/ellipse/index.md
--- title: "CanvasRenderingContext2D: ellipse() method" short-title: ellipse() slug: Web/API/CanvasRenderingContext2D/ellipse page-type: web-api-instance-method browser-compat: api.CanvasRenderingContext2D.ellipse --- {{APIRef}} The **`CanvasRenderingContext2D.ellipse()`** method of the Canvas 2D API adds an elliptical arc to the current sub-path. ## Syntax ```js-nolint 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](https://www.simply.science/index.php/math/geometry/conic-sections/ellipse/10022-eccentric-angle-and-parametric-equations-of-an-ellipse) at which the ellipse starts, measured clockwise from the positive x-axis and expressed in radians. - `endAngle` - : The [eccentric angle](https://www.simply.science/index.php/math/geometry/conic-sections/ellipse/10022-eccentric-angle-and-parametric-equations-of-an-ellipse) at which the ellipse ends, measured clockwise from the positive x-axis and expressed in radians. - `counterclockwise` {{optional_inline}} - : An optional boolean value which, if `true`, draws the ellipse counterclockwise (anticlockwise). The default value is `false` (clockwise). ### Return value None ({{jsxref("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 {{ EmbedLiveSample('Drawing_a_full_ellipse', 700, 250) }} ### 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 {{ EmbedLiveSample('Various_elliptical_arcs', 700, 180) }} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The interface defining this method: {{domxref("CanvasRenderingContext2D")}} - Use {{domxref("CanvasRenderingContext2D.arc()")}} to draw a circular arc
0
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d/textalign/index.md
--- title: "CanvasRenderingContext2D: textAlign property" short-title: textAlign slug: Web/API/CanvasRenderingContext2D/textAlign page-type: web-api-instance-property browser-compat: api.CanvasRenderingContext2D.textAlign --- {{APIRef}} The **`CanvasRenderingContext2D.textAlign`** property of the Canvas 2D API specifies the current text alignment used when drawing text. The alignment is relative to the `x` value of the {{domxref("CanvasRenderingContext2D.fillText", "fillText()")}} method. For example, if `textAlign` is `"center"`, then the text's left edge will be at `x - (textWidth / 2)`. ## Value Possible values: - `"left"` - : The text is left-aligned. - `"right"` - : The text is right-aligned. - `"center"` - : The text is centered. - `"start"` - : The text is aligned at the normal start of the line (left-aligned for left-to-right locales, right-aligned for right-to-left locales). - `"end"` - : The text is aligned at the normal end of the line (right-aligned for left-to-right locales, left-aligned for right-to-left locales). The default value is `"start"`. ## Examples ### General text alignment This example demonstrates the three "physical" values of the `textAlign` property: `"left"`, `"center"`, and `"right"`. #### HTML ```html <canvas id="canvas"></canvas> ``` #### JavaScript ```js const canvas = document.getElementById("canvas"); canvas.width = 350; const ctx = canvas.getContext("2d"); const x = canvas.width / 2; ctx.beginPath(); ctx.moveTo(x, 0); ctx.lineTo(x, canvas.height); ctx.stroke(); ctx.font = "30px serif"; ctx.textAlign = "left"; ctx.fillText("left-aligned", x, 40); ctx.textAlign = "center"; ctx.fillText("center-aligned", x, 85); ctx.textAlign = "right"; ctx.fillText("right-aligned", x, 130); ``` #### Result {{ EmbedLiveSample('General_text_alignment', 700, 180) }} ### Direction-dependent text alignment This example demonstrates the two direction-dependent values of the `textAlign` property: `"start"` and `"end"`. Note that the {{domxref("CanvasRenderingContext2D.direction", "direction")}} property is manually specified as `"ltr"`, although this is also the default for English-language text. #### HTML ```html <canvas id="canvas"></canvas> ``` #### JavaScript ```js const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); ctx.font = "30px serif"; ctx.direction = "ltr"; ctx.textAlign = "start"; ctx.fillText("Start-aligned", 0, 50); ctx.textAlign = "end"; ctx.fillText("End-aligned", canvas.width, 120); ``` #### Result {{ EmbedLiveSample('Direction-dependent_text_alignment', 700, 180) }} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The interface defining this property: {{domxref("CanvasRenderingContext2D")}}
0
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d/reset/index.md
--- title: "CanvasRenderingContext2D: reset() method" short-title: reset() slug: Web/API/CanvasRenderingContext2D/reset page-type: web-api-instance-method browser-compat: api.CanvasRenderingContext2D.reset --- {{APIRef}} 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](/en-US/docs/Web/API/CanvasRenderingContext2D#transformations) matrix, [compositing](/en-US/docs/Web/API/CanvasRenderingContext2D#compositing) properties, clipping region, dash list, [line styles](/en-US/docs/Web/API/CanvasRenderingContext2D#line_styles), [text styles](/en-US/docs/Web/API/CanvasRenderingContext2D#text_styles), [shadows](/en-US/docs/Web/API/CanvasRenderingContext2D#shadows), [image smoothing](/en-US/docs/Web/API/CanvasRenderingContext2D#image_smoothing), [filters](/en-US/docs/Web/API/CanvasRenderingContext2D#filters), and so on. ## Syntax ```js-nolint reset() ``` ### Parameters None. ### Return value None ({{jsxref("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: {{EmbedLiveSample("Examples", 500, 250)}} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The interface defining this method: {{domxref("CanvasRenderingContext2D")}}
0
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d/globalcompositeoperation/index.md
--- title: "CanvasRenderingContext2D: globalCompositeOperation property" short-title: globalCompositeOperation slug: Web/API/CanvasRenderingContext2D/globalCompositeOperation page-type: web-api-instance-property browser-compat: api.CanvasRenderingContext2D.globalCompositeOperation --- {{APIRef}} The **`CanvasRenderingContext2D.globalCompositeOperation`** property of the Canvas 2D API sets the type of compositing operation to apply when drawing new shapes. See also [Compositing and clipping](/en-US/docs/Web/API/Canvas_API/Tutorial/Compositing) in the [Canvas Tutorial](/en-US/docs/Web/API/Canvas_API/Tutorial). ## Value A string identifying which of the compositing or blending mode operations to use. This may be any of the following values: - `"source-over"` - : This is the default setting and draws new shapes on top of the existing canvas content. - `"source-in"` - : The new shape is drawn only where both the new shape and the destination canvas overlap. Everything else is made transparent. - `"source-out"` - : The new shape is drawn where it doesn't overlap the existing canvas content. - `"source-atop"` - : The new shape is only drawn where it overlaps the existing canvas content. - `"destination-over"` - : New shapes are drawn behind the existing canvas content. - `"destination-in"` - : The existing canvas content is kept where both the new shape and existing canvas content overlap. Everything else is made transparent. - `"destination-out"` - : The existing content is kept where it doesn't overlap the new shape. - `"destination-atop"` - : The existing canvas is only kept where it overlaps the new shape. The new shape is drawn behind the canvas content. - `"lighter"` - : Where both shapes overlap, the color is determined by adding color values. - `"copy"` - : Only the new shape is shown. - `"xor"` - : Shapes are made transparent where both overlap and drawn normal everywhere else. - `"multiply"` - : The pixels of the top layer are multiplied with the corresponding pixels of the bottom layer. A darker picture is the result. - `"screen"` - : The pixels are inverted, multiplied, and inverted again. A lighter picture is the result (opposite of `multiply`) - `"overlay"` - : A combination of `multiply` and `screen`. Dark parts on the base layer become darker, and light parts become lighter. - `"darken"` - : Retains the darkest pixels of both layers. - `"lighten"` - : Retains the lightest pixels of both layers. - `"color-dodge"` - : Divides the bottom layer by the inverted top layer. - `"color-burn"` - : Divides the inverted bottom layer by the top layer, and then inverts the result. - `"hard-light"` - : Like `overlay`, a combination of `multiply` and `screen` — but instead with the top layer and bottom layer swapped. - `"soft-light"` - : A softer version of `hard-light`. Pure black or white does not result in pure black or white. - `"difference"` - : Subtracts the bottom layer from the top layer — or the other way round — to always get a positive value. - `"exclusion"` - : Like `difference`, but with lower contrast. - `"hue"` - : Preserves the luma and chroma of the bottom layer, while adopting the hue of the top layer. - `"saturation"` - : Preserves the luma and hue of the bottom layer, while adopting the chroma of the top layer. - `"color"` - : Preserves the luma of the bottom layer, while adopting the hue and chroma of the top layer. - `"luminosity"` - : Preserves the hue and chroma of the bottom layer, while adopting the luma of the top layer. ## Examples ### Changing the composite operation This example uses the `globalCompositeOperation` property to draw two rectangles that exclude themselves where they overlap. #### HTML ```html <canvas id="canvas"></canvas> ``` #### JavaScript ```js const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); ctx.globalCompositeOperation = "xor"; ctx.fillStyle = "blue"; ctx.fillRect(10, 10, 100, 100); ctx.fillStyle = "red"; ctx.fillRect(50, 50, 100, 100); ``` #### Result {{ EmbedLiveSample('Changing_the_composite_operation', 700, 180) }} ### Demonstration of all values #### Global values This code sets up the global values used by the rest of the program. ```js const canvas1 = document.createElement("canvas"); const canvas2 = document.createElement("canvas"); const gco = [ "source-over", "source-in", "source-out", "source-atop", "destination-over", "destination-in", "destination-out", "destination-atop", "lighter", "copy", "xor", "multiply", "screen", "overlay", "darken", "lighten", "color-dodge", "color-burn", "hard-light", "soft-light", "difference", "exclusion", "hue", "saturation", "color", "luminosity", ].reverse(); const gcoText = [ "This is the default setting and draws new shapes on top of the existing canvas content.", "The new shape is drawn only where both the new shape and the destination canvas overlap. Everything else is made transparent.", "The new shape is drawn where it doesn't overlap the existing canvas content.", "The new shape is only drawn where it overlaps the existing canvas content.", "New shapes are drawn behind the existing canvas content.", "The existing canvas content is kept where both the new shape and existing canvas content overlap. Everything else is made transparent.", "The existing content is kept where it doesn't overlap the new shape.", "The existing canvas is only kept where it overlaps the new shape. The new shape is drawn behind the canvas content.", "Where both shapes overlap the color is determined by adding color values.", "Only the new shape is shown.", "Shapes are made transparent where both overlap and drawn normal everywhere else.", "The pixels of the top layer are multiplied with the corresponding pixel of the bottom layer. A darker picture is the result.", "The pixels are inverted, multiplied, and inverted again. A lighter picture is the result (opposite of multiply)", "A combination of multiply and screen. Dark parts on the base layer become darker, and light parts become lighter.", "Retains the darkest pixels of both layers.", "Retains the lightest pixels of both layers.", "Divides the bottom layer by the inverted top layer.", "Divides the inverted bottom layer by the top layer, and then inverts the result.", "A combination of multiply and screen like overlay, but with top and bottom layer swapped.", "A softer version of hard-light. Pure black or white does not result in pure black or white.", "Subtracts the bottom layer from the top layer or the other way round to always get a positive value.", "Like difference, but with lower contrast.", "Preserves the luma and chroma of the bottom layer, while adopting the hue of the top layer.", "Preserves the luma and hue of the bottom layer, while adopting the chroma of the top layer.", "Preserves the luma of the bottom layer, while adopting the hue and chroma of the top layer.", "Preserves the hue and chroma of the bottom layer, while adopting the luma of the top layer.", ].reverse(); const width = 320; const height = 340; ``` #### Main program When the page loads, this code runs to set up and run the example: ```js window.onload = () => { // lum in sRGB const lum = { r: 0.33, g: 0.33, b: 0.33, }; // resize canvas canvas1.width = width; canvas1.height = height; canvas2.width = width; canvas2.height = height; lightMix(); colorSphere(); runComposite(); return; }; ``` And this code, `runComposite()`, handles the bulk of the work, relying on a number of utility functions to do the hard parts. ```js function createCanvas() { const canvas = document.createElement("canvas"); canvas.style.background = `url(${op_8x8.data})`; canvas.style.border = "1px solid #000"; canvas.style.margin = "5px"; canvas.width = width / 2; canvas.height = height / 2; return canvas; } function runComposite() { const dl = document.createElement("dl"); document.body.appendChild(dl); while (gco.length) { const pop = gco.pop(); const dt = document.createElement("dt"); dt.textContent = pop; dl.appendChild(dt); const dd = document.createElement("dd"); const p = document.createElement("p"); p.textContent = gcoText.pop(); dd.appendChild(p); const canvasToDrawOn = createCanvas(); const canvasToDrawFrom = createCanvas(); const canvasToDrawResult = createCanvas(); let ctx = canvasToDrawResult.getContext("2d"); ctx.clearRect(0, 0, width, height); ctx.save(); ctx.drawImage(canvas1, 0, 0, width / 2, height / 2); ctx.globalCompositeOperation = pop; ctx.drawImage(canvas2, 0, 0, width / 2, height / 2); ctx.globalCompositeOperation = "source-over"; ctx.fillStyle = "rgb(0 0 0 / 80%)"; ctx.fillRect(0, height / 2 - 20, width / 2, 20); ctx.fillStyle = "#FFF"; ctx.font = "14px arial"; ctx.fillText(pop, 5, height / 2 - 5); ctx.restore(); ctx = canvasToDrawOn.getContext("2d"); ctx.clearRect(0, 0, width, height); ctx.save(); ctx.drawImage(canvas1, 0, 0, width / 2, height / 2); ctx.fillStyle = "rgb(0 0 0 / 80%)"; ctx.fillRect(0, height / 2 - 20, width / 2, 20); ctx.fillStyle = "#FFF"; ctx.font = "14px arial"; ctx.fillText("existing content", 5, height / 2 - 5); ctx.restore(); ctx = canvasToDrawFrom.getContext("2d"); ctx.clearRect(0, 0, width, height); ctx.save(); ctx.drawImage(canvas2, 0, 0, width / 2, height / 2); ctx.fillStyle = "rgb(0 0 0 / 80%)"; ctx.fillRect(0, height / 2 - 20, width / 2, 20); ctx.fillStyle = "#FFF"; ctx.font = "14px arial"; ctx.fillText("new content", 5, height / 2 - 5); ctx.restore(); dd.appendChild(canvasToDrawOn); dd.appendChild(canvasToDrawFrom); dd.appendChild(canvasToDrawResult); dl.appendChild(dd); } } ``` #### Utility functions The program relies on a number of utility functions. ```js const lightMix = () => { const ctx = canvas2.getContext("2d"); ctx.save(); ctx.globalCompositeOperation = "lighter"; ctx.beginPath(); ctx.fillStyle = "rgb(255 0 0 / 100%)"; ctx.arc(100, 200, 100, Math.PI * 2, 0, false); ctx.fill(); ctx.beginPath(); ctx.fillStyle = "rgb(0 0 255 / 100%)"; ctx.arc(220, 200, 100, Math.PI * 2, 0, false); ctx.fill(); ctx.beginPath(); ctx.fillStyle = "rgb(0 255 0 / 100%)"; ctx.arc(160, 100, 100, Math.PI * 2, 0, false); ctx.fill(); ctx.restore(); ctx.beginPath(); ctx.fillStyle = "#f00"; ctx.fillRect(0, 0, 30, 30); ctx.fill(); }; ``` ```js const colorSphere = (element) => { const ctx = canvas1.getContext("2d"); const width = 360; const halfWidth = width / 2; const rotate = (1 / 360) * Math.PI * 2; // per degree const offset = 0; // scrollbar offset const oleft = -20; const otop = -20; for (let n = 0; n <= 359; n++) { const gradient = ctx.createLinearGradient( oleft + halfWidth, otop, oleft + halfWidth, otop + halfWidth, ); const color = Color.HSV_RGB({ H: (n + 300) % 360, S: 100, V: 100 }); gradient.addColorStop(0, "rgb(0 0 0 / 0%)"); gradient.addColorStop(0.7, `rgb(${color.R} ${color.G} ${color.B} / 100%)`); gradient.addColorStop(1, "rgb(255 255 255 / 100%)"); ctx.beginPath(); ctx.moveTo(oleft + halfWidth, otop); ctx.lineTo(oleft + halfWidth, otop + halfWidth); ctx.lineTo(oleft + halfWidth + 6, otop); ctx.fillStyle = gradient; ctx.fill(); ctx.translate(oleft + halfWidth, otop + halfWidth); ctx.rotate(rotate); ctx.translate(-(oleft + halfWidth), -(otop + halfWidth)); } ctx.beginPath(); ctx.fillStyle = "#00f"; ctx.fillRect(15, 15, 30, 30); ctx.fill(); return ctx.canvas; }; ``` ```js // HSV (1978) = H: Hue / S: Saturation / V: Value Color = {}; Color.HSV_RGB = (o) => { const S = o.S / 100; let H = o.H / 360, V = o.V / 100; let R, G; let A, B, C, D; if (S === 0) { R = G = B = Math.round(V * 255); } else { if (H >= 1) H = 0; H *= 6; D = H - Math.floor(H); A = Math.round(255 * V * (1 - S)); B = Math.round(255 * V * (1 - S * D)); C = Math.round(255 * V * (1 - S * (1 - D))); V = Math.round(255 * V); switch (Math.floor(H)) { case 0: R = V; G = C; B = A; break; case 1: R = B; G = V; B = A; break; case 2: R = A; G = V; B = C; break; case 3: R = A; G = B; B = V; break; case 4: R = C; G = A; B = V; break; case 5: R = V; G = A; B = B; break; } } return { R, G, B }; }; const createInterlace = (size, color1, color2) => { const proto = document.createElement("canvas").getContext("2d"); proto.canvas.width = size * 2; proto.canvas.height = size * 2; proto.fillStyle = color1; // top-left proto.fillRect(0, 0, size, size); proto.fillStyle = color2; // top-right proto.fillRect(size, 0, size, size); proto.fillStyle = color2; // bottom-left proto.fillRect(0, size, size, size); proto.fillStyle = color1; // bottom-right proto.fillRect(size, size, size, size); const pattern = proto.createPattern(proto.canvas, "repeat"); pattern.data = proto.canvas.toDataURL(); return pattern; }; const op_8x8 = createInterlace(8, "#FFF", "#eee"); ``` #### Result {{EmbedLiveSample("Demonstration of all values", "100%", 7250)}} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The interface defining this property: {{domxref("CanvasRenderingContext2D")}} - {{domxref("CanvasRenderingContext2D.globalAlpha")}}
0
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d/imagesmoothingenabled/index.md
--- title: "CanvasRenderingContext2D: imageSmoothingEnabled property" short-title: imageSmoothingEnabled slug: Web/API/CanvasRenderingContext2D/imageSmoothingEnabled page-type: web-api-instance-property browser-compat: api.CanvasRenderingContext2D.imageSmoothingEnabled --- {{APIRef}} The **`imageSmoothingEnabled`** property of the {{domxref("CanvasRenderingContext2D")}} interface, part of the [Canvas API](/en-US/docs/Web/API/Canvas_API), determines whether scaled images are smoothed (`true`, default) or not (`false`). On getting the `imageSmoothingEnabled` property, the last value it was set to is returned. This property is useful for games and other apps that use pixel art. When enlarging images, the default resizing algorithm will blur the pixels. Set this property to `false` to retain the pixels' sharpness. > **Note:** You can adjust the smoothing quality with the > {{domxref("CanvasRenderingContext2D.imageSmoothingQuality", "imageSmoothingQuality")}} > property. ## Value A boolean value indicating whether to smooth scaled images or not. The default value is `true`. ## Examples ### Disabling image smoothing This example compares three images. The first image is drawn at its natural size, the second is scaled to 3X and drawn with image smoothing enabled, and the third is scaled to 3X but drawn with image smoothing disabled. #### HTML ```html <canvas id="canvas" width="460" height="210"></canvas> ``` #### JavaScript ```js const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); ctx.font = "16px sans-serif"; ctx.textAlign = "center"; const img = new Image(); img.src = "https://interactive-examples.mdn.mozilla.net/media/examples/star.png"; img.onload = () => { const w = img.width, h = img.height; ctx.fillText("Source", w * 0.5, 20); ctx.drawImage(img, 0, 24, w, h); ctx.fillText("Smoothing = TRUE", w * 2.5, 20); ctx.imageSmoothingEnabled = true; ctx.drawImage(img, w, 24, w * 3, h * 3); ctx.fillText("Smoothing = FALSE", w * 5.5, 20); ctx.imageSmoothingEnabled = false; ctx.drawImage(img, w * 4, 24, w * 3, h * 3); }; ``` #### Result {{ EmbedLiveSample('Disabling_image_smoothing', 700, 240) }} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The interface defining this property: {{domxref("CanvasRenderingContext2D")}} - {{domxref("CanvasRenderingContext2D.imageSmoothingQuality")}} - {{cssxref("image-rendering")}}
0
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d/stroketext/index.md
--- title: "CanvasRenderingContext2D: strokeText() method" short-title: strokeText() slug: Web/API/CanvasRenderingContext2D/strokeText page-type: web-api-instance-method browser-compat: api.CanvasRenderingContext2D.strokeText --- {{APIRef}} The {{domxref("CanvasRenderingContext2D")}} method **`strokeText()`**, part of the Canvas 2D API, strokes — that is, draws the outlines of — the characters of a text string at the specified coordinates. An optional parameter allows specifying a maximum width for the rendered text, which the {{Glossary("user agent")}} will achieve by condensing the text or by using a lower font size. This method draws directly to the canvas without modifying the current path, so any subsequent {{domxref("CanvasRenderingContext2D.fill()", "fill()")}} or {{domxref("CanvasRenderingContext2D.stroke()", "stroke()")}} calls will have no effect on it. > **Note:** Use the {{domxref('CanvasRenderingContext2D.fillText()', 'fillText()')}} method to > fill the text characters rather than having just their outlines drawn. ## Syntax ```js-nolint strokeText(text, x, y) strokeText(text, x, y, maxWidth) ``` ### Parameters - `text` - : A string specifying the text string to render into the context. The text is rendered using the settings specified by {{domxref("CanvasRenderingContext2D.font","font")}}, {{domxref("CanvasRenderingContext2D.textAlign","textAlign")}}, {{domxref("CanvasRenderingContext2D.textBaseline","textBaseline")}}, and {{domxref("CanvasRenderingContext2D.direction","direction")}}. - `x` - : The x-axis coordinate of the point at which to begin drawing the text. - `y` - : The y-axis coordinate of the point at which to begin drawing the text. - `maxWidth` {{optional_inline}} - : The maximum width the text may be once rendered. If not specified, there is no limit to the width of the text. However, if this value is provided, the user agent will adjust the kerning, select a more horizontally condensed font (if one is available or can be generated without loss of quality), or scale down to a smaller font size in order to fit the text in the specified width. ### Return value None ({{jsxref("undefined")}}). ## Examples ### Drawing text outlines This example writes the words "Hello world" using the `strokeText()` method. #### HTML First, we need a canvas to draw into. This code creates a context 400 pixels wide and 150 pixels high. ```html <canvas id="canvas" width="400" height="150"></canvas> ``` #### JavaScript The JavaScript code for this example follows. ```js const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); ctx.font = "50px serif"; ctx.strokeText("Hello world", 50, 90); ``` This code obtains a reference to the {{HTMLElement("canvas")}}, then gets a reference to its 2D graphics context. With that in hand, we set the {{domxref("CanvasRenderingContext2D.font", "font")}} to 50-pixel-tall "serif" (the user's default [serif](https://en.wikipedia.org/wiki/Serif) font), then call `strokeText()` to draw the text "Hello world," starting at the coordinates (50, 90). #### Result {{ EmbedLiveSample('Drawing_text_outlines', 700, 180) }} ### Restricting the text size This example writes the words "Hello world," restricting its width to 140 pixels. #### HTML ```html <canvas id="canvas" width="400" height="150"></canvas> ``` #### JavaScript ```js const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); ctx.font = "50px serif"; ctx.strokeText("Hello world", 50, 90, 140); ``` #### Result {{ EmbedLiveSample('Restricting_the_text_size', 700, 180) }} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Drawing text](/en-US/docs/Web/API/Canvas_API/Tutorial/Drawing_text) - The interface defining this method: {{domxref("CanvasRenderingContext2D")}} - {{domxref("CanvasRenderingContext2D.fillText()")}}
0
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d/ispointinpath/index.md
--- title: "CanvasRenderingContext2D: isPointInPath() method" short-title: isPointInPath() slug: Web/API/CanvasRenderingContext2D/isPointInPath page-type: web-api-instance-method browser-compat: api.CanvasRenderingContext2D.isPointInPath --- {{APIRef}} The **`CanvasRenderingContext2D.isPointInPath()`** method of the Canvas 2D API reports whether or not the specified point is contained in the current path. ## Syntax ```js-nolint isPointInPath(x, y) isPointInPath(x, y, fillRule) isPointInPath(path, x, y) isPointInPath(path, x, y, fillRule) ``` ### Parameters - `x` - : The x-axis coordinate of the point to check, unaffected by the current transformation of the context. - `y` - : The y-axis coordinate of the point to check, unaffected by the current transformation of the context. - `fillRule` - : The algorithm by which to determine if a point is inside or outside the path. Possible values: - `nonzero` - : The [non-zero winding rule](https://en.wikipedia.org/wiki/Nonzero-rule). Default rule. - `evenodd` - : The [even-odd winding rule](https://en.wikipedia.org/wiki/Even%E2%80%93odd_rule). - `path` - : A {{domxref("Path2D")}} path to check against. If unspecified, the current path is used. ### Return value - A boolean value - : A Boolean, which is `true` if the specified point is contained in the current or specified path, otherwise `false`. ## Examples ### Checking a point in the current path This example uses the `isPointInPath()` method to check if a point is within the current path. #### HTML ```html <canvas id="canvas"></canvas> <p>In path: <code id="result">false</code></p> ``` #### JavaScript ```js const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); const result = document.getElementById("result"); ctx.rect(10, 10, 100, 100); ctx.fill(); result.innerText = ctx.isPointInPath(30, 70); ``` #### Result {{ EmbedLiveSample('Checking_a_point_in_the_current_path', 700, 220) }} ### Checking a point in the specified path Whenever you move the mouse, this example checks whether the cursor is in a circular `Path2D` path. If yes, the circle becomes green, otherwise it is red. #### HTML ```html <canvas id="canvas"></canvas> ``` #### JavaScript ```js const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); // Create circle const circle = new Path2D(); circle.arc(150, 75, 50, 0, 2 * Math.PI); ctx.fillStyle = "red"; ctx.fill(circle); // Listen for mouse moves canvas.addEventListener("mousemove", (event) => { // Check whether point is inside circle const isPointInPath = ctx.isPointInPath(circle, event.offsetX, event.offsetY); ctx.fillStyle = isPointInPath ? "green" : "red"; // Draw circle ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.fill(circle); }); ``` #### Result {{ EmbedLiveSample('Checking_a_point_in_the_specified_path', 700, 180) }} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ### Gecko-specific note - Prior to Gecko 7.0 (Firefox 7.0 / Thunderbird 7.0 / SeaMonkey 2.4), this method incorrectly failed to multiply the specified point's coordinates by the current transformation matrix before comparing it to the path. Now this method works correctly even if the context is rotated, scaled, or otherwise transformed. ## See also - The interface defining this method: {{domxref("CanvasRenderingContext2D")}}
0
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d/getimagedata/index.md
--- title: "CanvasRenderingContext2D: getImageData() method" short-title: getImageData() slug: Web/API/CanvasRenderingContext2D/getImageData page-type: web-api-instance-method browser-compat: api.CanvasRenderingContext2D.getImageData --- {{APIRef("Canvas API")}} The {{domxref("CanvasRenderingContext2D")}} method **`getImageData()`** of the Canvas 2D API returns an {{domxref("ImageData")}} object representing the underlying pixel data for a specified portion of the canvas. This method is not affected by the canvas's transformation matrix. If the specified rectangle extends outside the bounds of the canvas, the pixels outside the canvas are transparent black in the returned `ImageData` object. > **Note:** Image data can be painted onto a canvas using the > {{domxref("CanvasRenderingContext2D.putImageData()", "putImageData()")}} method. You can find more information about `getImageData()` and general manipulation of canvas contents in [Pixel manipulation with canvas](/en-US/docs/Web/API/Canvas_API/Tutorial/Pixel_manipulation_with_canvas). ## Syntax ```js-nolint getImageData(sx, sy, sw, sh) getImageData(sx, sy, sw, sh, settings) ``` ### Parameters - `sx` - : The x-axis coordinate of the top-left corner of the rectangle from which the `ImageData` will be extracted. - `sy` - : The y-axis coordinate of the top-left corner of the rectangle from which the `ImageData` will be extracted. - `sw` - : The width of the rectangle from which the `ImageData` will be extracted. Positive values are to the right, and negative to the left. - `sh` - : The height of the rectangle from which the `ImageData` will be extracted. Positive values are down, and negative are up. - `settings` {{optional_inline}} - : An object with the following properties: - `colorSpace`: Specifies the color space of the image data. Can be set to `"srgb"` for the [sRGB color space](https://en.wikipedia.org/wiki/SRGB) or `"display-p3"` for the [display-p3 color space](https://en.wikipedia.org/wiki/DCI-P3). ### Return value An {{domxref("ImageData")}} object containing the image data for the rectangle of the canvas specified. The coordinates of the rectangle's top-left corner are `(sx, sy)`, while the coordinates of the bottom corner are `(sx + sw - 1, sy + sh - 1)`. ### Exceptions - `IndexSizeError` {{domxref("DOMException")}} - : Thrown if either `sw` or `sh` are zero. - `SecurityError` {{domxref("DOMException")}} - : The canvas contains or may contain pixels which were loaded from an origin other than the one from which the document itself was loaded. To avoid a `SecurityError` {{domxref("DOMException")}} being thrown in this situation, configure CORS to allow the source image to be used in this way. See [Allowing cross-origin use of images and canvas](/en-US/docs/Web/HTML/CORS_enabled_image). ## Examples ### Getting image data from a canvas This example draws an image, and then uses `getImageData()` to grab a portion of the canvas. We use `getImageData()` to extract a slice of the image, starting at `(10, 20)`, with a width of `80` and a height of `230`. We then draw this slice three times, positioning the slices progressively below and to the right of the last slice. #### HTML ```html <canvas id="canvas" width="700" height="400"></canvas> ``` #### JavaScript ```js const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); const image = new Image(); image.src = "plumeria.jpg"; image.addEventListener("load", () => { ctx.drawImage(image, 0, 0, 233, 320); const imageData = ctx.getImageData(10, 20, 80, 230); ctx.putImageData(imageData, 260, 0); ctx.putImageData(imageData, 380, 50); ctx.putImageData(imageData, 500, 100); }); ``` #### Result {{EmbedLiveSample("Getting_image_data_from_a_canvas", "", 420)}} ### Color space conversion The optional `colorSpace` setting allows you to get image data in the desired format. ```js const context = canvas.getContext("2d", { colorSpace: "display-p3" }); context.fillStyle = "color(display-p3 0.5 0 0)"; context.fillRect(0, 0, 10, 10); // Get ImageData converted to sRGB const imageData = context.getImageData(0, 0, 1, 1, { colorSpace: "srgb" }); console.log(imageData.colorSpace); // "srgb" ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The interface defining this method: {{domxref("CanvasRenderingContext2D")}} - {{domxref("ImageData")}} object - {{domxref("CanvasRenderingContext2D.putImageData()")}} - [Pixel manipulation with canvas](/en-US/docs/Web/API/Canvas_API/Tutorial/Pixel_manipulation_with_canvas)
0
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d/createimagedata/index.md
--- title: "CanvasRenderingContext2D: createImageData() method" short-title: createImageData() slug: Web/API/CanvasRenderingContext2D/createImageData page-type: web-api-instance-method browser-compat: api.CanvasRenderingContext2D.createImageData --- {{APIRef}} The **`CanvasRenderingContext2D.createImageData()`** method of the Canvas 2D API creates a new, blank {{domxref("ImageData")}} object with the specified dimensions. All of the pixels in the new object are transparent black. ## Syntax ```js-nolint createImageData(width, height) createImageData(width, height, settings) createImageData(imagedata) ``` ### Parameters - `width` - : The width to give the new `ImageData` object. A negative value flips the rectangle around the vertical axis. - `height` - : The height to give the new `ImageData` object. A negative value flips the rectangle around the horizontal axis. - `settings` {{optional_inline}} - : An object with the following properties: - `colorSpace`: Specifies the color space of the image data. Can be set to `"srgb"` for the [sRGB color space](https://en.wikipedia.org/wiki/SRGB) or `"display-p3"` for the [display-p3 color space](https://en.wikipedia.org/wiki/DCI-P3). - `imagedata` - : An existing `ImageData` object from which to copy the width and height. The image itself is **not** copied. ### Return value A new {{domxref("ImageData")}} object with the specified width and height. The new object is filled with transparent black pixels. ### Exceptions - `IndexSizeError` {{domxref("DOMException")}} - : Thrown if either of the `width` or `height` arguments is zero. ## Examples ### Creating a blank ImageData object This snippet creates a blank `ImageData` object using the `createImageData()` method. ```html <canvas id="canvas"></canvas> ``` The generated object is 100 pixels wide and 50 pixels tall, making 5,000 pixels in all. Each pixel within an `ImageData` object consists of four array values, so the object's {{domxref("ImageData.data", "data")}} property has a length of 4 × 5,000, or 20,000. ```js const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); const imageData = ctx.createImageData(100, 50); console.log(imageData); // ImageData { width: 100, height: 50, data: Uint8ClampedArray[20000] } ``` ### Filling a blank ImageData object This example creates and fills a new `ImageData` object with purple pixels. ```html <canvas id="canvas"></canvas> ``` Since each pixel consists of four values, the `for` loop iterates by multiples of four. The array values associated with each pixel are R (red), G (green), B (blue), and A (alpha), in that order. ```js const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); const imageData = ctx.createImageData(100, 100); // Iterate through every pixel for (let i = 0; i < imageData.data.length; i += 4) { // Modify pixel data imageData.data[i + 0] = 190; // R value imageData.data[i + 1] = 0; // G value imageData.data[i + 2] = 210; // B value imageData.data[i + 3] = 255; // A value } // Draw image data to the canvas ctx.putImageData(imageData, 20, 20); ``` #### Result {{EmbedLiveSample("Filling_a_blank_ImageData_object", 700, 180)}} ### More examples For more examples using `createImageData()` and the `ImageData` object, see [Pixel manipulation with canvas](/en-US/docs/Web/API/Canvas_API/Tutorial/Pixel_manipulation_with_canvas) and {{domxref("ImageData.data")}}. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The interface defining this method: {{domxref("CanvasRenderingContext2D")}} - {{domxref("ImageData")}} - [Pixel manipulation with canvas](/en-US/docs/Web/API/Canvas_API/Tutorial/Pixel_manipulation_with_canvas)
0
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d/iscontextlost/index.md
--- title: "CanvasRenderingContext2D: isContextLost() method" short-title: isContextLost() slug: Web/API/CanvasRenderingContext2D/isContextLost page-type: web-api-instance-method status: - experimental browser-compat: api.CanvasRenderingContext2D.isContextLost --- {{APIRef}}{{SeeCompatTable}} The **`CanvasRenderingContext2D.isContextLost()`** method of the Canvas 2D API returns `true` if the rendering context is lost (and has not yet been reset). This might occur due to driver crashes, running out of memory, and so on. If the user agent detects that the canvas backing storage is lost it will fire the [`contextlost` event](/en-US/docs/Web/API/HTMLCanvasElement/contextlost_event) at the associated [`HTMLCanvasElement`](/en-US/docs/Web/API/HTMLCanvasElement). If this event is not cancelled it will attempt to reset the backing storage to the default state (this is equivalent to calling {{domxref("CanvasRenderingContext2D.reset()")}}). On success it will fire the [`contextrestored` event](/en-US/docs/Web/API/HTMLCanvasElement/contextrestored_event), indicating that the context is ready to reinitialize and redraw. ## Syntax ```js-nolint isContextLost() ``` ### Parameters None. ### Return value `true` if the rendering context was lost; `false` otherwise. ### Examples ```js const ctx = canvas.getContext("2d"); if (ctx.isContextLost()) { console.log("Context is lost"); } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The interface defining this method: {{domxref("CanvasRenderingContext2D")}} - [`HTMLCanvasElement: contextlost` event](/en-US/docs/Web/API/HTMLCanvasElement/contextlost_event) - [`HTMLCanvasElement: contextrestored` event](/en-US/docs/Web/API/HTMLCanvasElement/contextrestored_event)
0
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d/fill/index.md
--- title: "CanvasRenderingContext2D: fill() method" short-title: fill() slug: Web/API/CanvasRenderingContext2D/fill page-type: web-api-instance-method browser-compat: api.CanvasRenderingContext2D.fill --- {{APIRef}} The **`CanvasRenderingContext2D.fill()`** method of the Canvas 2D API fills the current or given path with the current {{domxref("CanvasRenderingContext2D.fillStyle", "fillStyle")}}. ## Syntax ```js-nolint fill() fill(path) fill(fillRule) fill(path, fillRule) ``` ### Parameters - `fillRule` - : The algorithm by which to determine if a point is inside or outside the filling region. Possible values: - `nonzero` - : The [non-zero winding rule](https://en.wikipedia.org/wiki/Nonzero-rule). Default rule. - `evenodd` - : The [even-odd winding rule](https://en.wikipedia.org/wiki/Even%E2%80%93odd_rule). - `path` - : A {{domxref("Path2D")}} path to fill. ### Return value None ({{jsxref("undefined")}}). ## Examples ### Filling a rectangle This example fills a rectangle with the `fill()` method. #### HTML ```html <canvas id="canvas"></canvas> ``` #### JavaScript ```js const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); ctx.rect(10, 10, 150, 100); ctx.fill(); ``` #### Result {{ EmbedLiveSample('Filling_a_rectangle', 700, 180) }} ### Specifying a path and a fillRule This example saves some intersecting lines to a Path2D object. The `fill()` method is then used to render the object to the canvas. A hole is left unfilled in the object's center by using the `"evenodd"` rule; by default (with the `"nonzero"` rule), the hole would also be filled. #### HTML ```html <canvas id="canvas"></canvas> ``` #### JavaScript ```js const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); // Create path let region = new Path2D(); region.moveTo(30, 90); region.lineTo(110, 20); region.lineTo(240, 130); region.lineTo(60, 130); region.lineTo(190, 20); region.lineTo(270, 90); region.closePath(); // Fill path ctx.fillStyle = "green"; ctx.fill(region, "evenodd"); ``` #### Result {{ EmbedLiveSample('Specifying_a_path_and_a_fillRule', 700, 180) }} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The interface defining this method: {{domxref("CanvasRenderingContext2D")}} - {{domxref("CanvasRenderingContext2D.fillStyle")}}
0
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d/fontstretch/index.md
--- title: "CanvasRenderingContext2D: fontStretch property" short-title: fontStretch slug: Web/API/CanvasRenderingContext2D/fontStretch page-type: web-api-instance-property browser-compat: api.CanvasRenderingContext2D.fontStretch --- {{APIRef}} The **`CanvasRenderingContext2D.fontStretch`** property of the [Canvas API](/en-US/docs/Web/API/Canvas_API) specifies how the font may be expanded or condensed when drawing text. The property corresponds to the [`font-stretch`](/en-US/docs/Web/CSS/font-stretch) CSS property when used with keywords (percentage values are not supported). ## Value The font stretch value as a string. This is one of: `ultra-condensed`, `extra-condensed`, `condensed`, `semi-condensed`, `normal` (default), `semi-expanded`, `expanded`, `extra-expanded`, `ultra-expanded`. The property can be used to get or set the font stretch value. ## Examples In this example we display the text "Hello World" using each of the supported values of the `fontStretch` property. The stretch value is also displayed for each case by reading the property. ### HTML ```html <canvas id="canvas" width="700" height="310"></canvas> ``` ### JavaScript First we get the canvas declared in the HTML file and use it to get the `CanvasRenderingContext2D` that will later be used for drawing text. ```js const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); ``` The next step in the example is to load a variable font that can be varied in the width axis. This is needed because `fontStretch` can only stretch a font that contains information about how glyphs are drawn when stretched — otherwise text will be drawn using the closest available font stretch value for the font, which will often be the normal width. In this case we use [`FontFace`](/en-US/docs/Web/API/FontFace) to define a font face for the [Inconsolata](https://fonts.google.com/specimen/Inconsolata/tester) Google Font, which supports font widths from 50% to 200% (allowing us to demonstrate `fontStretch` values from `ultra-condensed` to `ultra-expanded`). We then add this to the document's [`FontFaceSet`](/en-US/docs/Web/API/FontFaceSet) ([`document.fonts`](/en-US/docs/Web/API/Document/fonts)) so that it can be used for drawing. ```js const fontFile = new FontFace( "Inconsolata", 'url(https://fonts.gstatic.com/s/inconsolata/v31/QlddNThLqRwH-OJ1UHjlKENVzlm-WkL3GZQmAwPyya15.woff2) format("woff2")', { stretch: "50% 200%" }, ); document.fonts.add(fontFile); ``` The code below then calls [`FontFaceSet.load()`](/en-US/docs/Web/API/FontFaceSet/load) to fetch and load the Google Font. Note that this call sets the size of the font that is needed, and returns a promise that resolves when the font has been loaded. We then assign the font face we downloaded to the context, and use the context to draw text to the canvas at each of the keyword stretch levels. Note that again the size of the desired font is specified (this does not have to match the loaded font size). ```js document.fonts.load("30px Inconsolata").then( () => { ctx.font = "30px 'Inconsolata'"; // Default (normal) ctx.fillText(`Hello world (default: ${ctx.fontStretch})`, 5, 20); ctx.fontStretch = "ultra-condensed"; ctx.fillText(`Hello world (${ctx.fontStretch})`, 5, 50); ctx.fontStretch = "extra-condensed"; ctx.fillText(`Hello world (${ctx.fontStretch})`, 5, 80); ctx.fontStretch = "condensed"; ctx.fillText(`Hello world (${ctx.fontStretch})`, 5, 110); ctx.fontStretch = "semi-condensed"; ctx.fillText(`Hello world (${ctx.fontStretch})`, 5, 140); ctx.fontStretch = "extra-condensed"; ctx.fillText(`Hello world (${ctx.fontStretch})`, 5, 170); ctx.fontStretch = "semi-expanded"; ctx.fillText(`Hello world (${ctx.fontStretch})`, 5, 200); ctx.fontStretch = "expanded"; ctx.fillText(`Hello world (${ctx.fontStretch})`, 5, 230); ctx.fontStretch = "extra-expanded"; ctx.fillText(`Hello world (${ctx.fontStretch})`, 5, 260); ctx.fontStretch = "ultra-expanded"; ctx.fillText(`Hello world (${ctx.fontStretch})`, 5, 290); }, (err) => { console.error(err); }, ); ``` ### Result {{ EmbedLiveSample('Examples', 700, 300) }} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d/filltext/index.md
--- title: "CanvasRenderingContext2D: fillText() method" short-title: fillText() slug: Web/API/CanvasRenderingContext2D/fillText page-type: web-api-instance-method browser-compat: api.CanvasRenderingContext2D.fillText --- {{APIRef("HTML DOM")}} The {{domxref("CanvasRenderingContext2D")}} method **`fillText()`**, part of the Canvas 2D API, draws a text string at the specified coordinates, filling the string's characters with the current {{domxref("CanvasRenderingContext2D.fillStyle", "fillStyle")}}. An optional parameter allows specifying a maximum width for the rendered text, which the {{Glossary("user agent")}} will achieve by condensing the text or by using a lower font size. This method draws directly to the canvas without modifying the current path, so any subsequent {{domxref("CanvasRenderingContext2D.fill()", "fill()")}} or {{domxref("CanvasRenderingContext2D.stroke()", "stroke()")}} calls will have no effect on it. The text is rendered using the font and text layout configuration as defined by the {{domxref("CanvasRenderingContext2D.font","font")}}, {{domxref("CanvasRenderingContext2D.textAlign","textAlign")}}, {{domxref("CanvasRenderingContext2D.textBaseline","textBaseline")}}, and {{domxref("CanvasRenderingContext2D.direction","direction")}} properties. > **Note:** To draw the outlines of the characters in a string, call the context's > {{domxref("CanvasRenderingContext2D.strokeText", "strokeText()")}} method. ## Syntax ```js-nolint fillText(text, x, y) fillText(text, x, y, maxWidth) ``` ### Parameters - `text` - : A string specifying the text string to render into the context. The text is rendered using the settings specified by {{domxref("CanvasRenderingContext2D.font","font")}}, {{domxref("CanvasRenderingContext2D.textAlign","textAlign")}}, {{domxref("CanvasRenderingContext2D.textBaseline","textBaseline")}}, and {{domxref("CanvasRenderingContext2D.direction","direction")}}. - `x` - : The x-axis coordinate of the point at which to begin drawing the text, in pixels. - `y` - : The y-axis coordinate of the baseline on which to begin drawing the text, in pixels. - `maxWidth` {{optional_inline}} - : The maximum number of pixels wide the text may be once rendered. If not specified, there is no limit to the width of the text. However, if this value is provided, the user agent will adjust the kerning, select a more horizontally condensed font (if one is available or can be generated without loss of quality), or scale down to a smaller font size in order to fit the text in the specified width. ### Return value None ({{jsxref("undefined")}}). ## Examples ### Drawing filled text This example writes the words "Hello world" using the `fillText()` method. #### HTML First, we need a canvas to draw into. This code creates a context 400 pixels wide and 150 pixels across. ```html <canvas id="canvas" width="400" height="150"></canvas> ``` #### JavaScript The JavaScript code for this example follows. ```js const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); ctx.font = "50px serif"; ctx.fillText("Hello world", 50, 90); ``` This code obtains a reference to the {{HTMLElement("canvas")}}, then gets a reference to its 2D graphics context. With that in hand, we set the {{domxref("CanvasRenderingContext2D.font", "font")}} to 50-pixel-tall "serif" (the user's default [serif](https://en.wikipedia.org/wiki/Serif) font), then call `fillText()` to draw the text "Hello world," starting at the coordinates (50, 90). #### Result {{ EmbedLiveSample('Drawing_filled_text', 700, 180) }} ### Restricting the text size This example writes the words "Hello world," restricting its width to 140 pixels. #### HTML ```html <canvas id="canvas" width="400" height="150"></canvas> ``` #### JavaScript ```js const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); ctx.font = "50px serif"; ctx.fillText("Hello world", 50, 90, 140); ``` #### Result {{ EmbedLiveSample('Restricting_the_text_size', 700, 180) }} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Drawing text](/en-US/docs/Web/API/Canvas_API/Tutorial/Drawing_text) - {{domxref("CanvasRenderingContext2D")}} - {{domxref("CanvasRenderingContext2D.strokeText()")}}
0
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d/clip/index.md
--- title: "CanvasRenderingContext2D: clip() method" short-title: clip() slug: Web/API/CanvasRenderingContext2D/clip page-type: web-api-instance-method browser-compat: api.CanvasRenderingContext2D.clip --- {{APIRef}} The **`CanvasRenderingContext2D.clip()`** method of the Canvas 2D API turns the current or given path into the current clipping region. The previous clipping region, if any, is intersected with the current or given path to create the new clipping region. In the image below, the red outline represents a clipping region shaped like a star. Only those parts of the checkerboard pattern that are within the clipping region get drawn. ![Star-shaped clipping region](canvas_clipping_path.png) > **Note:** Be aware that the clipping region is only constructed from > shapes added to the path. It doesn't work with shape primitives drawn directly to the > canvas, such as {{domxref("CanvasRenderingContext2D.fillRect()","fillRect()")}}. > Instead, you'd have to use {{domxref("CanvasRenderingContext2D.rect()","rect()")}} to > add a rectangular shape to the path before calling `clip()`. > **Note:** Clip paths cannot be reverted directly. You must save your canvas state using {{domxref("CanvasRenderingContext2D/save", "save()")}} before calling `clip()`, and restore it once you have finished drawing in the clipped area using {{domxref("CanvasRenderingContext2D/restore", "restore()")}}. ## Syntax ```js-nolint clip() clip(path) clip(fillRule) clip(path, fillRule) ``` ### Parameters - `fillRule` - : The algorithm by which to determine if a point is inside or outside the clipping region. Possible values: - `nonzero` - : The [non-zero winding rule](https://en.wikipedia.org/wiki/Nonzero-rule). Default rule. - `evenodd` - : The [even-odd winding rule](https://en.wikipedia.org/wiki/Even%E2%80%93odd_rule). - `path` - : A {{domxref("Path2D")}} path to use as the clipping region. ### Return value None ({{jsxref("undefined")}}). ## Examples ### A simple clipping region This example uses the `clip()` method to create a clipping region according to the shape of a circular arc. Two rectangles are then drawn; only those parts within the clipping region are rendered. #### HTML ```html <canvas id="canvas"></canvas> ``` #### JavaScript The clipping region is a full circle, with its center at (100, 75), and a radius of 50. ```js const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); // Create circular clipping region ctx.beginPath(); ctx.arc(100, 75, 50, 0, Math.PI * 2); ctx.clip(); // Draw stuff that gets clipped ctx.fillStyle = "blue"; ctx.fillRect(0, 0, canvas.width, canvas.height); ctx.fillStyle = "orange"; ctx.fillRect(0, 0, 100, 100); ``` #### Result {{ EmbedLiveSample('A_simple_clipping_region', 700, 180) }} ### Specifying a path and a fillRule This example saves two rectangles to a Path2D object, which is then made the current clipping region using the `clip()` method. The `"evenodd"` rule creates a hole where the clipping rectangles intersect; by default (with the `"nonzero"` rule), there would be no hole. #### HTML ```html <canvas id="canvas"></canvas> ``` #### JavaScript ```js const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); // Create clipping path let region = new Path2D(); region.rect(80, 10, 20, 130); region.rect(40, 50, 100, 50); ctx.clip(region, "evenodd"); // Draw stuff that gets clipped ctx.fillStyle = "blue"; ctx.fillRect(0, 0, canvas.width, canvas.height); ``` #### Result {{ EmbedLiveSample('Specifying_a_path_and_a_fillRule', 700, 180) }} ### Creating a complex clipping region This example uses two paths, a rectangle and a square to create a complex clipping region. The `clip()` method is called twice, first to set the current clipping region to the circle using a `Path2D` object, then again to intersect the circle clipping region with a square. The final clipping region is a shape representing the intersection of the circle and the square. #### HTML ```html <canvas id="canvas"></canvas> ``` #### JavaScript ```js const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); // Create two clipping paths let circlePath = new Path2D(); circlePath.arc(150, 75, 75, 0, 2 * Math.PI); let squarePath = new Path2D(); squarePath.rect(85, 10, 130, 130); // Set the clip to the circle ctx.clip(circlePath); // Set the clip to be the intersection of the circle and the square ctx.clip(squarePath); // Draw stuff that gets clipped ctx.fillStyle = "blue"; ctx.fillRect(0, 0, canvas.width, canvas.height); ``` #### Result {{ EmbedLiveSample('Creating_a_complex_clipping_region', 300, 150) }} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The interface defining this method: {{domxref("CanvasRenderingContext2D")}}
0
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d/beginpath/index.md
--- title: "CanvasRenderingContext2D: beginPath() method" short-title: beginPath() slug: Web/API/CanvasRenderingContext2D/beginPath page-type: web-api-instance-method browser-compat: api.CanvasRenderingContext2D.beginPath --- {{APIRef}} The **`CanvasRenderingContext2D.beginPath()`** method of the Canvas 2D API starts a new path by emptying the list of sub-paths. Call this method when you want to create a new path. > **Note:** To create a new sub-path, i.e., one matching the current > canvas state, you can use {{domxref("CanvasRenderingContext2D.moveTo()")}}. ## Syntax ```js-nolint beginPath() ``` ### Parameters None. ### Return value None ({{jsxref("undefined")}}). ## Examples ### Creating distinct paths This example creates two paths, each of which contains a single line. #### HTML ```html <canvas id="canvas"></canvas> ``` #### JavaScript The `beginPath()` method is called before beginning each line, so that they may be drawn with different colors. ```js const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); // First path ctx.beginPath(); ctx.strokeStyle = "blue"; ctx.moveTo(20, 20); ctx.lineTo(200, 20); ctx.stroke(); // Second path ctx.beginPath(); ctx.strokeStyle = "green"; ctx.moveTo(20, 20); ctx.lineTo(120, 120); ctx.stroke(); ``` #### Result {{ EmbedLiveSample('Creating_distinct_paths', 700, 180) }} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The interface defining this method: {{domxref("CanvasRenderingContext2D")}} - {{domxref("CanvasRenderingContext2D.closePath()")}}
0
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d/canvas/index.md
--- title: "CanvasRenderingContext2D: canvas property" short-title: canvas slug: Web/API/CanvasRenderingContext2D/canvas page-type: web-api-instance-property browser-compat: api.CanvasRenderingContext2D.canvas --- {{APIRef}} The **`CanvasRenderingContext2D.canvas`** property, part of the [Canvas API](/en-US/docs/Web/API/Canvas_API), is a read-only reference to the {{domxref("HTMLCanvasElement")}} object that is associated with a given context. It might be [`null`](/en-US/docs/Web/JavaScript/Reference/Operators/null) if there is no associated {{HTMLElement("canvas")}} element. ## Value A {{domxref("HTMLCanvasElement")}} object. ## Examples Given this {{HTMLElement("canvas")}} element: ```html <canvas id="canvas"></canvas> ``` … you can get a reference to the canvas element within the `CanvasRenderingContext2D` by using the `canvas` property: ```js const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); ctx.canvas; // HTMLCanvasElement ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("CanvasRenderingContext2D")}} interface - [Canvas API](/en-US/docs/Web/API/Canvas_API)
0
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d/shadowcolor/index.md
--- title: "CanvasRenderingContext2D: shadowColor property" short-title: shadowColor slug: Web/API/CanvasRenderingContext2D/shadowColor page-type: web-api-instance-property browser-compat: api.CanvasRenderingContext2D.shadowColor --- {{APIRef}} The **`CanvasRenderingContext2D.shadowColor`** property of the Canvas 2D API specifies the color of shadows. Be aware that the shadow's rendered opacity will be affected by the opacity of the {{domxref("CanvasRenderingContext2D.fillStyle", "fillStyle")}} color when filling, and of the {{domxref("CanvasRenderingContext2D.strokeStyle", "strokeStyle")}} color when stroking. > **Note:** Shadows are only drawn if the `shadowColor` > property is set to a non-transparent value. One of the > {{domxref("CanvasRenderingContext2D.shadowBlur", "shadowBlur")}}, > {{domxref("CanvasRenderingContext2D.shadowOffsetX", "shadowOffsetX")}}, or > {{domxref("CanvasRenderingContext2D.shadowOffsetY", "shadowOffsetY")}} properties must > be non-zero, as well. ## Value A string parsed as a [CSS](/en-US/docs/Web/CSS) {{cssxref("&lt;color&gt;")}} value. The default value is fully-transparent black. ## Examples ### Adding a shadow to shapes This example adds a shadow to two squares; the first one is filled, and the second one is stroked. The `shadowColor` property sets the shadows' color, while `shadowOffsetX` and `shadowOffsetY` set their position relative to the shapes. #### HTML ```html <canvas id="canvas"></canvas> ``` #### JavaScript ```js const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); // Shadow ctx.shadowColor = "red"; ctx.shadowOffsetX = 10; ctx.shadowOffsetY = 10; // Filled rectangle ctx.fillRect(20, 20, 100, 100); // Stroked rectangle ctx.lineWidth = 6; ctx.strokeRect(170, 20, 100, 100); ``` #### Result {{ EmbedLiveSample('Adding_a_shadow_to_shapes', 700, 180) }} ### Shadows on translucent shapes A shadow's opacity is affected by the transparency level of its parent object (even when `shadowColor` specifies a completely opaque value). This example strokes and fills a rectangle with translucent colors. #### HTML ```html <canvas id="canvas"></canvas> ``` #### JavaScript The resulting alpha value of the fill shadow is `.8 * .2`, or `.16`. The alpha of the stroke shadow is `.8 * .6`, or `.48`. ```js const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); // Shadow ctx.shadowColor = "rgb(255 0 0 / 80%)"; ctx.shadowBlur = 8; ctx.shadowOffsetX = 30; ctx.shadowOffsetY = 20; // Filled rectangle ctx.fillStyle = "rgb(0 255 0 / 20%)"; ctx.fillRect(10, 10, 150, 100); // Stroked rectangle ctx.lineWidth = 10; ctx.strokeStyle = "rgb(0 0 255 / 60%)"; ctx.strokeRect(10, 10, 150, 100); ``` #### Result {{ EmbedLiveSample('Shadows_on_translucent_shapes', 700, 180) }} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ### WebKit/Blink-specific notes In WebKit- and Blink-based browsers, the non-standard and deprecated method `ctx.setShadow()` is implemented besides this property. ```js setShadow(width, height, blur, color, alpha); setShadow(width, height, blur, graylevel, alpha); setShadow(width, height, blur, r, g, b, a); setShadow(width, height, blur, c, m, y, k, a); ``` ## See also - The interface defining this property: {{domxref("CanvasRenderingContext2D")}}
0
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d/fillstyle/index.md
--- title: "CanvasRenderingContext2D: fillStyle property" short-title: fillStyle slug: Web/API/CanvasRenderingContext2D/fillStyle page-type: web-api-instance-property browser-compat: api.CanvasRenderingContext2D.fillStyle --- {{APIRef}} The **`CanvasRenderingContext2D.fillStyle`** property of the [Canvas 2D API](/en-US/docs/Web/API/Canvas_API) specifies the color, gradient, or pattern to use inside shapes. The default style is `#000` (black). > **Note:** For more examples of fill and stroke styles, see [Applying styles and color](/en-US/docs/Web/API/Canvas_API/Tutorial/Applying_styles_and_colors) in the [Canvas tutorial](/en-US/docs/Web/API/Canvas_API/Tutorial). ## Value One of the following: - A string parsed as CSS {{cssxref("&lt;color&gt;")}} value. - A {{domxref("CanvasGradient")}} object (a linear or radial gradient). - A {{domxref("CanvasPattern")}} object (a repeating image). ## Examples ### Changing the fill color of a shape This example applies a blue fill color to a rectangle. #### HTML ```html <canvas id="canvas"></canvas> ``` #### JavaScript ```js const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); ctx.fillStyle = "blue"; ctx.fillRect(10, 10, 100, 100); ``` #### Result {{ EmbedLiveSample('Changing_the_fill_color_of_a_shape', 700, 160) }} ### Creating multiple fill colors using loops In this example, we use two `for` loops to draw a grid of rectangles, each having a different fill color. To achieve this, we use the two variables `i` and `j` to generate a unique RGB color for each square, and only modify the red and green values. (The blue channel has a fixed value.) By modifying the channels, you can generate all kinds of palettes. ```html hidden <canvas id="canvas" width="150" height="150"></canvas> ``` ```js const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); for (let i = 0; i < 6; i++) { for (let j = 0; j < 6; j++) { ctx.fillStyle = `rgb( ${Math.floor(255 - 42.5 * i)} ${Math.floor(255 - 42.5 * j)} 0)`; ctx.fillRect(j * 25, i * 25, 25, 25); } } ``` The result looks like this: {{EmbedLiveSample("Creating_multiple_fill_colors_using_loops", 160, 160, "canvas_fillstyle.png")}} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ### WebKit/Blink-specific note In WebKit- and Blink-based browsers, the non-standard and deprecated method `ctx.setFillColor()` is implemented in addition to this property. ```js setFillColor(color, /* (optional) */ alpha); setFillColor(grayLevel, /* (optional) */ alpha); setFillColor(r, g, b, a); setFillColor(c, m, y, k, a); ``` ## See also - [Canvas API](/en-US/docs/Web/API/Canvas_API) - The interface defining this property: {{domxref("CanvasRenderingContext2D")}} - Values used by this property: - {{cssxref("&lt;color&gt;")}} CSS data type - {{domxref("CanvasGradient")}} object - {{domxref("CanvasPattern")}} object
0
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d/scrollpathintoview/index.md
--- title: "CanvasRenderingContext2D: scrollPathIntoView() method" short-title: scrollPathIntoView() slug: Web/API/CanvasRenderingContext2D/scrollPathIntoView page-type: web-api-instance-method status: - experimental browser-compat: api.CanvasRenderingContext2D.scrollPathIntoView --- {{APIRef}} {{SeeCompatTable}} The **`CanvasRenderingContext2D.scrollPathIntoView()`** method of the Canvas 2D API scrolls the current or given path into view. It is similar to {{domxref("Element.scrollIntoView()")}}. ## Syntax ```js-nolint scrollPathIntoView() scrollPathIntoView(path) ``` ### Parameters - `path` - : A {{domxref("Path2D")}} path to use. ### Return value None ({{jsxref("undefined")}}). ## Examples ### Using the scrollPathIntoView method This example demonstrates the `scrollPathIntoView()` method. #### HTML ```html <canvas id="canvas"></canvas> ``` #### JavaScript ```js const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); ctx.beginPath(); ctx.fillRect(10, 10, 30, 30); ctx.scrollPathIntoView(); ``` #### Editable demo Edit the code below to see your changes update live in the canvas: ```html hidden <canvas id="canvas" width="400" height="200" class="playable-canvas"> <input id="button" type="range" min="1" max="12" /> </canvas> <div class="playable-buttons"> <input id="edit" type="button" value="Edit" /> <input id="reset" type="button" value="Reset" /> </div> <textarea id="code" class="playable-code"> ctx.beginPath(); ctx.rect(10, 10, 30, 30); ctx.fill(); if (ctx.scrollPathIntoView) { ctx.scrollPathIntoView(); } else { ctx.fillText("Your browser does not support 'scrollPathIntoView()'.", 0, 150); } </textarea> ``` ```js hidden 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); ``` {{ EmbedLiveSample('Editable_demo', 700, 400) }} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The interface defining this method: {{domxref("CanvasRenderingContext2D")}} - {{domxref("Element.scrollIntoView()")}}
0
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d/roundrect/index.md
--- title: "CanvasRenderingContext2D: roundRect() method" short-title: roundRect() slug: Web/API/CanvasRenderingContext2D/roundRect page-type: web-api-instance-method browser-compat: api.CanvasRenderingContext2D.roundRect --- {{APIRef}} The **`CanvasRenderingContext2D.roundRect()`** method of the Canvas 2D API adds a rounded rectangle to the current path. The radii of the corners can be specified in much the same way as the CSS [`border-radius`](/en-US/docs/Web/CSS/border-radius) property. Like other methods that modify the current path, this method does not directly render anything. To draw the rounded rectangle onto a canvas, you can use the {{domxref("CanvasRenderingContext2D.fill", "fill()")}} or {{domxref("CanvasRenderingContext2D.stroke", "stroke()")}} methods. ## Syntax ```js-nolint roundRect(x, y, width, height, radii) ``` ### Parameters - `x` - : The x-axis coordinate of the rectangle's starting point, in pixels. - `y` - : The y-axis coordinate of the rectangle's starting point, in pixels. - `width` - : The rectangle's width. Positive values are to the right, and negative to the left. - `height` - : The rectangle's height. Positive values are down, and negative are up. - `radii` - : A number or list specifying the radii of the circular arc to be used for the corners of the rectangle. The number and order of the radii function in the same way as the [`border-radius`](/en-US/docs/Web/CSS/border-radius) CSS property when `width` and `height` are _positive_: - `all-corners` - `[all-corners]` - `[top-left-and-bottom-right, top-right-and-bottom-left]` - `[top-left, top-right-and-bottom-left, bottom-right]` - `[top-left, top-right, bottom-right, bottom-left]` If `width` is _negative_ the rounded rectangle is flipped horizontally, so the radius values that normally apply to the left corners are used on the right and vice versa. Similarly, when `height` is negative, the rounded rect is flipped vertically. The specified radii may be scaled (reduced) if any of the edges are shorter than the combined radius of the vertices on either end. The `radii` parameter can also be a {{domxref("DOMPoint")}} or {{domxref("DOMPointReadOnly")}} instance, or an object containing the same properties (`{x: 0, y: 0}`), or a list of such objects, or a list mixing numbers and such objects. ### Return value None ({{jsxref("undefined")}}). ### Exceptions - {{jsxref("RangeError")}} - : If `radii` is a list that has zero or more than four elements, or if one of its values is a negative number. ## Examples ### Drawing rectangles This example creates a number of rounded rectangular paths using the `roundRect()` method. The paths are then rendered using the `stroke()` method. #### HTML ```html <canvas id="canvas" width="700" height="300"></canvas> ``` #### JavaScript First we create a context for drawing our rounded rectangles. ```js const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); ``` The code below draws two rectangles, both starting from the point (10, 20) and with a width of 150 and a height of 100. The first rectangle is drawn in red and specifies a zero radius for all the corners using a number as an argument. The second is drawn in blue, and specifies a 40px radius as a single element in a list. ```js // Rounded rectangle with zero radius (specified as a number) ctx.strokeStyle = "red"; ctx.beginPath(); ctx.roundRect(10, 20, 150, 100, 0); ctx.stroke(); // Rounded rectangle with 40px radius (single element list) ctx.strokeStyle = "blue"; ctx.beginPath(); ctx.roundRect(10, 20, 150, 100, [40]); ctx.stroke(); ``` Below the previous rectangle we draw another in orange that specifies the values of the radii of opposite corners. ```js // Rounded rectangle with 2 different radii ctx.strokeStyle = "orange"; ctx.beginPath(); ctx.roundRect(10, 150, 150, 100, [10, 40]); ctx.stroke(); ``` Finally, we draw two rounded rectangles that have four values for the radii and the same starting point. The difference here is that the second is drawn with a negative width. ```js // Rounded rectangle with four different radii ctx.strokeStyle = "green"; ctx.beginPath(); ctx.roundRect(400, 20, 200, 100, [0, 30, 50, 60]); ctx.stroke(); // Same rectangle drawn backwards ctx.strokeStyle = "magenta"; ctx.beginPath(); ctx.roundRect(400, 150, -200, 100, [0, 30, 50, 60]); ctx.stroke(); ``` #### Result The result is shown below. For the two rectangles on the right, note how the bottom rectangle is drawn with a negative width, and how this flips the rectangle horizontally. {{ EmbedLiveSample('Drawing_a_rectangle', 700, 300) }} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The interface defining this method: {{domxref("CanvasRenderingContext2D")}} - {{domxref("CanvasRenderingContext2D.rect()")}} - {{domxref("CanvasRenderingContext2D.fillRect")}} - {{domxref("CanvasRenderingContext2D.strokeRect()")}} - {{domxref("CanvasRenderingContext2D.fill()")}} - {{domxref("CanvasRenderingContext2D.stroke()")}}
0
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d/globalalpha/index.md
--- title: "CanvasRenderingContext2D: globalAlpha property" short-title: globalAlpha slug: Web/API/CanvasRenderingContext2D/globalAlpha page-type: web-api-instance-property browser-compat: api.CanvasRenderingContext2D.globalAlpha --- {{APIRef}} The **`CanvasRenderingContext2D.globalAlpha`** property of the Canvas 2D API specifies the alpha (transparency) value that is applied to shapes and images before they are drawn onto the canvas. > **Note:** See also the chapter [Applying styles and color](/en-US/docs/Web/API/Canvas_API/Tutorial/Applying_styles_and_colors) in the [Canvas Tutorial](/en-US/docs/Web/API/Canvas_API/Tutorial). ## Value A number between `0.0` (fully transparent) and `1.0` (fully opaque), inclusive. The default value is `1.0`. Values outside that range, including {{jsxref("Infinity")}} and {{jsxref("NaN")}}, will not be set, and `globalAlpha` will retain its previous value. ## Examples ### Drawing translucent shapes This example uses the `globalAlpha` property to draw two semi-transparent rectangles. #### HTML ```html <canvas id="canvas"></canvas> ``` #### JavaScript ```js const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); ctx.globalAlpha = 0.5; ctx.fillStyle = "blue"; ctx.fillRect(10, 10, 100, 100); ctx.fillStyle = "red"; ctx.fillRect(50, 50, 100, 100); ``` #### Result {{ EmbedLiveSample('Drawing_translucent_shapes', 700, 180) }} ### Overlaying transparent shapes This example illustrates the effect of overlaying multiple transparent shapes on top of each other. We begin by drawing a solid background composed of four differently colored squares. Next, we set the `globalAlpha` property to `0.2` (20% opaque); this alpha level will apply to all of our transparent shapes. After that, we use a `for` loop to draw a series of circles with increasing radii. With each new circle, the opacity of the previous circles underneath is effectively increased. If we were to increase the step count (and thus draw more circles), the background would eventually disappear completely from the center of the image. ```html hidden <canvas id="canvas" width="150" height="150"></canvas> ``` ```js const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); // Draw background ctx.fillStyle = "#FD0"; ctx.fillRect(0, 0, 75, 75); ctx.fillStyle = "#6C0"; ctx.fillRect(75, 0, 75, 75); ctx.fillStyle = "#09F"; ctx.fillRect(0, 75, 75, 75); ctx.fillStyle = "#F30"; ctx.fillRect(75, 75, 75, 75); ctx.fillStyle = "#FFF"; // Set transparency value ctx.globalAlpha = 0.2; // Draw transparent circles for (let i = 0; i < 7; i++) { ctx.beginPath(); ctx.arc(75, 75, 10 + 10 * i, 0, Math.PI * 2, true); ctx.fill(); } ``` {{EmbedLiveSample("Overlaying_transparent_shapes", "180", "180", "canvas_globalalpha.png")}} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ### Gecko-specific notes - Starting with Gecko 5.0, specifying invalid values for `globalAlpha` no longer throws a `SYNTAX_ERR` exception; these are now correctly silently ignored. ### WebKit/Blink-specific notes - In WebKit- and Blink-based browsers, a non-standard and deprecated method `ctx.setAlpha()` is implemented in addition to this property. ## See also - The interface defining this property: {{domxref("CanvasRenderingContext2D")}} - {{domxref("CanvasRenderingContext2D.globalCompositeOperation")}}
0
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d/linedashoffset/index.md
--- title: "CanvasRenderingContext2D: lineDashOffset property" short-title: lineDashOffset slug: Web/API/CanvasRenderingContext2D/lineDashOffset page-type: web-api-instance-property browser-compat: api.CanvasRenderingContext2D.lineDashOffset --- {{APIRef}} The **`CanvasRenderingContext2D.lineDashOffset`** property of the Canvas 2D API sets the line dash offset, or "phase." > **Note:** Lines are drawn by calling the > {{domxref("CanvasRenderingContext2D.stroke()", "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. {{ EmbedLiveSample('Offsetting_a_line_dash', 700, 180) }} ### Marching ants The [marching ants](https://en.wikipedia.org/wiki/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. ```html hidden <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(); ``` {{ EmbedLiveSample('Marching_ants', 700, 180) }} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The interface defining this property: {{domxref("CanvasRenderingContext2D")}} - {{domxref("CanvasRenderingContext2D.getLineDash()")}} - {{domxref("CanvasRenderingContext2D.setLineDash()")}} - [Applying styles and color](/en-US/docs/Web/API/Canvas_API/Tutorial/Applying_styles_and_colors)
0
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d/linewidth/index.md
--- title: "CanvasRenderingContext2D: lineWidth property" short-title: lineWidth slug: Web/API/CanvasRenderingContext2D/lineWidth page-type: web-api-instance-property browser-compat: api.CanvasRenderingContext2D.lineWidth --- {{APIRef}} The **`CanvasRenderingContext2D.lineWidth`** property of the Canvas 2D API sets the thickness of lines. > **Note:** Lines can be drawn with the > {{domxref("CanvasRenderingContext2D.stroke()", "stroke()")}}, > {{domxref("CanvasRenderingContext2D.strokeRect()", "strokeRect()")}}, > and {{domxref("CanvasRenderingContext2D.strokeText()", "strokeText()")}} methods. ## Value A number specifying the line width, in coordinate space units. Zero, negative, {{jsxref("Infinity")}}, and {{jsxref("NaN")}} values are ignored. This value is `1.0` by default. ## Examples ### Changing line width This example draws a line and a rectangle, using a line width of 15 units. #### HTML ```html <canvas id="canvas"></canvas> ``` #### JavaScript ```js const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); ctx.lineWidth = 15; ctx.beginPath(); ctx.moveTo(20, 20); ctx.lineTo(130, 130); ctx.rect(40, 40, 70, 70); ctx.stroke(); ``` #### Result {{ EmbedLiveSample('Changing_line_width', 700, 180) }} ### More examples For more examples and explanation about this property, see [Applying styles and color](/en-US/docs/Web/API/Canvas_API/Tutorial/Applying_styles_and_colors) in the [Canvas Tutorial](/en-US/docs/Web/API/Canvas_API/Tutorial). ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The interface defining this property: {{domxref("CanvasRenderingContext2D")}} - {{domxref("CanvasRenderingContext2D.lineCap")}} - {{domxref("CanvasRenderingContext2D.lineJoin")}} - [Applying styles and color](/en-US/docs/Web/API/Canvas_API/Tutorial/Applying_styles_and_colors)
0
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d/filter/index.md
--- title: "CanvasRenderingContext2D: filter property" short-title: filter slug: Web/API/CanvasRenderingContext2D/filter page-type: web-api-instance-property browser-compat: api.CanvasRenderingContext2D.filter --- {{APIRef}} The **`CanvasRenderingContext2D.filter`** property of the Canvas 2D API provides filter effects such as blurring and grayscaling. It is similar to the CSS {{cssxref("filter")}} property and accepts the same values. ## Value The `filter` property accepts a value of `"none"` or one or more of the following filter functions in a string. - [`url()`](/en-US/docs/Web/CSS/filter#url) - : A CSS {{cssxref("url", "url()")}}. Takes an IRI pointing to an SVG filter element, which may be embedded in an external XML file. - [`blur()`](/en-US/docs/Web/CSS/filter#blur) - : A CSS {{cssxref("&lt;length&gt;")}}. Applies a Gaussian blur to the drawing. It defines the value of the standard deviation to the Gaussian function, i.e., how many pixels on the screen blend into each other; thus, a larger value will create more blur. A value of `0` leaves the input unchanged. - [`brightness()`](/en-US/docs/Web/CSS/filter#brightness) - : A CSS {{cssxref("&lt;percentage&gt;")}}. Applies a linear multiplier to the drawing, making it appear brighter or darker. A value under `100%` darkens the image, while a value over `100%` brightens it. A value of `0%` will create an image that is completely black, while a value of `100%` leaves the input unchanged. - [`contrast()`](/en-US/docs/Web/CSS/filter#contrast) - : A CSS {{cssxref("&lt;percentage&gt;")}}. Adjusts the contrast of the drawing. A value of `0%` will create a drawing that is completely black. A value of `100%` leaves the drawing unchanged. - [`drop-shadow()`](/en-US/docs/Web/CSS/filter#drop-shadow) - : Applies a drop shadow effect to the drawing. A drop shadow is effectively a blurred, offset version of the drawing's alpha mask drawn in a particular color, composited below the drawing. This function takes up to five arguments: - `<offset-x>` - : See {{cssxref("&lt;length&gt;")}} for possible units. Specifies the horizontal distance of the shadow. - `<offset-y>` - : See {{cssxref("&lt;length&gt;")}} for possible units. Specifies the vertical distance of the shadow. - `<blur-radius>` - : The larger this value, the bigger the blur, so the shadow becomes bigger and lighter. Negative values are not allowed. - `<color>` - : See {{cssxref("&lt;color&gt;")}} values for possible keywords and notations. - [`grayscale()`](/en-US/docs/Web/CSS/filter#grayscale) - : A CSS {{cssxref("&lt;percentage&gt;")}}. Converts the drawing to grayscale. A value of `100%` is completely grayscale. A value of `0%` leaves the drawing unchanged. - [`hue-rotate()`](/en-US/docs/Web/CSS/filter#hue-rotate) - : A CSS {{cssxref("&lt;angle&gt;")}}. Applies a hue rotation on the drawing. A value of `0deg` leaves the input unchanged. - [`invert()`](/en-US/docs/Web/CSS/filter#invert) - : A CSS {{cssxref("&lt;percentage&gt;")}}. Inverts the drawing. A value of `100%` means complete inversion. A value of `0%` leaves the drawing unchanged. - [`opacity()`](/en-US/docs/Web/CSS/filter#opacity) - : A CSS {{cssxref("&lt;percentage&gt;")}}. Applies transparency to the drawing. A value of `0%` means completely transparent. A value of `100%` leaves the drawing unchanged. - [`saturate()`](/en-US/docs/Web/CSS/filter#saturate) - : A CSS {{cssxref("&lt;percentage&gt;")}}. Saturates the drawing. A value of `0%` means completely un-saturated. A value of `100%` leaves the drawing unchanged. - [`sepia()`](/en-US/docs/Web/CSS/filter#sepia) - : A CSS {{cssxref("&lt;percentage&gt;")}}. Converts the drawing to sepia. A value of `100%` means completely sepia. A value of `0%` leaves the drawing unchanged. - `none` - : No filter is applied. Initial value. ## Examples To view these examples, make sure to use a browser that supports this feature; see the compatibility table below. ### Applying a blur This example blurs a piece of text using the `filter` property. #### HTML ```html <canvas id="canvas"></canvas> ``` #### JavaScript ```js const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); ctx.filter = "blur(4px)"; ctx.font = "48px serif"; ctx.fillText("Hello world", 50, 100); ``` #### Result {{ EmbedLiveSample('Applying_a_blur', 700, 180) }} ### Applying multiple filters You can combine as many filters as you like. This example applies the `contrast`, `sepia`, and `drop-shadow` filters to a photo of a rhino. #### HTML ```html <canvas id="canvas" width="400" height="150"></canvas> <div style="display:none;"> <img id="source" src="rhino.jpg" /> </div> ``` #### JavaScript ```js const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); const image = document.getElementById("source"); image.addEventListener("load", (e) => { // Draw unfiltered image ctx.drawImage(image, 0, 0, image.width * 0.6, image.height * 0.6); // Draw image with filter ctx.filter = "contrast(1.4) sepia(1) drop-shadow(-9px 9px 3px #e81)"; ctx.drawImage(image, 400, 0, -image.width * 0.6, image.height * 0.6); }); ``` #### Result {{ EmbedLiveSample('Applying_multiple_filters', 700, 180) }} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The interface defining this property: {{domxref("CanvasRenderingContext2D")}} - CSS {{cssxref("filter")}} - CSS {{cssxref("&lt;filter-function&gt;")}}
0
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d/quadraticcurveto/index.md
--- title: "CanvasRenderingContext2D: quadraticCurveTo() method" short-title: quadraticCurveTo() slug: Web/API/CanvasRenderingContext2D/quadraticCurveTo page-type: web-api-instance-method browser-compat: api.CanvasRenderingContext2D.quadraticCurveTo --- {{APIRef}} The **`CanvasRenderingContext2D.quadraticCurveTo()`** method of the Canvas 2D API adds a quadratic [Bézier curve](/en-US/docs/Glossary/Bezier_curve) to the current sub-path. It requires two points: the first one is a control point and the second one is the end point. The starting point is the latest point in the current path, which can be changed using {{domxref("CanvasRenderingContext2D.moveTo", "moveTo()")}} before creating the quadratic Bézier curve. ## Syntax ```js-nolint quadraticCurveTo(cpx, cpy, x, y) ``` ### Parameters - `cpx` - : The x-axis coordinate of the control point. - `cpy` - : The y-axis coordinate of the control point. - `x` - : The x-axis coordinate of the end point. - `y` - : The y-axis coordinate of the end point. ### Return value None ({{jsxref("undefined")}}). ## Examples ### How quadraticCurveTo works This example shows how a quadratic Bézier curve is drawn. #### HTML ```html <canvas id="canvas"></canvas> ``` #### JavaScript ```js const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); // Quadratic Bézier curve ctx.beginPath(); ctx.moveTo(50, 20); ctx.quadraticCurveTo(230, 30, 50, 100); ctx.stroke(); // Start and end points ctx.fillStyle = "blue"; ctx.beginPath(); ctx.arc(50, 20, 5, 0, 2 * Math.PI); // Start point ctx.arc(50, 100, 5, 0, 2 * Math.PI); // End point ctx.fill(); // Control point ctx.fillStyle = "red"; ctx.beginPath(); ctx.arc(230, 30, 5, 0, 2 * Math.PI); ctx.fill(); ``` #### Result In this example, the control point is red and the start and end points are blue. {{ EmbedLiveSample('How_quadraticCurveTo_works', 315, 165) }} ### A simple quadratic curve This example draws a simple quadratic Bézier curve using `quadraticCurveTo()`. #### HTML ```html <canvas id="canvas"></canvas> ``` #### JavaScript The curve begins at the point specified by `moveTo()`: (20, 110). The control point is placed at (230, 150). The curve ends at (250, 20). ```js const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); ctx.beginPath(); ctx.moveTo(20, 110); ctx.quadraticCurveTo(230, 150, 250, 20); ctx.stroke(); ``` #### Result {{ EmbedLiveSample('A_simple_quadratic_curve', 700, 180) }} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The interface defining this method: {{domxref("CanvasRenderingContext2D")}} - [Bézier curve](/en-US/docs/Glossary/Bezier_curve)
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/htmlmenuelement/index.md
--- title: HTMLMenuElement slug: Web/API/HTMLMenuElement page-type: web-api-interface browser-compat: api.HTMLMenuElement --- {{APIRef("HTML DOM")}} The **`HTMLMenuElement`** interface provides additional properties (beyond those inherited from the {{domxref("HTMLElement")}} interface) for manipulating a {{HTMLElement("menu")}} element. `<menu>` is a semantic alternative to the {{HTMLElement("ul")}} element. {{InheritanceDiagram}} ## Instance properties _Inherits properties from its parent, {{domxref("HTMLElement")}}, and its ancestors._ - {{domxref("HTMLMenuElement.compact")}} {{deprecated_inline}} - : A boolean determining if the menu displays compactly. ## Instance methods _Inherits methods from its parent, {{domxref("HTMLElement")}}, and its ancestors._ _`HTMLMenuElement` doesn't implement specific methods._ ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{DOMxRef("HTMLMenuItemElement")}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/xrwebglbinding/index.md
--- title: XRWebGLBinding slug: Web/API/XRWebGLBinding page-type: web-api-interface status: - experimental browser-compat: api.XRWebGLBinding --- {{APIRef("WebXR Device API")}} {{secureContext_header}}{{SeeCompatTable}} The **`XRWebGLBinding`** interface is used to create layers that have a GPU backend. ## Constructor - {{domxref("XRWebGLBinding.XRWebGLBinding", "XRWebGLBinding()")}} {{Experimental_Inline}} - : Creates a new `XRWebGLBinding` object for the specified XR session and WebGL rendering context. ## Instance properties - {{domxref("XRWebGLBinding.nativeProjectionScaleFactor")}} {{ReadOnlyInline}} {{Experimental_Inline}} - : The `scaleFactor` that was passed in during the construction of the projection layer. The native buffer size is scaled by this number. ## Instance methods - {{domxref("XRWebGLBinding.createCubeLayer()")}} {{Experimental_Inline}} - : Returns an {{domxref("XRCubeLayer")}} object, which is a layer that renders directly from a [cubemap](https://en.wikipedia.org/wiki/Cube_mapping), and projects it onto the inside faces of a cube. - {{domxref("XRWebGLBinding.createCylinderLayer()")}} {{Experimental_Inline}} - : Returns an {{domxref("XRCylinderLayer")}} object which is a layer that takes up a curved rectangular space in the virtual environment. - {{domxref("XRWebGLBinding.createEquirectLayer()")}} {{Experimental_Inline}} - : Returns an {{domxref("XREquirectLayer")}} object which is a layer that maps [equirectangular](https://en.wikipedia.org/wiki/Equirectangular_projection) coded data onto the inside of a sphere. - {{domxref("XRWebGLBinding.createProjectionLayer()")}} {{Experimental_Inline}} - : Returns an {{domxref("XRProjectionLayer")}} object which is a layer that fills the entire view of the observer and is refreshed close to the device's native frame rate. - {{domxref("XRWebGLBinding.createQuadLayer()")}} {{Experimental_Inline}} - : Returns an {{domxref("XRQuadLayer")}} object which is a two-dimensional object positioned and oriented in 3D space. - {{domxref("XRWebGLBinding.getDepthInformation()")}} {{Experimental_Inline}} - : Returns an {{domxref("XRWebGLDepthInformation")}} object containing WebGL depth information. - {{domxref("XRWebGLBinding.getReflectionCubeMap()")}} {{Experimental_Inline}} - : Returns a {{domxref("WebGLTexture")}} object containing a reflection cube map texture. - {{domxref("XRWebGLBinding.getSubImage()")}} {{Experimental_Inline}} - : Returns an {{domxref("XRWebGLSubImage")}} object representing the WebGL texture to render. - {{domxref("XRWebGLBinding.getViewSubImage()")}} {{Experimental_Inline}} - : Returns an {{domxref("XRWebGLSubImage")}} object representing the WebGL texture to render for an {{domxref("XRView")}}. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("XRWebGLLayer")}} - {{domxref('WebGLRenderingContext')}} and {{domxref("WebGL2RenderingContext")}}
0
data/mdn-content/files/en-us/web/api/xrwebglbinding
data/mdn-content/files/en-us/web/api/xrwebglbinding/getdepthinformation/index.md
--- title: "XRWebGLBinding: getDepthInformation() method" short-title: getDepthInformation() slug: Web/API/XRWebGLBinding/getDepthInformation page-type: web-api-instance-method status: - experimental browser-compat: api.XRWebGLBinding.getDepthInformation --- {{APIRef("WebXR Device API")}}{{SeeCompatTable}} The **`getDepthInformation()`** method of the {{domxref("XRWebGLBinding")}} interface returns an {{domxref("XRWebGLDepthInformation")}} object containing WebGL depth information. ## Syntax ```js-nolint getDepthInformation(view) ``` ### Parameters - `view` - : An {{domxref("XRView")}} object obtained from a viewer pose. ### Return value An {{domxref("XRWebGLDepthInformation")}} object. ### Exceptions - `NotSupportedError` {{domxref("DOMException")}} - : Thrown if `"depth-sensing"` is not in the list of enabled features for this {{domxref("XRSession")}}. - `InvalidStateError` {{domxref("DOMException")}} - : Thrown if the `XRFrame` is not active nor animated. Obtaining depth information is only valid within the {{domxref("XRSession.requestAnimationFrame()", "requestAnimationFrame()")}} callback. - `InvalidStateError` {{domxref("DOMException")}} - : Thrown if the session's {{domxref("XRSession.depthUsage", "depthUsage")}} is not `"gpu-optimized"`. ## Examples ### Obtaining WebGL depth information ```js const canvasElement = document.querySelector(".output-canvas"); const gl = canvasElement.getContext("webgl"); await gl.makeXRCompatible(); // Make sure to request a session with depth-sensing enabled const session = navigator.xr.requestSession("immersive-ar", { requiredFeatures: ["depth-sensing"], depthSensing: { usagePreference: ["gpu-optimized"], formatPreference: ["luminance-alpha"], }, }); const glBinding = new XRWebGLBinding(session, gl); // … // Obtain depth information in an active and animated frame function rafCallback(time, frame) { session.requestAnimationFrame(rafCallback); const pose = frame.getViewerPose(referenceSpace); if (pose) { for (const view of pose.views) { const depthInformation = glBinding.getDepthInformation(view); if (depthInformation) { // Do something with the depth information // gl.bindTexture(gl.TEXTURE_2D, depthInformation.texture); // … } } } } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("XRWebGLDepthInformation.texture")}}
0
data/mdn-content/files/en-us/web/api/xrwebglbinding
data/mdn-content/files/en-us/web/api/xrwebglbinding/createquadlayer/index.md
--- title: "XRWebGLBinding: createQuadLayer() method" short-title: createQuadLayer() slug: Web/API/XRWebGLBinding/createQuadLayer page-type: web-api-instance-method status: - experimental browser-compat: api.XRWebGLBinding.createQuadLayer --- {{APIRef("WebXR Device API")}}{{SeeCompatTable}} The **`createQuadLayer()`** method of the {{domxref("XRWebGLBinding")}} interface returns an {{domxref("XRQuadLayer")}} object which is a layer that takes up a flat rectangular space in the virtual environment. ## Syntax ```js-nolint createQuadLayer(options) ``` ### Parameters - `options` - : An object to configure the {{domxref("XRQuadLayer")}}. It must have the `space`, `viewPixelHeight`, and `viewPixelWidth` properties. `init` has the following properties: - `colorFormat` {{optional_inline}} - : A {{domxref("WebGL_API/Types", "GLenum")}} defining the data type of the color texture data. Possible values: - `gl.RGB` - `gl.RGBA` Additionally, for contexts with the {{domxref("EXT_sRGB")}} extension enabled: - `ext.SRGB_EXT` - `ext.SRGB_ALPHA_EXT` Additionally, for {{domxref("WebGL2RenderingContext")}} contexts: - `gl.RGBA8` - `gl.RGB8` - `gl.SRGB8` - `gl.RGB8_ALPHA8` Additionally, for contexts with the {{domxref("WEBGL_compressed_texture_etc")}} extension enabled: - `ext.COMPRESSED_RGB8_ETC2` - `ext.COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2` - `ext.COMPRESSED_RGBA8_ETC2_EAC` - `ext.COMPRESSED_SRGB8_ETC2` - `ext.COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2` - `ext.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC` Additionally, for contexts with the {{domxref("WEBGL_compressed_texture_astc")}} extension enabled: - All of the formats the extension supports. The default value is `gl.RGBA`. - `depthFormat` {{optional_inline}} - : A {{domxref("WebGL_API/Types", "GLenum")}} defining the data type of the depth texture data or `0` indicating that the layer should not provide a depth texture (in that case {{domxref("XRProjectionLayer.ignoreDepthValues")}} will be `true`). Possible values within {{domxref("WebGLRenderingContext")}} contexts with the {{domxref("WEBGL_depth_texture")}} extension enabled, or within {{domxref("WebGL2RenderingContext")}} contexts (no extension required): - `gl.DEPTH_COMPONENT` - `gl.DEPTH_STENCIL` Additionally, for {{domxref("WebGL2RenderingContext")}} contexts: - `gl.DEPTH_COMPONENT24` - `gl.DEPTH24_STENCIL24` The default value is `gl.DEPTH_COMPONENT`. - `height` {{optional_inline}} - : A number specifying the height of the layer in meters. The default value is `1.0`. - `isStatic` {{optional_inline}} - : A boolean that, if true, indicates you can only draw to this layer when {{domxref("XRCompositionLayer.needsRedraw", "needsRedraw")}} is `true`. The default value is `false`. - `layout` {{optional_inline}} - : A string indicating the layout of the layer. Possible values: - `default` - : The layer accommodates all views of the session. - `mono` - : A single {{domxref("XRSubImage")}} is allocated and presented to both eyes. - `stereo` - : The user agent decides how it allocates the {{domxref("XRSubImage")}} (one or two) and the layout (top/bottom or left/right). - `stereo-left-right` - : A single {{domxref("XRSubImage")}} is allocated. Left eye gets the left area of the texture, right eye the right. - `stereo-top-bottom` - : A single {{domxref("XRSubImage")}} is allocated. Left eye gets the top area of the texture, right eye the bottom. The default value is `mono`. - `mipLevels` {{optional_inline}} - : A number specifying desired number of mip levels. The default value is `1`. - `space` **Required** - : An {{domxref("XRSpace")}} object defining the layer's spatial relationship with the user's physical environment. - `textureType` {{optional_inline}} - : A string defining the type of texture the layer will have. Possible values: - `texture` - : The textures of {{domxref("XRWebGLSubImage")}} will be of type `gl.TEXTURE_2D`. - `texture-array` - : the textures of {{domxref("XRWebGLSubImage")}} will be of type `gl.TEXTURE_2D_ARRAY` (WebGL 2 contexts only). The default value is `texture`. - `transform` {{optional_inline}} - : An {{domxref("XRRigidTransform")}} object defining the offset and orientation relative to `space`. - `viewPixelHeight` **Required** - : A number specifying the pixel height of the layer view. - `viewPixelWidth` **Required** - : A number specifying the pixel width of the layer view. - `width` {{optional_inline}} - : A number specifying the width of the layer in meters. The default value is `1.0`. ### Return value An {{domxref("XRQuadLayer")}} object. ## Examples ### Creating an `XRQuadLayer` Configure the quad layer using the properties listed above in a call to `createQuadLayer()`. To present layers to the XR device, add them to the `layers` render state using {{domxref("XRSession.updateRenderState()")}}. ```js function onXRSessionStarted(xrSession) { const glCanvas = document.createElement("canvas"); const gl = glCanvas.getContext("webgl2", { xrCompatible: true }); const xrGlBinding = new XRWebGLBinding(xrSession, gl); const quadLayer = xrGlBinding.createQuadLayer({ space: xrReferenceSpace, viewPixelHeight: 512, viewPixelWidth: 512, transform: new XRRigidTransform({ z: -2 }), }); xrSession.updateRenderState({ layers: [quadLayer], }); } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("XRQuadLayer")}} - [WebGL constants](/en-US/docs/Web/API/WebGL_API/Constants)
0
data/mdn-content/files/en-us/web/api/xrwebglbinding
data/mdn-content/files/en-us/web/api/xrwebglbinding/getviewsubimage/index.md
--- title: "XRWebGLBinding: getViewSubImage() method" short-title: getViewSubImage() slug: Web/API/XRWebGLBinding/getViewSubImage page-type: web-api-instance-method status: - experimental browser-compat: api.XRWebGLBinding.getViewSubImage --- {{APIRef("WebXR Device API")}}{{SeeCompatTable}} The **`getViewSubImage()`** method of the {{domxref("XRWebGLBinding")}} interface returns a {{domxref("XRWebGLSubImage")}} object representing the WebGL texture to render for a view. ## Syntax ```js-nolint getViewSubImage(layer, view) ``` ### Parameters - `layer` - : The {{domxref("XRProjectionLayer")}} to use for rendering (to render other layer types, see {{domxref("XRWebGLBinding.getSubImage()")}}). - `view` - : The {{domxref("XRView")}} to use for rendering. ### Return value A {{domxref("XRWebGLSubImage")}} object. ### Exceptions A {{jsxref("TypeError")}} is thrown, - if `layer` is not in the [session's `layer` array](/en-US/docs/Web/API/XRSession/updateRenderState#setting_the_layers_array). ## Examples ### Rendering an `XRProjectionLayer` The following example renders an {{domxref("XRProjectionLayer")}} to a view. ```js const xrGlBinding = new XRWebGLBinding(xrSession, gl); const layer = xrGlBinding.createProjectionLayer({}); const framebuffer = gl.createFramebuffer(); xrSession.updateRenderState({ layers: [layer] }); xrSession.requestAnimationFrame(onXRFrame); function onXRFrame(time, xrFrame) { xrSession.requestAnimationFrame(onXRFrame); gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer); for (const view in xrViewerPose.views) { const subImage = xrGlBinding.getViewSubImage(layer, view); gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, subImage.colorTexture, 0, ); gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, subImage.depthStencilTexture, 0, ); const viewport = subImage.viewport; gl.viewport(viewport.x, viewport.y, viewport.width, viewport.height); // Render from the viewpoint of xrView } } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("XRWebGLSubImage")}}
0
data/mdn-content/files/en-us/web/api/xrwebglbinding
data/mdn-content/files/en-us/web/api/xrwebglbinding/nativeprojectionscalefactor/index.md
--- title: "XRWebGLBinding: nativeProjectionScaleFactor property" short-title: nativeProjectionScaleFactor slug: Web/API/XRWebGLBinding/nativeProjectionScaleFactor page-type: web-api-instance-property status: - experimental browser-compat: api.XRWebGLBinding.nativeProjectionScaleFactor --- {{APIRef("WebXR Device API")}}{{SeeCompatTable}} The read-only **`nativeProjectionScaleFactor`** property of the {{domxref("XRWebGLBinding")}} interface represents the scaling factor by which the projection layer's resolution is multiplied by to get the native resolution of the WebXR device's frame buffer. For more details, see {{domxref("XRWebGLLayer.getNativeFramebufferScaleFactor_static", "XRWebGLLayer.getNativeFramebufferScaleFactor()")}}. ## Value A floating-point number representing by how much the device's native frame buffer size is scaled by. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("XRWebGLLayer.getNativeFramebufferScaleFactor_static", "XRWebGLLayer.getNativeFramebufferScaleFactor()")}}
0
data/mdn-content/files/en-us/web/api/xrwebglbinding
data/mdn-content/files/en-us/web/api/xrwebglbinding/createcubelayer/index.md
--- title: "XRWebGLBinding: createCubeLayer() method" short-title: createCubeLayer() slug: Web/API/XRWebGLBinding/createCubeLayer page-type: web-api-instance-method status: - experimental browser-compat: api.XRWebGLBinding.createCubeLayer --- {{APIRef("WebXR Device API")}}{{SeeCompatTable}} The **`createCubeLayer()`** method of the {{domxref("XRWebGLBinding")}} interface returns an {{domxref("XRCubeLayer")}} object, which is a layer that renders directly from a [cubemap](https://en.wikipedia.org/wiki/Cube_mapping), and projects it onto the inside faces of a cube. ## Syntax ```js-nolint createCubeLayer(init) ``` ### Parameters - `init` - : An object to configure the {{domxref("XRCubeLayer")}}. It must have the `space`, `viewPixelHeight`, and `viewPixelWidth` properties. `init` has the following properties: - `colorFormat` {{optional_inline}} - : A {{domxref("WebGL_API/Types", "GLenum")}} defining the data type of the color texture data. Possible values: - `gl.RGB` - `gl.RGBA` (Default) Additionally, for contexts with the {{domxref("EXT_sRGB")}} extension enabled: - `ext.SRGB_EXT` - `ext.SRGB_ALPHA_EXT` Additionally, for {{domxref("WebGL2RenderingContext")}} contexts: - `gl.RGBA8` - `gl.RGB8` - `gl.SRGB8` - `gl.RGB8_ALPHA8` Additionally, for contexts with the {{domxref("WEBGL_compressed_texture_etc")}} extension enabled: - `ext.COMPRESSED_RGB8_ETC2` - `ext.COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2` - `ext.COMPRESSED_RGBA8_ETC2_EAC` - `ext.COMPRESSED_SRGB8_ETC2` - `ext.COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2` - `ext.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC` Additionally, for contexts with the {{domxref("WEBGL_compressed_texture_astc")}} extension enabled: - All of the [formats](/en-US/docs/Web/API/WEBGL_compressed_texture_astc#constants) the extension supports. - `depthFormat` {{optional_inline}} - : A {{domxref("WebGL_API/Types", "GLenum")}} defining the data type of the depth texture data or `0` indicating that the layer should not provide a depth texture. (In that case {{domxref("XRProjectionLayer.ignoreDepthValues")}} will be `true`.) Possible values for {{domxref("WebGLRenderingContext")}} contexts with the {{domxref("WEBGL_depth_texture")}} extension enabled, or for {{domxref("WebGL2RenderingContext")}} contexts (no extension required): - `gl.DEPTH_COMPONENT` (Default) - `gl.DEPTH_STENCIL` Additionally, for {{domxref("WebGL2RenderingContext")}} contexts: - `gl.DEPTH_COMPONENT24` - `gl.DEPTH24_STENCIL24` - `isStatic` {{optional_inline}} - : A boolean that, if true, indicates you can only draw to this layer when {{domxref("XRCompositionLayer.needsRedraw", "needsRedraw")}} is `true`. The default value is `false`. - `layout` - : A string indicating the layout of the layer. Possible values: - `default`: The layer accommodates all views of the session. - `mono`: A single {{domxref("XRSubImage")}} is allocated and presented to both eyes. - `stereo`: The user agent decides how it allocates the {{domxref("XRSubImage")}} (one or two) and the layout (top/bottom or left/right). - `stereo-left-right`: A single {{domxref("XRSubImage")}} is allocated. The left eye gets the left area of the texture, the right eye the right. - `stereo-top-bottom`: A single {{domxref("XRSubImage")}} is allocated. The left eye gets the top area of the texture, the right eye the bottom. The default value is `mono`. - `mipLevels` {{optional_inline}} - : A number specifying the desired number of mip levels. The default value is `1`. - `orientation` {{optional_inline}} - : A {{domxref("DOMPointReadOnly")}} specifying the orientation relative to the `space` property. - `space` **Required** - : An {{domxref("XRSpace")}} object defining the layer's spatial relationship with the user's physical environment. - `viewPixelHeight` **Required** - : A number specifying the pixel height of the layer view. - `viewPixelWidth` **Required** - : A number specifying the pixel width of the layer view. ### Return value An {{domxref("XRCubeLayer")}} object. ## Examples ### Creating an XRCubeLayer Configure the cube layer using the properties listed above in a call to `createCubeLayer()`. To present layers to the XR device, add them to the `layers` render state using {{domxref("XRSession.updateRenderState()")}}. ```js function onXRSessionStarted(xrSession) { const glCanvas = document.createElement("canvas"); const gl = glCanvas.getContext("webgl2", { xrCompatible: true }); const xrGlBinding = new XRWebGLBinding(xrSession, gl); const cubeLayer = xrGlBinding.createCubeLayer({ space: xrReferenceSpace, viewPixelHeight: 512, viewPixelWidth: 512, }); xrSession.updateRenderState({ layers: [cubeLayer], }); } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("XRCubeLayer")}} - [WebGL constants](/en-US/docs/Web/API/WebGL_API/Constants)
0
data/mdn-content/files/en-us/web/api/xrwebglbinding
data/mdn-content/files/en-us/web/api/xrwebglbinding/createprojectionlayer/index.md
--- title: "XRWebGLBinding: createProjectionLayer() method" short-title: createProjectionLayer() slug: Web/API/XRWebGLBinding/createProjectionLayer page-type: web-api-instance-method status: - experimental browser-compat: api.XRWebGLBinding.createProjectionLayer --- {{APIRef("WebXR Device API")}}{{SeeCompatTable}} The **`createProjectionLayer()`** method of the {{domxref("XRWebGLBinding")}} interface returns an {{domxref("XRProjectionLayer")}} object which is a layer that fills the entire view of the observer and is refreshed close to the device's native frame rate. ## Syntax ```js-nolint createProjectionLayer(options) ``` ### Parameters - `options` - : An object to configure the {{domxref("XRProjectionLayer")}}. - `textureType` {{optional_inline}} - : An string defining the type of texture the layer will have. Possible values: - `texture` - : The textures of {{domxref("XRWebGLSubImage")}} will be of type `gl.TEXTURE_2D`. - `texture-array` - : The textures of {{domxref("XRWebGLSubImage")}} will be of type `gl.TEXTURE_2D_ARRAY` (WebGL 2 contexts only). The default value is `texture`. - `colorFormat` {{optional_inline}} - : A {{domxref("WebGL_API/Types", "GLenum")}} defining the data type of the color texture data. Possible values: - `gl.RGB` - `gl.RGBA` Additionally, for contexts with the {{domxref("EXT_sRGB")}} extension enabled: - `ext.SRGB_EXT` - `ext.SRGB_ALPHA_EXT` Additionally, for {{domxref("WebGL2RenderingContext")}} contexts: - `gl.RGBA8` - `gl.RGB8` - `gl.SRGB8` - `gl.RGB8_ALPHA8` The default value is `gl.RGBA`. - `depthFormat` {{optional_inline}} - : A {{domxref("WebGL_API/Types", "GLenum")}} defining the data type of the depth texture data or `0` indicating that the layer should not provide a depth texture. (In that case {{domxref("XRProjectionLayer.ignoreDepthValues")}} will be `true`.) Possible values within {{domxref("WebGLRenderingContext")}} contexts with the {{domxref("WEBGL_depth_texture")}} extension enabled, or within {{domxref("WebGL2RenderingContext")}} contexts (no extension required): - `gl.DEPTH_COMPONENT` - `gl.DEPTH_STENCIL` Additionally, for {{domxref("WebGL2RenderingContext")}} contexts: - `gl.DEPTH_COMPONENT24` - `gl.DEPTH24_STENCIL24` The default value is `gl.DEPTH_COMPONENT`. - `scaleFactor` {{optional_inline}} - : A floating-point value which is used to scale the layer during compositing. A value of `1.0` represents the default pixel size for the frame buffer. (See also {{domxref("XRWebGLLayer.getNativeFramebufferScaleFactor_static", "XRWebGLLayer.getNativeFramebufferScaleFactor()")}}.) Unlike other layers, the `XRProjectionLayer` can't be created with an explicit pixel width and height, because the size is inferred by the hardware. (Projection layers fill the observer's entire view.) ### Return value An {{domxref("XRProjectionLayer")}} object. ## Examples ### Creating an `XRProjectionLayer` in a WebGL 2 context The `textureType` option allows allocating a texture array instead, in which every {{domxref("XRView")}} will be rendered into a separate level of the array. This allows for some rendering optimizations, such as the use of the {{domxref("OVR_multiview2")}} extension available in WebGL 2 contexts. ```js function onXRSessionStarted(xrSession) { const glCanvas = document.createElement("canvas"); const gl = glCanvas.getContext("webgl2", { xrCompatible: true }); const xrGlBinding = new XRWebGLBinding(xrSession, gl); const projectionLayer = xrGlBinding.createProjectionLayer({ textureType: "texture-array", }); xrSession.updateRenderState({ layers: [projectionLayer], }); } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("XRProjectionLayer")}} - [WebGL constants](/en-US/docs/Web/API/WebGL_API/Constants)
0
data/mdn-content/files/en-us/web/api/xrwebglbinding
data/mdn-content/files/en-us/web/api/xrwebglbinding/createcylinderlayer/index.md
--- title: "XRWebGLBinding: createCylinderLayer() method" short-title: createCylinderLayer() slug: Web/API/XRWebGLBinding/createCylinderLayer page-type: web-api-instance-method status: - experimental browser-compat: api.XRWebGLBinding.createCylinderLayer --- {{APIRef("WebXR Device API")}}{{SeeCompatTable}} The **`createCylinderLayer()`** method of the {{domxref("XRWebGLBinding")}} interface returns an {{domxref("XRCylinderLayer")}} object, which is a layer that takes up a curved rectangular space in the virtual environment. ## Syntax ```js-nolint createCylinderLayer(init) ``` ### Parameters - `init` - : An object to configure the {{domxref("XRCylinderLayer")}}. It must have the `space`, `viewPixelHeight`, and `viewPixelWidth` properties. `init` has the following properties: - `aspectRatio` {{optional_inline}} - : A number indicating the ratio of the visible cylinder section. It is the ratio of the width of the visible section of the cylinder divided by its height. The width is calculated by multiplying the `radius` with the `centralAngle`. The default value is `2.0`. - `centralAngle` {{optional_inline}} - : A number indicating the angle in radians of the visible section of the cylinder. Default value: `0.78539` (π / 4). - `colorFormat` {{optional_inline}} - : A {{domxref("WebGL_API/Types", "GLenum")}} defining the data type of the color texture data. Possible values: - `gl.RGB` - `gl.RGBA` Additionally, for contexts with the {{domxref("EXT_sRGB")}} extension enabled: - `ext.SRGB_EXT` - `ext.SRGB_ALPHA_EXT` Additionally, for {{domxref("WebGL2RenderingContext")}} contexts: - `gl.RGBA8` - `gl.RGB8` - `gl.SRGB8` - `gl.RGB8_ALPHA8` Additionally, for contexts with the {{domxref("WEBGL_compressed_texture_etc")}} extension enabled: - `ext.COMPRESSED_RGB8_ETC2` - `ext.COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2` - `ext.COMPRESSED_RGBA8_ETC2_EAC` - `ext.COMPRESSED_SRGB8_ETC2` - `ext.COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2` - `ext.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC` Additionally, for contexts with the {{domxref("WEBGL_compressed_texture_astc")}} extension enabled: - `All` of the formats the extension supports. The default value is `gl.RGBA`. - `depthFormat` {{optional_inline}} - : A {{domxref("WebGL_API/Types", "GLenum")}} defining the data type of the depth texture data or `0` indicating that the layer should not provide a depth texture (in that case {{domxref("XRProjectionLayer.ignoreDepthValues")}} will be `true`). Possible values within {{domxref("WebGLRenderingContext")}} contexts with the {{domxref("WEBGL_depth_texture")}} extension enabled, or within {{domxref("WebGL2RenderingContext")}} contexts (no extension required): - `gl.DEPTH_COMPONENT` - `gl.DEPTH_STENCIL` Additionally, for {{domxref("WebGL2RenderingContext")}} contexts: - `gl.DEPTH_COMPONENT24` - `gl.DEPTH24_STENCIL24` The default value is `gl.DEPTH_COMPONENT`. - `isStatic` {{optional_inline}} - : A boolean that, if true, indicates you can only draw to this layer when {{domxref("XRCompositionLayer.needsRedraw", "needsRedraw")}} is `true`. The default value is `false`. - `layout` {{optional_inline}} - : A string indicating the layout of the layer. Possible values: - `default` - : The layer accommodates all views of the session. - `mono` - : A single {{domxref("XRSubImage")}} is allocated and presented to both eyes. - `stereo` - : The user agent decides how it allocates the {{domxref("XRSubImage")}} (one or two) and the layout (top/bottom or left/right). - `stereo-left-right` - : A single {{domxref("XRSubImage")}} is allocated. Left eye gets the left area of the texture, right eye the right. - `stereo-top-bottom` - : A single {{domxref("XRSubImage")}} is allocated. Left eye gets the top area of the texture, right eye the bottom. The default value is `mono`. - `mipLevels` {{optional_inline}} - : A number specifying desired number of mip levels. The default value is `1`. - `radius` {{optional_inline}} - : A number indicating the radius of the cylinder. Default value: `2.0`. - `space` **Required** - : An {{domxref("XRSpace")}} object defining the layer's spatial relationship with the user's physical environment. - `textureType` {{optional_inline}} - : A string defining the type of texture the layer will have. Possible values: - `texture`: The textures of {{domxref("XRWebGLSubImage")}} will be of type `gl.TEXTURE_2D`. - `texture-array`: the textures of {{domxref("XRWebGLSubImage")}} will be of type `gl.TEXTURE_2D_ARRAY` (WebGL 2 contexts only). The default value is `texture`. - `transform` {{optional_inline}} - : An {{domxref("XRRigidTransform")}} object defining the offset and orientation relative to `space`. - `viewPixelHeight` **Required** - : A number specifying the pixel height of the layer view. - `viewPixelWidth` **Required** - : A number specifying the pixel width of the layer view. ### Return value An {{domxref("XRCylinderLayer")}} object. ## Examples ### Creating an `XRCylinderLayer` Configure the cylinder layer using the properties listed above in a call to `createCylinderLayer()`. To present layers to the XR device, add them to the `layers` render state using {{domxref("XRSession.updateRenderState()")}}. ```js function onXRSessionStarted(xrSession) { const glCanvas = document.createElement("canvas"); const gl = glCanvas.getContext("webgl2", { xrCompatible: true }); const xrGlBinding = new XRWebGLBinding(xrSession, gl); const cylinderLayer = xrGlBinding.createCylinderLayer({ space: xrReferenceSpace, viewPixelWidth: 1200, viewPixelHeight: 600, centralAngle: (60 * Math.PI) / 180, aspectRatio: 2, radius: 2, transform: new XRRigidTransform(/* … */), }); xrSession.updateRenderState({ layers: [cylinderLayer], }); } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("XRCylinderLayer")}} - [WebGL constants](/en-US/docs/Web/API/WebGL_API/Constants)
0
data/mdn-content/files/en-us/web/api/xrwebglbinding
data/mdn-content/files/en-us/web/api/xrwebglbinding/getreflectioncubemap/index.md
--- title: "XRWebGLBinding: getReflectionCubeMap() method" short-title: getReflectionCubeMap() slug: Web/API/XRWebGLBinding/getReflectionCubeMap page-type: web-api-instance-method status: - experimental browser-compat: api.XRWebGLBinding.getReflectionCubeMap --- {{APIRef("WebXR Device API")}}{{SeeCompatTable}} The **`getReflectionCubeMap()`** method of the {{domxref("XRWebGLBinding")}} interface returns a {{domxref("WebGLTexture")}} object containing a reflection cube map texture. The texture format is specified by the session's `reflectionFormat`. See the `options` parameter on {{domxref("XRSession.requestLightProbe()")}} and {{domxref("XRSession.preferredReflectionFormat")}} for more details. By default, the `srgba8` format is used. When using a `rgba16f` format, you need to be within a WebGL 2.0 context or enable the {{domxref("OES_texture_half_float")}} extension within WebGL 1.0 contexts. ## Syntax ```js-nolint getReflectionCubeMap(lightProbe) ``` ### Parameters - `lightProbe` - : An {{domxref("XRLightProbe")}} object returned by calling {{domxref("XRSession.requestLightProbe()")}}. ### Return value A {{domxref("WebGLTexture")}} object. ## Examples You typically call `getReflectionCubeMap()` whenever the `reflectionchange` event fires on a light probe to retrieve an updated cube map. This is less expensive than retrieving lighting information with every {{domxref("XRFrame")}}. If the `rgba16f` format is used, enable the {{domxref("OES_texture_half_float")}} extension within WebGL 1.0 contexts. ```js const glBinding = new XRWebGLBinding(xrSession, gl); gl.getExtension("OES_texture_half_float"); // if rgba16f is the preferredReflectionFormat xrSession.requestLightProbe().then((lightProbe) => { lightProbe.addEventListener("reflectionchange", () => { glBinding.getReflectionCubeMap(lightProbe); }); }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("XRLightProbe")}} - {{domxref("OES_texture_half_float")}}
0
data/mdn-content/files/en-us/web/api/xrwebglbinding
data/mdn-content/files/en-us/web/api/xrwebglbinding/xrwebglbinding/index.md
--- title: "XRWebGLBinding: XRWebGLBinding() constructor" short-title: XRWebGLBinding() slug: Web/API/XRWebGLBinding/XRWebGLBinding page-type: web-api-constructor status: - experimental browser-compat: api.XRWebGLBinding.XRWebGLBinding --- {{APIRef("WebXR Device API")}}{{SeeCompatTable}} The **`XRWebGLBinding()`** constructor creates and returns a new {{domxref("XRWebGLBinding")}} object. ## Syntax ```js-nolint new XRWebGLBinding(session, context) ``` ### Parameters - `session` - : An {{domxref("XRSession")}} object specifying the WebXR session which will be rendered using the WebGL context. - `context` - : A {{domxref("WebGLRenderingContext")}} or {{domxref("WebGL2RenderingContext")}} identifying the WebGL drawing context to use for rendering the scene for the specified WebXR session. ### Return value A new {{domxref("XRWebGLBinding")}}. ### Exceptions - `InvalidStateError` {{domxref("DOMException")}} - : Thrown if the new `XRWebGLBinding` could not be created due to one of the following situations: - The {{domxref("XRSession")}} specified by `session` has already been stopped. - The specified WebGL context, `context`, [has been lost](/en-US/docs/Web/API/WebGLRenderingContext/isContextLost#usage_notes) for any reason, such as a GPU switch or reset. - The specified `session` is immersive but the `context` is not WebXR compatible. ## Examples ```js const canvasElement = document.querySelector(".output-canvas"); const gl = canvasElement.getContext("webgl"); const xrSession = await navigator.xr.requestSession("immersive-vr"); await gl.makeXRCompatible(); const glBinding = new XRWebGLBinding(xrSession, gl); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("WebGLRenderingContext.makeXRCompatible()")}}
0
data/mdn-content/files/en-us/web/api/xrwebglbinding
data/mdn-content/files/en-us/web/api/xrwebglbinding/createequirectlayer/index.md
--- title: "XRWebGLBinding: createEquirectLayer() method" short-title: createEquirectLayer() slug: Web/API/XRWebGLBinding/createEquirectLayer page-type: web-api-instance-method status: - experimental browser-compat: api.XRWebGLBinding.createEquirectLayer --- {{APIRef("WebXR Device API")}}{{SeeCompatTable}} The **`createEquirectLayer()`** method of the {{domxref("XRWebGLBinding")}} interface returns an {{domxref("XREquirectLayer")}} object, which is a layer that maps [equirectangular](https://en.wikipedia.org/wiki/Equirectangular_projection) coded data onto the inside of a sphere. ## Syntax ```js-nolint createEquirectLayer(options) ``` ### Parameters - `options` - : An object to configure the {{domxref("XREquirectLayer")}}. It must have the `space`, `viewPixelHeight`, and `viewPixelWidth` properties. `init` has the following properties: - `centralHorizontalAngle` {{optional_inline}} - : A number indicating the central horizontal angle in radians of the sphere. Default value: `6.28318` (2π). - `colorFormat` {{optional_inline}} - : A {{domxref("WebGL_API/Types", "GLenum")}} defining the data type of the color texture data. Possible values: - `gl.RGB` - `gl.RGBA` Additionally, for contexts with the {{domxref("EXT_sRGB")}} extension enabled: - `ext.SRGB_EXT` - `ext.SRGB_ALPHA_EXT` Additionally, for {{domxref("WebGL2RenderingContext")}} contexts: - `gl.RGBA8` - `gl.RGB8` - `gl.SRGB8` - `gl.RGB8_ALPHA8` Additionally, for contexts with the {{domxref("WEBGL_compressed_texture_etc")}} extension enabled: - `ext.COMPRESSED_RGB8_ETC2` - `ext.COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2` - `ext.COMPRESSED_RGBA8_ETC2_EAC` - `ext.COMPRESSED_SRGB8_ETC2` - `ext.COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2` - `ext.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC` Additionally, for contexts with the {{domxref("WEBGL_compressed_texture_astc")}} extension enabled: - `All` of the formats the extension supports. The default value is `gl.RGBA`. - `depthFormat` {{optional_inline}} - : A {{domxref("WebGL_API/Types", "GLenum")}} defining the data type of the depth texture data, or else `0` to indicate that the layer should not provide a depth texture (in that case {{domxref("XRProjectionLayer.ignoreDepthValues")}} will be `true`). Possible values within {{domxref("WebGLRenderingContext")}} contexts with the {{domxref("WEBGL_depth_texture")}} extension enabled, or within {{domxref("WebGL2RenderingContext")}} contexts (no extension required): - `gl.DEPTH_COMPONENT` - `gl.DEPTH_STENCIL` Additionally, for {{domxref("WebGL2RenderingContext")}} contexts: - `gl.DEPTH_COMPONENT24` - `gl.DEPTH24_STENCIL24` The default value is `gl.DEPTH_COMPONENT`. - `isStatic` {{optional_inline}} - : A boolean that, if true, indicates you can only draw to this layer when {{domxref("XRCompositionLayer.needsRedraw", "needsRedraw")}} is `true`. The default value is `false`. - `layout` {{optional_inline}} - : A string indicating the layout of the layer. Possible values: - `default` - : The layer accommodates all views of the session. - `mono` - : A single {{domxref("XRSubImage")}} is allocated and presented to both eyes. - `stereo` - : The user agent decides how it allocates the {{domxref("XRSubImage")}} (one or two) and the layout (top/bottom or left/right). - `stereo-left-right` - : A single {{domxref("XRSubImage")}} is allocated. Left eye gets the left area of the texture, right eye the right. - `stereo-top-bottom` - : A single {{domxref("XRSubImage")}} is allocated. Left eye gets the top area of the texture, right eye the bottom. The default value is `mono`. - `lowerVerticalAngle` {{optional_inline}} - : A number indicating the lower vertical angle in radians of the sphere. Default value: `-1.570795` (-π/2). - `mipLevels` {{optional_inline}} - : A number specifying desired number of mip levels. The default value is `1`. - `radius` {{optional_inline}} - : A number indicating the radius of the sphere. Default value: `0` (infinite sphere). - `space` **Required** - : An {{domxref("XRSpace")}} object defining the layer's spatial relationship with the user's physical environment. - `textureType` {{optional_inline}} - : A string defining the type of texture the layer will have. Possible values: - `texture` - : The textures of {{domxref("XRWebGLSubImage")}} will be of type `gl.TEXTURE_2D`. - `texture-array` - : The textures of {{domxref("XRWebGLSubImage")}} will be of type `gl.TEXTURE_2D_ARRAY` (WebGL 2 contexts only). The default value is `texture`. - `transform` {{optional_inline}} - : An {{domxref("XRRigidTransform")}} object defining the offset and orientation relative to `space`. - `upperVerticalAngle` {{optional_inline}} - : A number indicating the upper vertical angle in radians of the sphere. Default value: `1.570795` (π/2). - `viewPixelHeight` **Required** - : A number specifying the pixel height of the layer view. - `viewPixelWidth` **Required** - : A number specifying the pixel width of the layer view. ### Return value An {{domxref("XREquirectLayer")}} object. ## Examples ### Creating an `XREquirectLayer` Configure the equirect layer using the properties listed above in a call to `createEquirect()`. To present layers to the XR device, add them to the `layers` render state using {{domxref("XRSession.updateRenderState()")}}. ```js function onXRSessionStarted(xrSession) { const glCanvas = document.createElement("canvas"); const gl = glCanvas.getContext("webgl2", { xrCompatible: true }); const xrGlBinding = new XRWebGLBinding(xrSession, gl); const equirectLayer = xrGlBinding.createEquirectLayer({ space: xrReferenceSpace, viewPixelWidth: 1200, viewPixelHeight: 600, centralHorizontalAngle: 2 * Math.PI, upperVerticalAngle: Math.PI / 2.0, lowerVerticalAngle: -Math.PI / 2.0, radius: 0, }); xrSession.updateRenderState({ layers: [equirectLayer], }); } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("XREquirectLayer")}} - [WebGL constants](/en-US/docs/Web/API/WebGL_API/Constants)
0
data/mdn-content/files/en-us/web/api/xrwebglbinding
data/mdn-content/files/en-us/web/api/xrwebglbinding/getsubimage/index.md
--- title: "XRWebGLBinding: getSubImage() method" short-title: getSubImage() slug: Web/API/XRWebGLBinding/getSubImage page-type: web-api-instance-method status: - experimental browser-compat: api.XRWebGLBinding.getSubImage --- {{APIRef("WebXR Device API")}}{{SeeCompatTable}} The **`getSubImage()`** method of the {{domxref("XRWebGLBinding")}} interface returns a {{domxref("XRWebGLSubImage")}} object representing the WebGL texture to render. ## Syntax ```js-nolint getSubImage(layer, frame) getSubImage(layer, frame, eye) ``` ### Parameters - `layer` - : The {{domxref("XRCompositionLayer")}} to use for rendering (can be all types of `XRCompositionLayer` objects except {{domxref("XRProjectionLayer")}}, see {{domxref("XRWebGLBinding.getViewSubImage()")}} for rendering projection layers). - `frame` - : The {{domxref("XRFrame")}} frame to use for rendering. - `eye` {{optional_inline}} - : An optional {{domxref("XRView.eye")}} indicating which view's eye to use for rendering. Possible values: - `left` - : The {{domxref("XRView")}} represents the point-of-view of the viewer's left eye. - `right` - : The view represents the viewer's right eye. - `none` - : The view describes a monoscopic view, or the view otherwise doesn't represent a particular eye's point-of-view. Defaults to `none`. ### Return value A {{domxref("XRWebGLSubImage")}} object. ### Exceptions A {{jsxref("TypeError")}} is thrown, - if `layer` is not in the [session's `layer` array](/en-US/docs/Web/API/XRSession/updateRenderState#setting_the_layers_array). - if `layer` is a {{domxref("XRProjectionLayer")}}. - if the layer's [`layout`](/en-US/docs/Web/API/XRCompositionLayer/layout) property is `default`. - if the layer's [`layout`](/en-US/docs/Web/API/XRCompositionLayer/layout) property is `stereo` and `eye` is `none`. ## Examples ### Rendering an `XRQuadLayer` The following example renders an {{domxref("XRQuadLayer")}}. ```js const xrGlBinding = new XRWebGLBinding(xrSession, gl); const quadLayer = xrGlBinding.createQuadLayer({ space: xrReferenceSpace, viewPixelWidth: 512, viewPixelHeight: 512, }); // Position 2 meters away from the origin with a width and height of 1.5 meters quadLayer.transform = new XRRigidTransform({ z: -2 }); quadLayer.width = 1.5; quadLayer.height = 1.5; const framebuffer = gl.createFramebuffer(); xrSession.updateRenderState({ layers: [quadLayer] }); xrSession.requestAnimationFrame(onXRFrame); function onXRFrame(time, xrFrame) { xrSession.requestAnimationFrame(onXRFrame); gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer); let subImage = xrGlBinding.getSubImage(quadLayer, xrFrame); gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, subImage.colorTexture, 0, ); let viewport = subImage.viewport; gl.viewport(viewport.x, viewport.y, viewport.width, viewport.height); // Render content for the quad layer } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("XRWebGLSubImage")}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/history/index.md
--- title: History slug: Web/API/History page-type: web-api-interface browser-compat: api.History --- {{APIRef("History API")}} The **`History`** interface of the {{domxref("History API", "", "", "nocode")}} allows manipulation of the browser _session history_, that is the pages visited in the tab or frame that the current page is loaded in. There is only one instance of `history` (It is a _singleton_.) accessible via the global object {{domxref("Window.history", "history")}}. > **Note:** This interface is only available on the main thread ({{domxref("Window")}}). It cannot be accessed in {{domxref("Worker")}} or {{domxref("Worklet")}} contexts. ## Instance properties _The `History` interface doesn't inherit any property._ - {{domxref("History.length","length")}} {{ReadOnlyInline}} - : Returns an `Integer` representing the number of elements in the session history, including the currently loaded page. For example, for a page loaded in a new tab this property returns `1`. - {{domxref("History.scrollRestoration","scrollRestoration")}} - : Allows web applications to explicitly set default scroll restoration behavior on history navigation. This property can be either `auto` or `manual`. - {{domxref("History.state","state")}} {{ReadOnlyInline}} - : Returns an `any` value representing the state at the top of the history stack. This is a way to look at the state without having to wait for a {{domxref("Window/popstate_event", "popstate")}} event. ## Instance methods _The `History`_ _interface doesn't inherit any methods._ - {{domxref("History.back","back()")}} - : This asynchronous method goes to the previous page in session history, the same action as when the user clicks the browser's <kbd>Back</kbd> button. Equivalent to `history.go(-1)`. Calling this method to go back beyond the first page in the session history has no effect and doesn't raise an exception. - {{domxref("History.forward","forward()")}} - : This asynchronous method goes to the next page in session history, the same action as when the user clicks the browser's <kbd>Forward</kbd> button; this is equivalent to `history.go(1)`. Calling this method to go forward beyond the most recent page in the session history has no effect and doesn't raise an exception. - {{domxref("History.go","go()")}} - : Asynchronously loads a page from the session history, identified by its relative location to the current page, for example `-1` for the previous page or `1` for the next page. If you specify an out-of-bounds value (for instance, specifying `-1` when there are no previously-visited pages in the session history), this method silently has no effect. Calling `go()` without parameters or a value of `0` reloads the current page. - {{domxref("History.pushState","pushState()")}} - : Pushes the given data onto the session history stack with the specified title (and, if provided, URL). The data is treated as opaque by the DOM; you may specify any JavaScript object that can be serialized. Note that all browsers but Safari currently ignore the _title_ parameter. For more information, see [Working with the History API](/en-US/docs/Web/API/History_API/Working_with_the_History_API). - {{domxref("History.replaceState","replaceState()")}} - : Updates the most recent entry on the history stack to have the specified data, title, and, if provided, URL. The data is treated as opaque by the DOM; you may specify any JavaScript object that can be serialized. Note that all browsers but Safari currently ignore the _title_ parameter. For more information, see [Working with the History API](/en-US/docs/Web/API/History_API/Working_with_the_History_API). ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("Window.history", "history")}} global object
0
data/mdn-content/files/en-us/web/api/history
data/mdn-content/files/en-us/web/api/history/go/index.md
--- title: "History: go() method" short-title: go() slug: Web/API/History/go page-type: web-api-instance-method browser-compat: api.History.go --- {{APIRef("History API")}} The **`go()`** method of the {{domxref("History")}} interface loads a specific page from the session history. You can use it to move forwards and backwards through the history depending on the value of a parameter. This method is {{glossary("asynchronous")}}. Add a listener for the {{domxref("Window/popstate_event", "popstate")}} event in order to determine when the navigation has completed. ## Syntax ```js-nolint go() go(delta) ``` ### Parameters - `delta` {{optional_inline}} - : The position in the history to which you want to move, relative to the current page. A negative value moves backwards, a positive value moves forwards. So, for example, `history.go(2)` moves forward two pages and `history.go(-2)` moves back two pages. If no value is passed or if `delta` equals 0, it has the same result as calling `location.reload()`. ### Return value None ({{jsxref("undefined")}}). ### Exceptions - `SecurityError` {{domxref("DOMException")}} - : Thrown if the associated document is not fully active. ## Examples To move back one page (the equivalent of calling {{domxref("History.back", "back()")}}): ```js history.go(-1); ``` To move forward a page, just like calling {{domxref("History.forward", "forward()")}}: ```js history.go(1); ``` To move forward two pages: ```js history.go(2); ``` To move backwards by two pages: ```js history.go(-2); ``` And, finally either of the following statements will reload the current page: ```js history.go(); history.go(0); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("History")}} - {{DOMxRef("History.back","back()")}} - {{DOMxRef("History.forward","forward()")}} - {{domxref("Window/popstate_event", "popstate")}} event - [Working with the History API](/en-US/docs/Web/API/History_API/Working_with_the_History_API)
0
data/mdn-content/files/en-us/web/api/history
data/mdn-content/files/en-us/web/api/history/length/index.md
--- title: "History: length property" short-title: length slug: Web/API/History/length page-type: web-api-instance-property browser-compat: api.History.length --- {{APIRef("History API")}} The **`length`** read-only property of the {{DOMxRef("History")}} interface returns an integer representing the number of elements in the session history, including the currently loaded page. For example, for a page loaded in a new tab this property returns `1`. ## Value A number. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The {{domxref("History")}} interface it belongs to.
0
data/mdn-content/files/en-us/web/api/history
data/mdn-content/files/en-us/web/api/history/replacestate/index.md
--- title: "History: replaceState() method" short-title: replaceState() slug: Web/API/History/replaceState page-type: web-api-instance-method browser-compat: api.History.replaceState --- {{APIRef("History API")}} The **`replaceState()`** method of the {{domxref("History")}} interface modifies the current history entry, replacing it with the state object and URL passed in the method parameters. This method is particularly useful when you want to update the state object or URL of the current history entry in response to some user action. ## Syntax ```js-nolint replaceState(state, unused) replaceState(state, unused, url) ``` ### Parameters - `state` - : An object which is associated with the history entry passed to the `replaceState()` method. The state object can be `null`. - `unused` - : This parameter exists for historical reasons, and cannot be omitted; passing the empty string is traditional, and safe against future changes to the method. - `url` {{optional_inline}} - : The URL of the history entry. The new URL must be of the same origin as the current URL; otherwise the `replaceState()` method throws an exception. ### Return value None ({{jsxref("undefined")}}). ### Exceptions - `SecurityError` {{domxref("DOMException")}} - : Thrown if the associated document is not fully active, or if the provided `url` parameter is not a valid URL. - `DataCloneError` {{domxref("DOMException")}} - : Thrown if the provided `state` parameter is not serializable. ## Examples Suppose `https://www.mozilla.org/foo.html` executes the following JavaScript: ```js const stateObj = { foo: "bar" }; history.pushState(stateObj, "", "bar.html"); ``` On the next page you could then use `history.state` to access the `stateObj` that was just added. The explanation of these two lines above can be found in the [Working with the History API](/en-US/docs/Web/API/History_API/Working_with_the_History_API#using_pushstate) article. Then suppose `https://www.mozilla.org/bar.html` executes the following JavaScript: ```js history.replaceState(stateObj, "", "bar2.html"); ``` This will cause the URL bar to display `https://www.mozilla.org/bar2.html`, but won't cause the browser to load `bar2.html` or even check that `bar2.html` exists. Suppose now that the user navigates to `https://www.microsoft.com`, then clicks the Back button. At this point, the URL bar will display `https://www.mozilla.org/bar2.html`. If the user now clicks Back again, the URL bar will display `https://www.mozilla.org/foo.html`, and totally bypass bar.html. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/history
data/mdn-content/files/en-us/web/api/history/back/index.md
--- title: "History: back() method" short-title: back() slug: Web/API/History/back page-type: web-api-instance-method browser-compat: api.History.back --- {{APIRef("History API")}} The **`back()`** method of the {{domxref("History")}} interface causes the browser to move back one page in the session history. It has the same effect as calling {{domxref("History.go", "history.go(-1)")}}. If there is no previous page, this method call does nothing. This method is {{glossary("asynchronous")}}. Add a listener for the {{domxref("Window/popstate_event", "popstate")}} event in order to determine when the navigation has completed. ## Syntax ```js-nolint back() ``` ### Parameters None. ### Return value None ({{jsxref("undefined")}}). ### Exceptions - `SecurityError` {{domxref("DOMException")}} - : Thrown if the associated document is not fully active. ## Examples The following short example causes a button on the page to navigate back one entry in the session history. ### HTML ```html <button id="go-back">Go back!</button> ``` ### JavaScript ```js document.getElementById("go-back").addEventListener("click", () => { history.back(); }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("History")}} - [Working with the History API](/en-US/docs/Web/API/History_API/Working_with_the_History_API)
0
data/mdn-content/files/en-us/web/api/history
data/mdn-content/files/en-us/web/api/history/state/index.md
--- title: "History: state property" short-title: state slug: Web/API/History/state page-type: web-api-instance-property browser-compat: api.History.state --- {{APIRef("History API")}} The **`state`** read-only property of the {{DOMxRef("History")}} interface returns a value representing the state at the top of the history stack. This is a way to look at the state without having to wait for a {{domxref("Window/popstate_event", "popstate")}} event. ## Value The state at the top of the history stack. The value is [`null`](/en-US/docs/Web/JavaScript/Reference/Operators/null) until the {{domxref("History.pushState","pushState()")}} or {{domxref("History.replaceState","replaceState()")}} method is used. ## Examples The code below logs the value of `history.state` before using the {{domxref("History.pushState","pushState()")}} method to push a value to the history. The next line logs the value to the console again, showing that `history.state` now has a value. ```js // Should be null because we haven't modified the history stack yet console.log("History.state before pushState: ", history.state); // Now push something on the stack history.pushState({ name: "Example" }, "pushState example", "page3.html"); // Now state has a value. console.log("History.state after pushState: ", history.state); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Working with the History API](/en-US/docs/Web/API/History_API/Working_with_the_History_API) - [`History.pushState()`](/en-US/docs/Web/API/History/pushState) - [`History.replaceState()`](/en-US/docs/Web/API/History/replaceState) - [`PopStateEvent.state`](/en-US/docs/Web/API/PopStateEvent/state)
0
data/mdn-content/files/en-us/web/api/history
data/mdn-content/files/en-us/web/api/history/pushstate/index.md
--- title: "History: pushState() method" short-title: pushState() slug: Web/API/History/pushState page-type: web-api-instance-method browser-compat: api.History.pushState --- {{APIRef("History API")}} The **`pushState()`** method of the {{domxref("History")}} interface adds an entry to the browser's session history stack. ## Syntax ```js-nolint pushState(state, unused) pushState(state, unused, url) ``` ### Parameters - `state` - : The `state` object is a JavaScript object which is associated with the new history entry created by `pushState()`. Whenever the user navigates to the new `state`, a {{domxref("Window/popstate_event", "popstate")}} event is fired, and the `state` property of the event contains a copy of the history entry's `state` object. The `state` object can be anything that can be serialized. > **Note:** Some browsers save `state` objects to the user's disk so they can be restored after the user restarts the browser, and impose a size limit on the serialized representation of a `state` object, and will throw an exception if you pass a `state` object whose serialized representation is larger than that size limit. So in cases where you want to ensure you have more space than what some browsers might impose, you're encouraged to use {{domxref("Window.sessionStorage", "sessionStorage")}} and/or {{domxref("Window.localStorage", "localStorage")}}. - `unused` - : This parameter exists for historical reasons, and cannot be omitted; passing an empty string is safe against future changes to the method. - `url` {{optional_inline}} - : The new history entry's URL. Note that the browser won't attempt to load this URL after a call to `pushState()`, but it may attempt to load the URL later, for instance, after the user restarts the browser. The new URL does not need to be absolute; if it's relative, it's resolved relative to the current URL. The new URL must be of the same {{glossary("origin")}} as the current URL; otherwise, `pushState()` will throw an exception. If this parameter isn't specified, it's set to the document's current URL. ### Return value None ({{jsxref("undefined")}}). ### Exceptions - `SecurityError` {{domxref("DOMException")}} - : Thrown if the associated document is not fully active, or if the provided `url` parameter is not a valid URL. - `DataCloneError` {{domxref("DOMException")}} - : Thrown if the provided `state` parameter is not serializable. ## Description In a sense, calling `pushState()` is similar to setting `window.location = "#foo"`, in that both will also create and activate another history entry associated with the current document. But `pushState()` has a few advantages: - The new URL can be any URL in the same origin as the current URL. In contrast, setting {{domxref("window.location")}} keeps you at the same document only if you modify only the hash. - Changing the page's URL is optional. In contrast, setting `window.location = "#foo";` only creates a new history entry if the current hash isn't `#foo`. - You can associate arbitrary data with your new history entry. With the hash-based approach, you need to encode all of the relevant data into a short string. Note that `pushState()` never causes a {{domxref("Window/hashchange_event", "hashchange")}} event to be fired, even if the new URL differs from the old URL only in its hash. ## Examples This creates a new browser history entry setting the _state_ and _url_. ### JavaScript ```js const state = { page_id: 1, user_id: 5 }; const url = "hello-world.html"; history.pushState(state, "", url); ``` ### Change a query parameter ```js const url = new URL(location); url.searchParams.set("foo", "bar"); history.pushState({}, "", url); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Working with the History API](/en-US/docs/Web/API/History_API/Working_with_the_History_API) - [Window: popstate event](/en-US/docs/Web/API/Window/popstate_event)
0
data/mdn-content/files/en-us/web/api/history
data/mdn-content/files/en-us/web/api/history/forward/index.md
--- title: "History: forward() method" short-title: forward() slug: Web/API/History/forward page-type: web-api-instance-method browser-compat: api.History.forward --- {{APIRef("History API")}} The **`forward()`** method of the {{domxref("History")}} interface causes the browser to move forward one page in the session history. It has the same effect as calling {{domxref("History.go", "history.go(1)")}}. This method is {{glossary("asynchronous")}}. Add a listener for the {{domxref("Window/popstate_event", "popstate")}} event in order to determine when the navigation has completed. ## Syntax ```js-nolint forward() ``` ### Parameters None. ### Return value None ({{jsxref("undefined")}}). ### Exceptions - `SecurityError` {{domxref("DOMException")}} - : Thrown if the associated document is not fully active. ## Examples The following examples create a button that moves forward one step in the session history. ### HTML ```html <button id="go-forward">Go Forward!</button> ``` ### JavaScript ```js document.getElementById("go-forward").addEventListener("click", (e) => { history.forward(); }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("History")}} - {{domxref("Window/popstate_event", "popstate")}} - [Working with the History API](/en-US/docs/Web/API/History_API/Working_with_the_History_API)
0
data/mdn-content/files/en-us/web/api/history
data/mdn-content/files/en-us/web/api/history/scrollrestoration/index.md
--- title: "History: scrollRestoration property" short-title: scrollRestoration slug: Web/API/History/scrollRestoration page-type: web-api-instance-property browser-compat: api.History.scrollRestoration --- {{APIRef("History API")}} The **`scrollRestoration`** property of the {{DOMxRef("History")}} interface allows web applications to explicitly set default scroll restoration behavior on history navigation. ## Value One of the following: - `auto` - : The location on the page to which the user has scrolled will be restored. - `manual` - : The location on the page is not restored. The user will have to scroll to the location manually. ## Examples ### Query the current scroll restoration behavior ```js const scrollRestoration = history.scrollRestoration; if (scrollRestoration === "manual") { console.log( "The location on the page is not restored, user will need to scroll manually.", ); } ``` ### Prevent automatic page location restoration ```js if (history.scrollRestoration) { history.scrollRestoration = "manual"; } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/svgfemergenodeelement/index.md
--- title: SVGFEMergeNodeElement slug: Web/API/SVGFEMergeNodeElement page-type: web-api-interface browser-compat: api.SVGFEMergeNodeElement --- {{APIRef("SVG")}} The **`SVGFEMergeNodeElement`** interface corresponds to the {{SVGElement("feMergeNode")}} element. {{InheritanceDiagram}} ## Instance properties _This interface also inherits properties from its parent interface, {{domxref("SVGElement")}}._ - {{domxref("SVGFEMergeNodeElement.in1")}} {{ReadOnlyInline}} - : An {{domxref("SVGAnimatedString")}} corresponding to the {{SVGAttr("in")}} attribute of the given element. ## Instance methods _This interface does not provide any specific methods, but implements those of its parent, {{domxref("SVGElement")}}._ ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{SVGElement("feMergeNode")}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/csscounterstylerule/index.md
--- title: CSSCounterStyleRule slug: Web/API/CSSCounterStyleRule page-type: web-api-interface browser-compat: api.CSSCounterStyleRule --- {{APIRef("CSS Counter Styles")}} The **`CSSCounterStyleRule`** interface represents an {{CSSxRef("@counter-style")}} [at-rule](/en-US/docs/Web/CSS/At-rule). {{InheritanceDiagram}} ## Instance properties _This interface also inherits properties from its parent {{DOMxRef("CSSRule")}}._ - {{DOMxRef("CSSCounterStyleRule.name")}} - : A string object that contains the serialization of the {{CSSxRef("&lt;custom-ident&gt;")}} defined as the `name` for the associated rule. - {{DOMxRef("CSSCounterStyleRule.system")}} - : A string object that contains the serialization of the {{CSSxRef("@counter-style/system", "system")}} descriptor defined for the associated rule. If the descriptor was not specified in the associated rule, the attribute returns an empty string. - {{DOMxRef("CSSCounterStyleRule.symbols")}} - : A string object that contains the serialization of the {{CSSxRef("@counter-style/symbols", "symbols")}} descriptor defined for the associated rule. If the descriptor was not specified in the associated rule, the attribute returns an empty string. - {{DOMxRef("CSSCounterStyleRule.additiveSymbols")}} - : A string object that contains the serialization of the {{CSSxRef("@counter-style/additive-symbols", "additive-symbols")}} descriptor defined for the associated rule. If the descriptor was not specified in the associated rule, the attribute returns an empty string. - {{DOMxRef("CSSCounterStyleRule.negative")}} - : A string object that contains the serialization of the {{CSSxRef("@counter-style/negative", "negative")}} descriptor defined for the associated rule. If the descriptor was not specified in the associated rule, the attribute returns an empty string. - {{DOMxRef("CSSCounterStyleRule.prefix")}} - : A string object that contains the serialization of the {{CSSxRef("@counter-style/prefix", "prefix")}} descriptor defined for the associated rule. If the descriptor was not specified in the associated rule, the attribute returns an empty string. - {{DOMxRef("CSSCounterStyleRule.suffix")}} - : A string object that contains the serialization of the {{CSSxRef("@counter-style/suffix", "suffix")}} descriptor defined for the associated rule. If the descriptor was not specified in the associated rule, the attribute returns an empty string. - {{DOMxRef("CSSCounterStyleRule.range")}} - : A string object that contains the serialization of the {{CSSxRef("@counter-style/range", "range")}} descriptor defined for the associated rule. If the descriptor was not specified in the associated rule, the attribute returns an empty string. - {{DOMxRef("CSSCounterStyleRule.pad")}} - : A string object that contains the serialization of the {{CSSxRef("@counter-style/pad", "pad")}} descriptor defined for the associated rule. If the descriptor was not specified in the associated rule, the attribute returns an empty string. - {{DOMxRef("CSSCounterStyleRule.speakAs")}} - : A string object that contains the serialization of the {{CSSxRef("@counter-style/speak-as", "speak-as")}} descriptor defined for the associated rule. If the descriptor was not specified in the associated rule, the attribute returns an empty string. - {{DOMxRef("CSSCounterStyleRule.fallback")}} - : A string object that contains the serialization of the {{CSSxRef("@counter-style/fallback", "fallback")}} descriptor defined for the associated rule. If the descriptor was not specified in the associated rule, the attribute returns an empty string. ## Instance methods _This interface doesn't implement any specific method but inherits methods from its parent {{DOMxRef("CSSRule")}}._ ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{CSSxRef("@counter-style")}} - [CSS counter styles](/en-US/docs/Web/CSS/CSS_counter_styles) module
0
data/mdn-content/files/en-us/web/api/csscounterstylerule
data/mdn-content/files/en-us/web/api/csscounterstylerule/name/index.md
--- title: "CSSCounterStyleRule: name property" short-title: name slug: Web/API/CSSCounterStyleRule/name page-type: web-api-instance-property browser-compat: api.CSSCounterStyleRule.name --- {{DefaultAPISidebar("CSS Counter Styles")}} The **`name`** property of the {{domxref("CSSCounterStyleRule")}} interface gets and sets the {{CSSxRef("&lt;custom-ident&gt;")}} defined as the `name` for the associated rule. ## Value A string ## Examples The following example shows a {{cssxref("@counter-style")}} rule. In JavaScript, `myRules[0]` is this `@counter-style` rule, returning `name` gives us the custom ident "box-corner". ```css @counter-style box-corner { system: fixed; symbols: ◰ ◳ ◲ ◱; suffix: ": "; fallback: disc; } ``` ```js let myRules = document.styleSheets[0].cssRules; console.log(myRules[0].name); // "box-corner" ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/csscounterstylerule
data/mdn-content/files/en-us/web/api/csscounterstylerule/speakas/index.md
--- title: "CSSCounterStyleRule: speakAs property" short-title: speakAs slug: Web/API/CSSCounterStyleRule/speakAs page-type: web-api-instance-property browser-compat: api.CSSCounterStyleRule.speakAs --- {{DefaultAPISidebar("CSS Counter Styles")}} The **`speakAs`** property of the {{domxref("CSSCounterStyleRule")}} interface gets and sets the value of the {{cssxref("@counter-style/speak-as","speak-as")}} descriptor. If the descriptor does not have a value set, this attribute returns an empty string. ## Value A string ## Examples The following example shows a {{cssxref("@counter-style")}} rule. In JavaScript, `myRules[0]` is this `@counter-style` rule, returning `speakAs` gives us the value "bullets". ```css @counter-style box-corner { system: fixed; symbols: ◰ ◳ ◲ ◱; suffix: ": "; speak-as: bullets; } ``` ```js let myRules = document.styleSheets[0].cssRules; console.log(myRules[0].speakAs); // "bullets" ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/csscounterstylerule
data/mdn-content/files/en-us/web/api/csscounterstylerule/additivesymbols/index.md
--- title: "CSSCounterStyleRule: additiveSymbols property" short-title: additiveSymbols slug: Web/API/CSSCounterStyleRule/additiveSymbols page-type: web-api-instance-property browser-compat: api.CSSCounterStyleRule.additiveSymbols --- {{DefaultAPISidebar("CSS Counter Styles")}} The **`additiveSymbols`** property of the {{domxref("CSSCounterStyleRule")}} interface gets and sets the value of the {{cssxref("@counter-style/additive-symbols","additive-symbols")}} descriptor. If the descriptor does not have a value set, this attribute returns an empty string. ## Value A string. ## Examples The following example shows a {{cssxref("@counter-style")}} rule. In JavaScript, `myRules[0]` is this `@counter-style` rule, returning `additiveSymbols` gives us the value " V 5, IV 4, I 1". ```css @counter-style additive-symbols-example { system: additive; additive-symbols: V 5, IV 4, I 1; } ``` ```js let myRules = document.styleSheets[0].cssRules; console.log(myRules[0].additiveSymbols); // " V 5, IV 4, I 1" ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/csscounterstylerule
data/mdn-content/files/en-us/web/api/csscounterstylerule/negative/index.md
--- title: "CSSCounterStyleRule: negative property" short-title: negative slug: Web/API/CSSCounterStyleRule/negative page-type: web-api-instance-property browser-compat: api.CSSCounterStyleRule.negative --- {{DefaultAPISidebar("CSS Counter Styles")}} The **`negative`** property of the {{domxref("CSSCounterStyleRule")}} interface gets and sets the value of the {{cssxref("@counter-style/negative","negative")}} descriptor. If the descriptor does not have a value set, this attribute returns an empty string. ## Value A string ## Examples The following example shows a {{cssxref("@counter-style")}} rule. In JavaScript, `myRules[0]` is this `@counter-style` rule, returning `negative` gives us the value "-". ```css @counter-style neg { system: numeric; symbols: "0" "1" "2" "3" "4" "5" "6" "7" "8" "9"; negative: "-"; } ``` ```js let myRules = document.styleSheets[0].cssRules; console.log(myRules[0].negative); // "-" ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0