W3cubDocs

/Web APIs

PaintWorkletGlobalScope: registerPaint() method

Experimental: This is an experimental technology
Check the Browser compatibility table carefully before using this in production.

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

Syntax

js

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 the 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().

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

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:

html

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

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

css

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

Specifications

Browser compatibility

Desktop Mobile
Chrome Edge Firefox Internet Explorer Opera Safari WebView Android Chrome Android Firefox for Android Opera Android Safari on IOS Samsung Internet
registerPaint 65 79 No No 52 No 65 65 No 47 No 9.0

See also

© 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/PaintWorkletGlobalScope/registerPaint