diff --git a/files/en-us/web/api/css_painting_api/guide/index.md b/files/en-us/web/api/css_painting_api/guide/index.md index 51f34227308ad91..edd127020a58918 100644 --- a/files/en-us/web/api/css_painting_api/guide/index.md +++ b/files/en-us/web/api/css_painting_api/guide/index.md @@ -5,42 +5,43 @@ page-type: guide --- {{DefaultAPISidebar("CSS Painting API")}} -The [CSS Paint API](/en-US/docs/Web/API/CSS_Painting_API) is designed to enable developers to programmatically define images which can then be used anywhere a CSS image can be invoked, such as CSS [`background-image`](/en-US/docs/Web/CSS/background-image), [`border-image`](/en-US/docs/Web/CSS/border-image-source), [`mask-image`](/en-US/docs/Web/CSS/mask-image), etc. + +The [CSS Paint API](/en-US/docs/Web/API/CSS_Painting_API) is designed to enable developers to programmatically define images which can then be used anywhere a CSS image can be invoked, such as CSS {{cssxref("background-image")}}, {{cssxref("border-image")}}, {{cssxref("mask-image")}}, etc. To programmatically create an image used by a CSS stylesheet we need to work through a few steps: -1. Define a paint worklet using the [`registerPaint()`](/en-US/docs/Web/API/PaintWorkletGlobalScope/registerPaint) function +1. Define a paint worklet using the {{domxref('PaintWorkletGlobalScope.registerPaint', 'registerPaint()')}} function 2. Register the worklet -3. Include the `{{cssxref("image/paint","paint()")}}` CSS function +3. Include the {{cssxref('image/paint', 'paint()')}} CSS function To elaborate over these steps, we're going to start by creating a half-highlight background, like on this header: ![Text reading 'My Cool Header' with a solid yellow background image block on the bottom left two thirds of the header](mycoolheader.png) > [!NOTE] -> The complete source for all the examples in this article can be found at [https://github.com/mdn/dom-examples/tree/main/css-painting](https://github.com/mdn/dom-examples/tree/main/css-painting), and the examples are running live at [https://mdn.github.io/dom-examples/css-painting/](https://mdn.github.io/dom-examples/css-painting/). +> See [CSS Painting API Example](https://mdn.github.io/dom-examples/css-painting/) for a full working demo (see the full [source code](https://github.com/mdn/dom-examples/tree/main/css-painting) also). ## CSS paint worklet -In an external script file, we employ the [`registerPaint()`](/en-US/docs/Web/API/PaintWorkletGlobalScope/registerPaint) function to name our [CSS Paint worklet](/en-US/docs/Web/API/Worklet). It takes two parameters. The first is the name we give the worklet — this is the name we will use in our CSS as the parameter of the `paint()` function when we want to apply this styling to an element. The second parameter is the class that does all the magic, defining the context options and what to paint to the two-dimensional canvas that will be our image. +In an external script file, we employ the {{domxref('PaintWorkletGlobalScope.registerPaint', 'registerPaint()')}} function to name our [CSS Paint worklet](/en-US/docs/Web/API/Worklet). It takes two parameters. The first is the name we give the worklet — this is the name we will use in our CSS as the parameter of the `paint()` function when we want to apply this styling to an element. The second parameter is the class that does all the magic, defining the context options and what to paint to the two-dimensional canvas that will be our image. ```js registerPaint( "headerHighlight", class { /* - define if alpha transparency is allowed alpha - is set to true by default. If set to false, all - colors used on the canvas will be fully opaque - */ + * define if alpha transparency is allowed alpha + * is set to true by default. If set to false, all + * colors used on the canvas will be fully opaque + */ static get contextOptions() { return { alpha: true }; } /* - ctx is the 2D drawing context - a subset of the HTML Canvas API. - */ + * ctx is the 2D drawing context + * a subset of the HTML Canvas API. + */ paint(ctx) { ctx.fillStyle = "hsl(55 90% 60% / 100%)"; ctx.fillRect(0, 15, 200, 20); /* order: x, y, w, h */ @@ -55,17 +56,17 @@ We have then used the `paint()` function to paint to our canvas. A `paint()` function can take three arguments. Here we have provided one argument: the rendering context (we'll look at more in due course), often referred to by the variable name `ctx`. The 2D Rendering Context is a subset of the [HTML Canvas API](/en-US/docs/Web/API/Canvas_API); the version available to Houdini (called the `PaintRenderingContext2D`) is a further subset containing most of the features available in the full Canvas API with the [exception](https://drafts.css-houdini.org/css-paint-api-1/#2d-rendering-context) of the `CanvasImageData`, `CanvasUserInterface`, `CanvasText`, and `CanvasTextDrawingStyles` APIs. -We define the [`fillStyle`](/en-US/docs/Web/API/CanvasRenderingContext2D/fillStyle) as being `hsl(55 90% 60% / 100%)`, which is a shade of yellow, and then call `fillRect()` to create a rectangle of that color. The [`fillRect()`](/en-US/docs/Web/API/CanvasRenderingContext2D/fillRect) parameters are, in order, x-axis origin, y-axis origin, width, and height. `fillRect(0, 15, 200, 20)` results in the creation of a rectangle that is 200 units wide by 20 units tall, positioned 0 units from the left and 15 units from the top of the content box. +We define the {{domxref('CanvasRenderingContext2D.fillStyle', 'fillStyle')}} as being `hsl(55 90% 60% / 100%)`, which is a shade of yellow, and then call `fillRect()` to create a rectangle of that color. The {{domxref('CanvasRenderingContext2D.fillRect', 'fillRect()')}} parameters are, in order, x-axis origin, y-axis origin, width, and height. `fillRect(0, 15, 200, 20)` results in the creation of a rectangle that is 200 units wide by 20 units tall, positioned 0 units from the left and 15 units from the top of the content box. -We can use the CSS [`background-size`](/en-US/docs/Web/CSS/background-size) and [`background-position`](/en-US/docs/Web/CSS/background-position) properties to re-size or relocate this background image, but this is the default size and placement of the yellow box we created in our paint worklet. +We can use the CSS {{cssxref("background-size")}} and {{cssxref("background-position")}} properties to re-size or relocate this background image, but this is the default size and placement of the yellow box we created in our paint worklet. -We tried to keep the example simple. For more options, look at the [canvas documentation](/en-US/docs/Web/HTML/Element/canvas). We also add a little bit of complexity later in this tutorial. +We tried to keep the example simple. For more options, look at the {{HTMLElement("canvas")}} documentation. We also add a little bit of complexity later in this tutorial. ## Registering the worklet -To use the paint worklet, we need to register it using [`addModule()`](/en-US/docs/Web/API/Worklet/addModule) and include it in our CSS, ensuring the CSS selector matches a DOM node in our HTML +To use the paint worklet, we need to register it using {{domxref('Worklet.addModule', 'addModule()')}} and include it in our CSS, ensuring the CSS selector matches a DOM node in our HTML -The setup and design of our paint worklet took place in the external script shown above. We need to register that [worklet](/en-US/docs/Web/API/Worklet) from our main script. +The setup and design of our paint worklet took place in the external script shown above. We need to register that {{domxref('worklet')}} from our main script. ```js CSS.paintWorklet.addModule("nameOfPaintWorkletFile.js"); @@ -126,9 +127,9 @@ registerPaint( } /* - ctx is the 2D drawing context - size is the paintSize, the dimensions (height and width) of the box being painted - */ + * ctx is the 2D drawing context + * size is the paintSize, the dimensions (height and width) of the box being painted + */ paint(ctx, size) { ctx.fillStyle = "hsl(55 90% 60% / 100%)"; ctx.fillRect(0, size.height / 3, size.width * 0.4, size.height * 0.6); @@ -206,7 +207,7 @@ registerPaint( ); ``` -The three parameters of the `paint()` function include the drawing context, paint size and properties. To be able to access properties, we include the static `inputProperties()` method, which provides live access to CSS properties, including regular properties and [custom properties](/en-US/docs/Web/CSS/CSS_cascading_variables), and returns an {{jsxref("Array", "array")}} of property names. We'll take a look at `inputArguments` in the last section. +The three parameters of the `paint()` function include the drawing context, paint size and properties. To be able to access properties, we include the static `inputProperties()` method, which provides live access to CSS properties, including regular properties and [custom properties](/en-US/docs/Web/CSS/CSS_cascading_variables), and returns an {{jsxref("Array", "array", "", 1)}} of property names. We'll take a look at `inputArguments` in the last section. Let's create a list of items with a background image that rotates between three different colors and three widths. @@ -227,20 +228,19 @@ registerPaint( } /* - use this function to retrieve any custom properties (or regular properties, such as 'height') - defined for the element, return them in the specified array - */ + * use this function to retrieve any custom properties (or regular properties, such as 'height') + * defined for the element, return them in the specified array + */ static get inputProperties() { return ["--boxColor", "--widthSubtractor"]; } paint(ctx, size, props) { /* - ctx -> drawing context - size -> paintSize: width and height - props -> properties: get() method - */ - + * ctx -> drawing context + * size -> paintSize: width and height + * props -> properties: get() method + */ ctx.fillStyle = props.get("--boxColor"); ctx.fillRect( 0, @@ -414,7 +414,7 @@ The result looks like this: {{EmbedGHLiveSample("dom-examples/css-painting/fancy-header-highlight/", 200, 200)}} -While you can't edit the worklet itself, you can play around with the CSS and HTML. Maybe try [`float`](/en-US/docs/Web/CSS/float) and [`clear`](/en-US/docs/Web/CSS/clear) on the headers? +While you can't edit the worklet itself, you can play around with the CSS and HTML. Maybe try {{cssxref("float")}} and {{cssxref("clear")}} on the headers? You could try making the background images above without the CSS Paint API. It is doable, but you would have to declare a different, fairly complex linear gradient for each different color you wanted to create. With the CSS Paint API, one worklet can be reused, with different colors passed in this case. @@ -472,7 +472,7 @@ When we `get` our list of argument values, we can ask specifically for a `']; } ``` -In this case, we specifically requested the `` attribute. The first element in the returned array will be a [`CSSUnparsedValue`](/en-US/docs/Web/API/CSSUnparsedValue). The second will be a [`CSSStyleValue`](/en-US/docs/Web/API/CSSStyleValue). +In this case, we specifically requested the `` attribute. The first element in the returned array will be a {{domxref('CSSUnparsedValue')}}. The second will be a {{domxref('CSSStyleValue')}}. If the custom argument is a CSS value, for instance a unit, we can invoke Typed OM CSSStyleValue class (and sub classes) by using the value type keyword when we retrieve it in the `registerPaint()` function. diff --git a/files/en-us/web/api/css_painting_api/index.md b/files/en-us/web/api/css_painting_api/index.md index df2215bee1b3536..ad923ae29fca5e1 100644 --- a/files/en-us/web/api/css_painting_api/index.md +++ b/files/en-us/web/api/css_painting_api/index.md @@ -13,7 +13,7 @@ The CSS Painting API — part of the [CSS Houdini](/en-US/docs/Web/API/Houdini_A ## Concepts and usage -Essentially, the CSS Painting API contains functionality allowing developers to create custom values for {{cssxref('image/paint', 'paint()')}}, a CSS [``](/en-US/docs/Web/CSS/image) function. You can then apply these values to properties like {{cssxref("background-image")}} to set complex custom backgrounds on an element. +Essentially, the CSS Painting API contains functionality allowing developers to create custom values for {{cssxref('image/paint', 'paint()')}}, a CSS {{cssxref('<image>')}} function. You can then apply these values to properties like {{cssxref('background-image')}} to set complex custom backgrounds on an element. For example: @@ -30,7 +30,7 @@ The API defines a {{domxref('worklet')}} that can be used to programmatically ge - {{domxref('PaintWorkletGlobalScope')}} - : The global execution context of the paint worklet. - {{domxref('PaintRenderingContext2D')}} - - : Implements a subset of the [`CanvasRenderingContext2D`](/en-US/docs/Web/API/CanvasRenderingContext2D) API. It has an output bitmap that is the size of the object it is rendering to. + - : The rendering context for drawing to the bitmap for the CSS Painting API. - {{domxref('PaintSize')}} - : Returns the read-only values of the output bitmap's width and height. @@ -131,7 +131,7 @@ li:nth-of-type(3n + 1) { #### JavaScript The setup and logic of the paint worklet is in the external script. -To register the worklet, we need to call [`addModule()`](/en-US/docs/Web/API/Worklet/addModule) from our main script: +To register the worklet, we need to call {{domxref('Worklet.addModule', 'addModule()')}} from our main script: ```js live-sample___example-boxbg CSS.paintWorklet.addModule( diff --git a/files/en-us/web/api/paintrenderingcontext2d/index.md b/files/en-us/web/api/paintrenderingcontext2d/index.md new file mode 100644 index 000000000000000..810c5c2da8e9845 --- /dev/null +++ b/files/en-us/web/api/paintrenderingcontext2d/index.md @@ -0,0 +1,186 @@ +--- +title: PaintRenderingContext2D +slug: Web/API/PaintRenderingContext2D +page-type: web-api-interface +status: + - experimental +browser-compat: api.PaintRenderingContext2D +--- + +{{APIRef("CSS Painting API")}}{{SeeCompatTable}} + +The **`PaintRenderingContext2D`** interface of the [CSS Painting API](/en-US/docs/Web/API/CSS_Painting_API) is the rendering context for drawing to the bitmap for the [CSS Painting API](/en-US/docs/Web/API/CSS_Painting_API). It implements a subset of the {{domxref("CanvasRenderingContext2D")}} API. + +The interface is only available in {{domxref("CanvasRenderingContext2D", "paint worklet global scope", "", 1)}}. + +## Instance properties and methods + +_All PaintRenderingContext2D's properties and methods have the same usage as in `CanvasRenderingContext2D`_ + +### Context + +- {{domxref("CanvasRenderingContext2D.isContextLost()")}} + - : Returns `true` if the rendering context was lost. + +### State + +- {{domxref("CanvasRenderingContext2D.save()")}} + - : Saves the current drawing style state using a stack so you can revert any change you make to it using `restore()`. +- {{domxref("CanvasRenderingContext2D.restore()")}} + - : Restores the drawing style state to the last element on the 'state stack' saved by `save()`. +- {{domxref("CanvasRenderingContext2D.reset()")}} + - : Resets the current drawing style state to the default values. + +### Transformations + +- {{domxref("CanvasRenderingContext2D.getTransform()")}} + - : Retrieves the current transformation matrix being applied to the context. +- {{domxref("CanvasRenderingContext2D.rotate()")}} + - : Adds a rotation to the transformation matrix. The angle argument represents a clockwise rotation angle and is expressed in radians. +- {{domxref("CanvasRenderingContext2D.scale()")}} + - : Adds a scaling transformation to the canvas units by x horizontally and by y vertically. +- {{domxref("CanvasRenderingContext2D.translate()")}} + - : Adds a translation transformation by moving the canvas and its origin x horizontally and y vertically on the grid. +- {{domxref("CanvasRenderingContext2D.transform()")}} + - : Multiplies the current transformation matrix with the matrix described by its arguments. +- {{domxref("CanvasRenderingContext2D.setTransform()")}} + - : Resets the current transform to the identity matrix, and then invokes the `transform()` method with the same arguments. +- {{domxref("CanvasRenderingContext2D.resetTransform()")}} + - : Resets the current transform by the identity matrix. + +### Compositing + +- {{domxref("CanvasRenderingContext2D.globalAlpha")}} + - : Alpha value that is applied to shapes and images before they are composited onto the canvas. Default `1.0` (opaque). +- {{domxref("CanvasRenderingContext2D.globalCompositeOperation")}} + - : With `globalAlpha` applied this sets how shapes and images are drawn onto the existing bitmap. + +### Image smoothing + +- {{domxref("CanvasRenderingContext2D.imageSmoothingEnabled")}} + - : Image smoothing mode; if disabled, images will not be smoothed if scaled. +- {{domxref("CanvasRenderingContext2D.imageSmoothingQuality")}} + - : Allows you to set the quality of image smoothing. + +### Fill and stroke styles + +- {{domxref("CanvasRenderingContext2D.fillStyle")}} + - : Color or style to use inside shapes. Default `#000` (black). +- {{domxref("CanvasRenderingContext2D.strokeStyle")}} + - : Color or style to use for the lines around shapes. Default `#000` (black). + +### Gradients and patterns + +- {{domxref("CanvasRenderingContext2D.createConicGradient()")}} + - : Creates a conic gradient around a point given by coordinates represented by the parameters. +- {{domxref("CanvasRenderingContext2D.createLinearGradient()")}} + - : Creates a linear gradient along the line given by the coordinates represented by the parameters. +- {{domxref("CanvasRenderingContext2D.createRadialGradient()")}} + - : Creates a radial gradient given by the coordinates of the two circles represented by the parameters. +- {{domxref("CanvasRenderingContext2D.createPattern()")}} + - : Creates a pattern using the specified image. It repeats the source in the directions specified by the repetition argument. This method returns a {{domxref("CanvasPattern")}}. + +### Shadows + +- {{domxref("CanvasRenderingContext2D.shadowBlur")}} + - : Specifies the blurring effect. Default: `0`. +- {{domxref("CanvasRenderingContext2D.shadowColor")}} + - : Color of the shadow. Default: fully-transparent black. +- {{domxref("CanvasRenderingContext2D.shadowOffsetX")}} + - : Horizontal distance the shadow will be offset. Default: `0`. +- {{domxref("CanvasRenderingContext2D.shadowOffsetY")}} + - : Vertical distance the shadow will be offset. Default: `0`. + +### Drawing rectangles + +- {{domxref("CanvasRenderingContext2D.clearRect()")}} + - : Sets all pixels in the rectangle defined by starting point _(x, y)_ and size _(width, height)_ to transparent black, erasing any previously drawn content. +- {{domxref("CanvasRenderingContext2D.fillRect()")}} + - : Draws a filled rectangle at _(x, y)_ position whose size is determined by _width_ and _height_. +- {{domxref("CanvasRenderingContext2D.strokeRect()")}} + - : Paints a rectangle which has a starting point at _(x, y)_ and has a _w_ width and an _h_ height onto the canvas, using the current stroke style. + +### Drawing paths + +- {{domxref("CanvasRenderingContext2D.beginPath()")}} + - : Starts a new path by emptying the list of sub-paths. Call this method when you want to create a new path. +- {{domxref("CanvasRenderingContext2D.fill()")}} + - : Fills the current sub-paths with the current fill style. +- {{domxref("CanvasRenderingContext2D.stroke()")}} + - : Strokes the current sub-paths with the current stroke style. +- {{domxref("CanvasRenderingContext2D.clip()")}} + - : Creates a clipping path from the current sub-paths. Everything drawn after `clip()` is called appears inside the clipping path only. For an example, see [Clipping paths](/en-US/docs/Web/API/Canvas_API/Tutorial/Compositing) in the Canvas tutorial. +- {{domxref("CanvasRenderingContext2D.isPointInPath()")}} + - : Reports whether or not the specified point is contained in the current path. +- {{domxref("CanvasRenderingContext2D.isPointInStroke()")}} + - : Reports whether or not the specified point is inside the area contained by the stroking of a path. + +### Drawing images + +- {{domxref("CanvasRenderingContext2D.drawImage()")}} + - : Draws the specified image. This method is available in multiple formats, providing a great deal of flexibility in its use. + +### Line styles + +The following methods and properties control how lines are drawn. + +- {{domxref("CanvasRenderingContext2D.lineWidth")}} + - : Width of lines. Default `1.0`. +- {{domxref("CanvasRenderingContext2D.lineCap")}} + - : Type of endings on the end of lines. Possible values: `butt` (default), `round`, `square`. +- {{domxref("CanvasRenderingContext2D.lineJoin")}} + - : Defines the type of corners where two lines meet. Possible values: `round`, `bevel`, `miter` (default). +- {{domxref("CanvasRenderingContext2D.miterLimit")}} + - : Miter limit ratio. Default `10`. +- {{domxref("CanvasRenderingContext2D.getLineDash()")}} + - : Returns the current line dash pattern array containing an even number of non-negative numbers. +- {{domxref("CanvasRenderingContext2D.setLineDash()")}} + - : Sets the current line dash pattern. +- {{domxref("CanvasRenderingContext2D.lineDashOffset")}} + - : Specifies where to start a dash array on a line. + +### Paths + +- {{domxref("CanvasRenderingContext2D.closePath()")}} + - : Causes the point of the pen to move back to the start of the current sub-path. It tries to draw a straight line from the current point to the start. If the shape has already been closed or has only one point, this function does nothing. +- {{domxref("CanvasRenderingContext2D.moveTo()")}} + - : Moves the starting point of a new sub-path to the (x, y) coordinates. +- {{domxref("CanvasRenderingContext2D.lineTo()")}} + - : Connects the last point in the current sub-path to the specified (x, y) coordinates with a straight line. +- {{domxref("CanvasRenderingContext2D.bezierCurveTo()")}} + - : Adds a cubic Bézier curve to the current path. +- {{domxref("CanvasRenderingContext2D.quadraticCurveTo()")}} + - : Adds a quadratic Bézier curve to the current path. +- {{domxref("CanvasRenderingContext2D.arc()")}} + - : Adds a circular arc to the current path. +- {{domxref("CanvasRenderingContext2D.arcTo()")}} + - : Adds an arc to the current path with the given control points and radius, connected to the previous point by a straight line. +- {{domxref("CanvasRenderingContext2D.ellipse()")}} + - : Adds an elliptical arc to the current path. +- {{domxref("CanvasRenderingContext2D.rect()")}} + - : Creates a path for a rectangle at position (x, y) with a size that is determined by _width_ and _height_. +- {{domxref("CanvasRenderingContext2D.roundRect()")}} + - : Creates a path for a rectangle with rounded corners at position (x, y) with a size that is determined by _width_ and _height_ and radii determined by _radii_. + +### Filters + +- {{domxref("CanvasRenderingContext2D.filter")}} {{Non-standard_Inline}} + - : Applies a CSS or SVG filter to the canvas, e.g., to change its brightness or blurriness. + +## Examples + +See full examples at [CSS Painting API](/en-US/docs/Web/API/CSS_Painting_API). + +## Specifications + +{{Specifications}} + +## Browser compatibility + +{{Compat}} + +## See also + +- [Using the CSS Painting API](/en-US/docs/Web/API/CSS_Painting_API/Guide) +- [CSS Painting API](/en-US/docs/Web/API/CSS_Painting_API) +- [Houdini APIs](/en-US/docs/Web/API/Houdini_APIs) diff --git a/files/en-us/web/api/paintworkletglobalscope/index.md b/files/en-us/web/api/paintworkletglobalscope/index.md index 23e8156de0a2a94..94b27907328245f 100644 --- a/files/en-us/web/api/paintworkletglobalscope/index.md +++ b/files/en-us/web/api/paintworkletglobalscope/index.md @@ -13,7 +13,7 @@ The **`PaintWorkletGlobalScope`** interface of the [CSS Painting API](/en-US/doc ## Privacy concerns -To avoid leaking visited links, this feature is currently disabled in Chrome-based browsers for {{HTMLElement("a")}} elements with an [`href`](/en-US/docs/Web/HTML/Element/a#href) attribute, and for children of such elements. For details, see the following: +To avoid leaking visited links, this feature is currently disabled in Chrome-based browsers for {{HTMLElement("a")}} elements with an `href` attribute, and for children of such elements. For details, see the following: - The CSS Painting API [Privacy Considerations section](https://drafts.css-houdini.org/css-paint-api/#privacy-considerations) - The CSS Painting API spec issue ["CSS Paint API leaks browsing history"](https://github.com/w3c/css-houdini-drafts/issues/791) @@ -109,5 +109,6 @@ You can also use the {{cssxref('@supports')}} at-rule. ## See also +- [Using the CSS Painting API](/en-US/docs/Web/API/CSS_Painting_API/Guide) - [CSS Painting API](/en-US/docs/Web/API/CSS_Painting_API) - [Houdini APIs](/en-US/docs/Web/API/Houdini_APIs)