Oh yeah, the CSS Paint API will be enabled by default in Chrome 65:
CSS Paint API allows you to programmatically generate an image whenever a CSS property expects an image. Properties like
background-image
orborder-image
are usually used withurl()
to load an image file or with CSS built-in functions likelinear-gradient()
. Instead of using those, you can now usepaint(myPainter)
to reference a paint worklet.
Inside a paint worklet a CanvasRenderingContext2D
has been made available for you to use. Use it like you would draw on a regular <canvas>
element. Next to the CanvasRenderingContext2D
you can also access the geometry of the element (e.g. get width
and height
), and can access other CSS properties (including CSS Variables).
There’s a nice demo included which showcases the rendering of a checkerboard pattern, which can be customised via two CSS Variables:
Here’s code for the painter demoed in the video above:
// checkerboard.js
class CheckerboardPainter {
// inputProperties returns a list of CSS properties that this paint function gets access to
static get inputProperties() { return ['--checkerboard-spacing', '--checkerboard-size']; }
paint(ctx, geom, properties) {
// Paint worklet uses CSS Typed OM to model the input values.
// As of now, they are mostly wrappers around strings,
// but will be augmented to hold more accessible data over time.
const size = parseInt(properties.get('--checkerboard-size').toString());
const spacing = parseInt(properties.get('--checkerboard-spacing').toString());
const colors = ['red', 'green', 'blue'];
for(let y = 0; y < geom.height/size; y++) {
for(let x = 0; x < geom.width/size; x++) {
ctx.fillStyle = colors[(x + y) % colors.length];
ctx.beginPath();
ctx.rect(x*(size + spacing), y*(size + spacing), size, size);
ctx.fill();
}
}
}
}
registerPaint('checkerboard', CheckerboardPainter);
New possibilities in Chrome 65: CSS Paint API →
💁♂️ Want to know more about Houdini? Check out Sam Richard’s talk “Magic Tricks with CSS Houdini” (video)
Leave a comment