CSS Paint API (Houdini’s Paint Worklet) available in Chrome 65!

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 or border-image are usually used with url() to load an image file or with CSS built-in functions like linear-gradient(). Instead of using those, you can now use paint(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.rect(x*(size + spacing), y*(size + spacing), size, size);

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)

Elsewhere , , ,

Leave a Reply

Your email address will not be published. Required fields are marked *