CSS Houdini Collection

CSS Paint API: Part 1 Intro

The CSS Paint API is designed to be used wherever you would invoke an image in CSS — backgrounds, borders, masks etc.

Here's a really simple example - let's say you want to create a cool half-highlight background, like on this header:

My Cool Header

The main setup & design will happen in an external script, a worklet, which we'll discuss in a minute. We first need to register that worklet from our main script:

// in our main script
await CSS.paintWorklet.addModule('header-highlight.js');

Now we'll create that header-highlight.js worklet; inside it we use the registerPaint() function to name our CSS Paint worklet, and also pass in a class that does all the magic:

registerPaint('headerHighlight', class {

	// Whether Alpha is allowed -> This is set to true by default, if it is set to false all colours used on the canvas will have full opacity, or alpha of 1.0
	static get contextOptions() { return {alpha: true}; }

	paint(ctx) {
	  // ctx - drawing context

	ctx.fillStyle = 'hsla(55, 90%, 60%, 1.0)';
	ctx.fillRect(0, 15, 200, 20);

	}
});

Now we have created a new paint worklet, and given it a name headerHighlight. We can now use that in our CSS, along with the paint() function, where we would normally call an image.

.example {
	background-image: paint(headerHighlight);
}

Our paint function takes one argument (we'll look at more in due course): ctx. This is the 2D Rendering Context, which is a subset of the HTML5 Canvas API. It contains pretty much all the features apart from "...CanvasImageData, CanvasUserInterface, CanvasText, or CanvasTextDrawingStyles APIs..." (taken from spec https://drafts.css-houdini.org/css-paint-api-1/#2d-rendering-context). So in short we can use it to draw whatever we like as our background image.

The above example just simple draws a filled rectangle, you can do a lot more than that (check out the Canvas API docs).

Let's take a look at some of the other data available to the paint() function. Go to Part Two