Paint API
Learn custom drawing with the CSS Paint API.
registerPaint and the paint method
You register a paint worklet with registerPaint('name', class). The class's paint(ctx, geometry, properties) method does the drawing. ctx is a Canvas-like drawing context; geometry gives the box width and height, properties the read CSS variables.
The worklet declares which variables it reads through inputProperties. The browser re-invokes the worklet only when those variables change.
Reading variables with inputProperties
The worklet declares the variables it reads with static get inputProperties() { return ['--tile-color']; }. Inside paint, properties.get('--tile-color') returns a CSSStyleValue; you call .toString() to get the color.
So when you write --tile-color: #f59e0b in CSS, the worklet redraws automatically. This is where the Paint API ties the worklet to live CSS.
Exercise Write the avatar mask in CSS
Complete the CSS below. In .avatar add --avatar-radius: 12 and mask-image: paint(rounded).
Show example solution
/* avatar mask */
.avatar {
--avatar-radius: 12;
mask-image: paint(rounded);
}
Test yourself
-
What does the ctx parameter of the paint method provide?
class TilePainter { paint(ctx, geom) { /* what does ctx provide? */ } }- A Canvas-like drawing context
- A network request context
- Only a text string
- The DOM tree root
Show answer
A Canvas-like drawing context — Correct. ctx is a Canvas-like drawing context with methods such as fillRect and arc.
-
Define the variable the worklet reads
.tile { --tile-color: ____; background: paint(tile); }Show answer
.tile { --tile-color: #f59e0b; background: paint(tile); } -
Match each method and field to its role
- registerPaint
- Registers the worklet
- paint(ctx, geom, props)
- Does the drawing
- inputProperties
- Variables to read
- properties.get()
- Returns the value object