Paint API - paintWorklet

The paintWorklet is the hook provided by the Paint API to attach your drawing code to the Paint section of the CSS rendering engine. Whenever the browser needs to draw the image for the property hooked it refers to the paint() method of the paintWorklet.

Whenever the paintWorklet is invoked, the browser initializes a context and the size of that context to the paint method. The context is an object of the PaintRenderingContext2D class, which is a subset of the CanvasRenderingContext2D. Most drawing functions used on the Canvas can be used to draw on this context.

Structure of the paintWorklet

The paintWorklet is a class in which you define the paint() method, the method in which you will draw the image required by the paint() function in the CSS properties. Besides the class it also has call to then registerPaint() function to register this paintWorklet class. This paintWorklet can be stored in a javascript file.

Actually, the class defines 4 sections...
  1. the paint method - this is where you perform the actual drawing of the image programmatically.
  2. inputProperties - in which you can specify the list of the custom properties or variables that the worklet can access from the calling code.
  3. inputArguments - in which you specify the list of types of the arguments that you will be passing in the paint() function.
  4. contextOptions - where settings for the PaintRenderingContext2D context can be accessed.
The shape of paintWorklet class is...
class thePaintName{
     static get inputProperties() {
        return ['--propname1', '--propname2',...];
    }

     static get inputArguments() {
        return ['<typeofarg1>', '<typeofarg2>',...];
    }

     static get contextOptions() {
        return {identifier: value};
    }

    paint(ctx, geom, props, args) {
         //... your drawing code
    }
}

registerPaint('theIdentifier',thePaintName);

The simplest form of the paintWorklet would look like this...
 
class thePainter{
    paint(ctx, geom) {
         //... your drawing code
    }
}

registerPaint('myPainting',thePainter);

Using the paintWorklet

Both the class and registerPaint functions can be stored in a Javascript (.js) file. This file is then attached to the document in the <script> tag of your HTML or through a javascript file referenced in HTML file.
    CSS.paintWorklet.addModule('myPaintWorklet.js');
where myPaintWorklet.js is the name of the javascript file containing the paintWorklet. More than one class and its registration function can be stored in one javascript file.

Now, this paintWorklet is ready to be used as a function in the CSS properties.
    .classname {
        ...
        background-image: paint(myPainting);
        ...
    }

paint(myPainting) function can be used wherever a image is defined in the CSS, for eg. background-image, border-image, etc.


Let us see this in use, in our firstcode for Paint API.