CSS Painting API
CSS Painting API — 作为 CSS Houdini API 系列的一部分 — 允许开发者编写 JavaScript 函数,直接绘制到元素的背景、边框或内容区域。
概念与用法
本质上,CSS Painting API 包含允许开发者为 CSS paint() 函数(一种 CSS <image> 函数)创建自定义值的功能。然后,你可以将这些值应用于 background-image 等属性,为元素设置复杂的自定义背景。
例如
aside {
background-image: paint(my-painted-image);
}
该 API 定义了一个 worklet,可用于以编程方式生成响应计算样式变化的图像。要了解有关此用法的更多信息,请参阅 使用 CSS Painting API。
接口
PaintWorkletGlobalScope-
paint worklet 的全局执行上下文。
PaintRenderingContext2D-
CSS Painting API 的渲染上下文,用于绘制到位图。
PaintSize-
表示作者应绘制的输出位图的大小。
示例
以下示例创建了一个列表项,其背景图像在三种不同的颜色和三种宽度之间旋转。在 支持的浏览器 中,您将看到类似下图的效果。

为了实现这一点,我们将定义两个自定义 CSS 属性:--box-color 和 --width-subtractor。
paint worklet
worklet 是一个外部 JavaScript 文件(在本例中我们将其命名为 boxbg.js),它定义了一个 paint worklet。使用 worklet,我们可以访问元素 CSS 属性(包括自定义属性)。
registerPaint(
"boxbg",
class {
static get contextOptions() {
return { alpha: true };
}
/*
Retrieve any custom properties (or regular properties,
such as 'height') defined for the element, and return
them as an array.
*/
static get inputProperties() {
return ["--box-color", "--width-subtractor"];
}
paint(ctx, size, props) {
/*
ctx -> drawing context
size -> paintSize: width and height
props -> properties: get() method
*/
ctx.fillStyle = props.get("--box-color");
ctx.fillRect(
0,
size.height / 3,
size.width * 0.4 - props.get("--width-subtractor"),
size.height * 0.6,
);
}
},
);
我们在 registerPaint() 类中使用了 inputProperties() 方法来获取应用于具有 boxbg 样式的元素的两个自定义属性的值,然后将这些值用于我们的 paint() 函数中。inputProperties() 方法可以返回所有影响元素的属性,而不仅仅是自定义属性。
使用 paint worklet
HTML
<ul>
<li>item 1</li>
<li>item 2</li>
<li>item 3</li>
<li>item 4</li>
<li>item 5</li>
<li>item 6</li>
<li>item 7</li>
<li>item 8</li>
<li>item 9</li>
<li>item 10</li>
<li>item N</li>
</ul>
CSS
在我们的 CSS 中,我们定义了 --box-color 和 --width-subtractor 自定义属性。
body {
font: 1.2em / 1.2 sans-serif;
}
li {
background-image: paint(boxbg);
--box-color: hsl(55 90% 60%);
}
li:nth-of-type(3n) {
--box-color: hsl(155 90% 60%);
--width-subtractor: 20;
}
li:nth-of-type(3n + 1) {
--box-color: hsl(255 90% 60%);
--width-subtractor: 40;
}
JavaScript
paint worklet 的设置和逻辑在外部脚本中。要注册 worklet,我们需要从主脚本调用 addModule()。
CSS.paintWorklet.addModule(
"https://mdn.github.io/houdini-examples/cssPaint/intro/worklets/boxbg.js",
);
在此示例中,worklet 托管在 https://mdn.github.io/,但您的 worklet 可能是一个相对资源,如下所示:
CSS.paintWorklet.addModule("boxbg.js");
结果
虽然您无法直接操作 worklet 的脚本,但您可以在 DevTools 中更改自定义属性值,以改变背景图像的颜色和宽度。
规范
| 规范 |
|---|
| CSS Painting API Level 1 # paintworkletglobalscope |
浏览器兼容性
加载中…