Using the CSS Painting API - Web APIs 编辑
The CSS Paint 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
, border-image
, mask-image
, etc.
To programmatically create an image used by a CSS stylesheet we need to work through a few steps:
- Define a paint worklet using the
registerPaint()
function - Register the worklet
- Include the
CSS functionpaint()
To elaborate over these steps, we're going to start by creating a half-highlight background, like on this header:
CSS paint worklet
In an external script file, we employ the registerPaint()
function to name our CSS Paint 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.
registerPaint('headerHighlight', class {
/*
define if alphatransparency is allowed alpha
is set to true by default. If set to false, all
colours used on the canvas will be fully opaque
*/
static get contextOptions() {
return { alpha: true };
}
/*
ctx is the 2D drawing context
a subset of the HTML5 Canvas API.
*/
paint(ctx) {
ctx.fillStyle = 'hsla(55, 90%, 60%, 1.0)';
ctx.fillRect(0, 15, 200, 20); /* order: x, y, w, h */
}
});
In this class example we have defined a single context option with the contextOptions()
function: we returned a simple object stating alpha transparency is allowed.
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 refered to by the variable name ctx
. The 2D Rendering Context is a subset of the HTML5 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 of the CanvasImageData
, CanvasUserInterface
, CanvasText
, and CanvasTextDrawingStyles
APIs.
We define the fillStyle
as being hsla(55, 90%, 60%, 1.0)
, which is a shade of yellow, and then call fillRect()
to create a rectangle of that color. The 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
and 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. We also add a little bit of complexity later in this tutorial.
Using the paint worklet
To use the paint worklet, we need to register it using addModule()
and include it in our CSS, ensuring the CSS selector matches a DOM node in our HTML
Registering the worklet
The setup and design of our paint worklet took place in the external script shown above. We need to register that worklet from our main script.
CSS.paintWorklet.addModule('nameOfPaintWorkletFile.js');
This can be done using the paint worklet's addModule()
method in a <script>
within the main HTML or in an external JavaScript file linked to from the document.
In our example, the paintworklet is stored on Github.
CSS.paintWorklet.addModule('https://mdn.github.io/houdini-examples/cssPaint/intro/01partOne/header-highlight.js');
Reference the paint worklet in CSS
Once we have a registered paint worklet, we can use it in CSS. Employ the CSS paint()
function like we would any other <image>
type, using the same string identifier we used in the paintworklet's registerPaint()
function.
.fancy {
background-image: paint(headerHighlight);
}
Putting it together
We can then add the fancy class to any element on the page to add a yellow box as a background:
<h1 class="fancy">My Cool Header</h1>
The following example will look like the image above in browsers supporting the CSS Painting API.
While you can't play with the worklet's script, you can alter the background-size
and background-position
to change the size and location of the background image.
PaintSize
In the example above, we created a 20x200 unit box, painted 15 units from the top of the element it is the same regardless of the size of the element. If the text is small, the yellow box looks like a huge underline. If the text is huge, the box might look like an bar above the first three letters. It would be better if the background image was relative to the size of the element — we can use the element's paintSize
property to ensure the background image is proportional to the size of the element's box model size.
In the above image, the background proportional to the size of the element. The 3rd example has width: 50%
; set on the block level element, making the element narrower and therefore the background image narrower.
The code to do this looks like so:
registerPaint('headerHighlight', class {
static get contextOptions() {
return { alpha: true };
}
/*
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 = 'hsla(55, 90%, 60%, 1.0)';
ctx.fillRect( 0, size.height / 3, size.width * 0.4, size.height * 0.6 );
}
});
This code example has two differences from our first example:
- We've included a second argument, which is the paint size.
- We've changed the dimensions and positioning of our rectangle to be relative to the size of the element box rather than absolute values.
We can pass the second parameter into the paint()
function to give us access to the width and the height of the element, via .width
and .height
properties.
Our header now has a highlight that changes according to it's size.
CSS.paintWorklet.addModule('https://mdn.github.io/houdini-examples/cssPaint/intro/02partTwo/header-highlight.js');
.fancy {
background-image: paint(headerHighlight);
}
.half {
width: 50%;
}
<h1 class="fancy">Largest Header</h1>
<h6 class="fancy">Smallest Header</h6>
<h3 class="fancy half">50% width header</h3>
While you can't play with the worklet's script, you can alter the element's font-size
and width
to change the size of the background image.
In browsers that support the CSS Paint API, the example below should appear like the image above.
Custom properties
In addition to accessing the size of the element, the worklet can also have access to CSS custom properties and regular CSS properties.
registerPaint('cssPaintFunctionName', class {
static get inputProperties() { return ['PropertyName1', '--customPropertyName2']; }
static get inputArguments() { return ['<color>']; }
static get contextOptions() { return {alpha: true}; }
paint(drawingContext, elementSize, styleMap) {
// Paint code goes here.
}
});
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, and returns an array
of property names. We'll take a look at inputArguments
in the last section.
Example
Let's create a list of items with a background image that rotates between three different colors and three widths.
In our CSS, we provide a different color and a width subtractor for the background box we've created via the --boxColor
and --widthSubtractor
custom properties.
li {
background-image: paint(boxbg);
--boxColor: hsla(55, 90%, 60%, 1.0);
}
li:nth-of-type(3n) {
--boxColor: hsla(155, 90%, 60%, 1.0);
--widthSubtractor: 20;
}
li:nth-of-type(3n+1) {
--boxColor: hsla(255, 90%, 60%, 1.0);
--widthSubtractor: 40;
}
In our worklet, we can reference those custom properties.
registerPaint('boxbg', class {
static get contextOptions() { return {alpha: true}; }
/*
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.fillStyle = props.get('--boxColor');
ctx.fillRect(0, size.height/3, size.width*0.4 - props.get('--widthSubtractor'), size.height*0.6);
}
});
We used the inputProperties()
method in the registerPaint()
class to get the values of two custom properties set on an element that has boxbg
applied to it and then used those within our paint()
function. The inputProperties()
method can return all properties affecting the element, not just custom properties.
In our <script>
we register the worklet:
CSS.paintWorklet.addModule('https://mdn.github.io/houdini-examples/cssPaint/intro/worklet/boxbg.js');
While you can't play with the worklet's script, you can alter the custom property values to change the colors and width of the background image.
Adding complexity
The above examples might not seem very exciting, as you could recreate them in a few different ways with existing CSS properties, e.g. by positioning some decorative generated content with ::before,
or including background: linear-gradient(yellow, yellow) 0 15px / 200px 20px no-repeat;
What makes the CSS Painting API so interesting and powerful is that you can create complex images, passing variables, that automatically resize.
Let's take a look at a more complex paint example.
registerPaint('headerHighlight', class {
static get inputProperties() { return ['--highColour']; }
static get contextOptions() { return {alpha: true}; }
paint(ctx, size, props) {
/* set where to start the highlight & dimensions */
const x = 0;
const y = size.height * 0.3;
const blockWidth = size.width * 0.33;
const highlightHeight = size.height * 0.85;
const color = props.get('--highColour');
ctx.fillStyle = color;
ctx.beginPath();
ctx.moveTo( x, y );
ctx.lineTo( blockWidth, y );
ctx.lineTo( blockWidth + highlightHeight, highlightHeight );
ctx.lineTo( x, highlightHeight );
ctx.lineTo( x, y );
ctx.closePath();
ctx.fill();
/* create the dashes */
for (let i = 0; i < 4; i++) {
let start = i * 2;
ctx.beginPath();
ctx.moveTo( (blockWidth) + (start * 10) + 10, y );
ctx.lineTo( (blockWidth) + (start * 10) + 20, y );
ctx.lineTo( (blockWidth) + (start * 10) + 20 + (highlightHeight), highlightHeight );
ctx.lineTo( (blockWidth) + (start * 10) + 10 + (highlightHeight), highlightHeight );
ctx.lineTo( (blockWidth) + (start * 10) + 10, y );
ctx.closePath();
ctx.fill();
}
} // paint
});
We can then create a little HTML that will accept this image as backgrounds:
<h1 class="fancy">Largest Header</h1>
<h3 class="fancy">Medium size header</h3>
<h6 class="fancy">Smallest Header</h6>
We give each header a different value for the --highColour
custom property
.fancy {
background-image: paint(headerHighlight);
}
h1 { --highColour: hsla(155, 90%, 60%, 0.7); }
h3 { --highColour: hsla(255, 90%, 60%, 0.5); }
h6 { --highColour: hsla(355, 90%, 60%, 0.3); }
And we register our worklet
CSS.paintWorklet.addModule('https://mdn.github.io/houdini-examples/cssPaint/intro/03partThree/header-highlight.js');
While you can't edit the worklet itself, you can play around with the CSS and HTML. Maybe try float
and 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 re-used, with different colors passed in this case.
Passing parameters
With the CSS Paint API, we not only have access to custom properties and regular properties, but we can pass custom arguments to the paint()
function as well.
We can add these extra arguments when we call the function in the CSS. Let's say we want to sometimes stroke our background instead of fill it — let's pass in an extra argument for this occasion.
li {
background-image: paint(hollowHighlights, stroke);
}
Now we can use the inputArguments()
method in the registerPaint()
class to access the custom argument we have added to our paint()
function.
static get inputArguments() { return ['*']; }
We then have access to that argument.
paint(ctx, size, props, args) {
// use our custom arguments
const hasStroke = args[0].toString();
// if stroke arg is 'stroke', don't fill
if (hasStroke === 'stroke') {
ctx.fillStyle = 'transparent';
ctx.strokeStyle = colour;
}
...
}
We can pass more than one argument.
li {
background-image: paint(hollowHighlights, stroke, 10px);
}
We can also specify that we want a particular type of argument. When we get
our list of argument values, we ask specifically for a <length>
unit.
static get inputArguments() { return ['*', '<length>']; }
In this case, we specifically requested the <length>
attribute. The first element in the returned array will be a CSSUnparsedValue
. The second will be a 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.
Let's say we add a second argument with how many pixels wide we want the stroke to be:
li {
background-image: paint(hollowHighlights, stroke, 10px);
}
When we get
our list of argument values, we can ask specifically for a <length>
unit.
static get inputArguments() { return ['*', '<length>']; }
Now we can access the type and value properties, meaning we can get the number of pixels and a number type right out of the box. (Admittedly, ctx.lineWidth
takes a float as a value rather than a value with length units, but for example's sake...)
paint(ctx, size, props, args) {
const strokeWidth = args[1];
if (strokeWidth.unit === 'px') {
ctx.lineWidth = strokeWidth.value;
} else {
ctx.lineWidth = 1.0;
}
...
}
It's worth noting the difference between using custom properties to control different parts of this worklet and the arguments set out here. Custom properties (and in fact any properties on the style map) are global — they can be used elsewhere within our CSS (and JS).
You may for example have a --mainColor
, which will be useful for setting the color within a paint()
function, but can also be used to set colors elsewhere in your CSS. If you wanted to change it specifically for paint, it could prove difficult. This is where the custom argument feature comes in handy. Another way to think about it is that arguments are set to control what you are actually drawing, whereas properties are set to control styling.
Now we can really start to see the benefits of this API, if we can control a myriad of drawing parameters from our CSS through both custom properties and extra paint()
function arguments, then we can really start to build reusable and highly controllable styling functions.
registerPaint('hollowHighlights', class {
static get inputProperties() { return ['--boxColor']; }
// Input arguments that can be passed to the `paint` function
static get inputArguments() { return ['*','']; }
static get contextOptions() { return {alpha: true}; }
paint(ctx, size, props, args) {
// ctx -> drawing context
// size -> size of the box being painted
// props -> list of custom properties available to the element
// args -> list of arguments set when calling the paint() function in the css
// where to start the highlight & dimensions
const x = 0;
const y = size.height * 0.3;
const blockWidth = size.width * 0.33;
const blockHeight = size.height * 0.85;
// the values passed in the paint() function in the CSS
const colour = props.get( '--boxColor' );
const strokeType = args[0].toString();
const strokeWidth = parseInt(args[1]);
// set the stroke width
if ( strokeWidth ) {
ctx.lineWidth = strokeWidth;
} else {
ctx.lineWidth = 1.0;
}
// set the fill type
if ( strokeType === 'stroke' ) {
ctx.fillStyle = 'transparent';
ctx.strokeStyle = colour;
} else if ( strokeType === 'filled' ) {
ctx.fillStyle = colour;
ctx.strokeStyle = colour;
} else {
ctx.fillStyle = 'none';
ctx.strokeStyle = 'none';
}
// block
ctx.beginPath();
ctx.moveTo( x, y );
ctx.lineTo( blockWidth, y );
ctx.lineTo( blockWidth + blockHeight, blockHeight );
ctx.lineTo( x, blockHeight );
ctx.lineTo( x, y );
ctx.closePath();
ctx.fill();
ctx.stroke();
// dashes
for (let i = 0; i < 4; i++) {
let start = i * 2;
ctx.beginPath();
ctx.moveTo( blockWidth + (start * 10) + 10, y);
ctx.lineTo( blockWidth + (start * 10) + 20, y);
ctx.lineTo( blockWidth + (start * 10) + 20 + blockHeight, blockHeight);
ctx.lineTo( blockWidth + (start * 10) + 10 + blockHeight, blockHeight);
ctx.lineTo( blockWidth + (start * 10) + 10, y);
ctx.closePath();
ctx.fill();
ctx.stroke();
}
} // paint
});
We can set different colors, stroke widths, and pick whether the background image should be filled or hollow:
li {
--boxColor: hsla(155, 90%, 60%, 0.5);
background-image: paint(hollowHighlights, stroke, 5px);
}
li:nth-of-type(3n) {
--boxColor: hsla(255, 90%, 60%, 0.5);
background-image: paint(hollowHighlights, filled, 3px);
}
li:nth-of-type(3n+1) {
--boxColor: hsla(355, 90%, 60%, 0.5);
background-image: paint(hollowHighlights, stroke, 1px);
}
In our <script>
we register the worklet:
CSS.paintWorklet.addModule('https://mdn.github.io/houdini-examples/cssPaint/intro/worklets/hollow.js');
See also
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论