PaintWorkletGlobalScope:registerPaint() 方法

实验性: 这是一个 实验性技术
在生产环境中使用之前,请仔细查看 浏览器兼容性表

registerPaint() 方法是 PaintWorkletGlobalScope 接口的方法,用于注册一个类,以编程方式生成图像,其中 CSS 属性期望一个文件。

语法

js
registerPaint(name, classRef)

参数

name

要注册的工作线程类的名称。

classRef

实现工作线程类的引用。

返回值

无 (undefined)。

异常

TypeError

当某个参数无效或缺失时抛出。

InvalidModificationError DOMException

当已存在具有指定名称的工作线程时抛出。

示例

以下显示了注册示例工作线程模块。这应该在单独的 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() 方法注册它。

html
<script>
  CSS.paintWorklet.addModule("checkboardWorklet.js");
</script>

然后,您可以在 CSS 中任何 <image> 值有效的地方使用 paint() CSS 函数。

css
li {
  background-image: paint(checkerboard);
}

规范

规范
CSS 绘制 API 第 1 级
# dom-paintworkletglobalscope-registerpaint

浏览器兼容性

BCD 表仅在启用 JavaScript 的浏览器中加载。

另请参阅