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 |
浏览器兼容性
加载中…