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 |
瀏覽器相容性
載入中…