CSS paint() Function

The paint() function allows you to use a custom CSS Paint Worklet to draw dynamic images.

It's part of the CSS Painting API (often referred to as CSS Houdini). It allows developers to write JavaScript functions that draw directly into an element's background, border, or content using a subset of the HTML5 Canvas API.

You can use the paint() function anywhere an image data type is accepted in CSS, such as the background-image or border-image properties. This gives you the power to create complex, responsive patterns and graphics that would be impossible or highly inefficient with standard CSS alone.

It is important to note that browser support for the CSS Painting API is currently limited, primarily working in Chromium-based browsers (like Chrome and Edge). You should always provide a standard CSS fallback. Here is an example of a custom checkerboard pattern generated entirely via the paint() function:

View Output Full Screen Preview

How It Works

Using the paint() function is a two-step process:

  1. Register the Worklet (JavaScript): You must write a JavaScript class with a paint() method and register it using registerPaint('workletName', class). This file is then loaded into the browser using CSS.paintWorklet.addModule('worklet.js').
  2. Call the Worklet (CSS): Once registered, you can reference the worklet in your CSS by passing its name to the paint() function, like background-image: paint(workletName);.

Passing Arguments

The CSS Painting API also allows you to pass custom arguments to your worklet directly from your CSS. For example, you could write paint(myWorklet, blue, 20px) to tell your JavaScript to draw a blue pattern that is 20 pixels wide.

Note: Passing arguments requires the browser to support the CSS Properties and Values API, which allows you to define custom CSS variables.

Official Syntax

The official syntax of the paint() function is as follows:

Possible Values

As indicated in the official syntax, the paint() function accepts the following values:

ident

The identifier (name) of the paint worklet you registered in your JavaScript file. For example, checkerboard.

declaration-value

An optional, comma-separated list of arguments to pass to the paint worklet. These can be colors, lengths, or any other valid CSS values that your JavaScript is programmed to accept.

CSS Specifications

Browser Support

The following table provided by Caniuse.com shows the level of browser support for this feature.