PaintWorkletGlobalScope: registerPaint() 方法
PaintWorkletGlobalScope 介面的 registerPaint() 方法用於註冊一個類,該類可以以程式設計方式生成 CSS 屬性期望的檔案影像。
語法
js
registerPaint(name, classRef)
引數
返回值
無(undefined)。
異常
TypeError-
當引數之一無效或缺失時丟擲。
InvalidModificationErrorDOMException-
當具有指定名稱的工作let已存在時丟擲。
示例
以下展示瞭如何註冊一個示例工作let模組。這應該放在一個單獨的 JS 檔案中。請注意,registerPaint() 是在沒有 PaintWorkletGlobalScope 引用的情況下呼叫的。該檔案本身是透過 CSS.paintWorklet.addModule() 載入的(在此處記錄在 PaintWorklet 的父類 Worklet.addModule() 中)。
js
/* checkboardWorklet.js */
class CheckerboardPainter {
paint(ctx, geom, properties) {
// Use `ctx` as if it was a normal canvas
const colors = ["red", "green", "blue"];
const size = 32;
for (let y = 0; y < geom.height / size; y++) {
for (let x = 0; x < geom.width / size; x++) {
const color = colors[(x + y) % colors.length];
ctx.beginPath();
ctx.fillStyle = color;
ctx.rect(x * size, y * size, size, size);
ctx.fill();
}
}
}
}
// Register our class under a specific name
registerPaint("checkerboard", CheckerboardPainter);
使用 paintworklet 的第一步是使用 registerPaint() 函式定義 paint worklet,如上所示。要使用它,你需要使用 CSS.paintWorklet.addModule() 方法進行註冊。
js
CSS.paintWorklet.addModule("checkboardWorklet.js");
然後,你可以在 CSS 中任何接受 <image> 值的地方使用 paint() CSS 函式。
css
li {
background-image: paint(checkerboard);
}
規範
| 規範 |
|---|
| CSS Painting API Level 1 # dom-paintworkletglobalscope-registerpaint |
瀏覽器相容性
載入中…