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.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)

Published by Bramus!

Bramus is a frontend web developer from Belgium, working as a Chrome Developer Relations Engineer at Google. From the moment he discovered view-source at the age of 14 (way back in 1997), he fell in love with the web and has been tinkering with it ever since (more …)

Join the Conversation

1 Comment

Leave a comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.