大网数据广告活动
Web 标准与前端开发

PaintWorkletGlobalScope: registerPaint() method

· 52CE 我爱测

The **`registerPaint()`** method of the PaintWorkletGlobalScope interface registers a class to programmatically generate an image where a CSS property expects a file.

CSS Painting API

The registerPaint() method of the PaintWorkletGlobalScope interface registers a class to programmatically generate an image where a CSS property expects a file.

Syntax

registerPaint(name, classRef)

Parameters

  • name
    • : The name of the worklet class to register.
  • classRef
    • : A reference to the class that implements the worklet.

Return value

None (undefined).

Exceptions

  • TypeError
    • : Thrown when one of the arguments is invalid or missing.
  • InvalidModificationError DOMException
    • : Thrown when a worklet already exists with the specified name.

Examples

The following shows registering an example worklet module. This should be in a separate js file. Note that registerPaint() is called without a reference to PaintWorkletGlobalScope. The file itself is loaded through CSS.paintWorklet.addModule() (documented here on the parent class of PaintWorklet, at Worklet.addModule()).

/* 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);

The first step in using a paintworklet is defining the paint worklet using the registerPaint() function, as done above. To use it, you register it with the CSS.paintWorklet.addModule() method:

CSS.paintWorklet.addModule("checkboardWorklet.js");

You can then use the image/paint CSS function in your CSS anywhere an <image> value is valid.

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

Specifications

Browser compatibility

See also

来源:MDN Web Docs / Mozilla 贡献者 · 作者与贡献记录 · CC BY-SA 2.5。离线整理了版式、链接和媒体显示。

资料来源与适用范围

资料来源
MDN Web Docs / Mozilla 贡献者
适用范围
请按文中版本与环境说明核对
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 2.5

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。