Index

A viewBox for Paint API Worklets

Paint API worklets are an excellent platform for creative expression on the web. They are fast, portable, and responsive, but they can also be fiddly — especially when working with generative designs.

Why? Their inherent responsiveness can be more of a curse than a blessing! Paint API worklets re-render every time their “target” element changes size, resulting in an ever-changing drawing space. Often, this is wonderful. But, it can introduce significant complexity when working both with and without randomness.


This got me thinking — wouldn’t it be rad if we could define a viewBox attribute for our Paint API worklets, just like an SVG? We could define a fixed drawing space, say 1024x1024 units, and have it automatically scale to either cover or fit within its target element.

Something like this:

.worklet-target {
  --viewbox-width: 1024;
  --viewbox-height: 1024;
  --scale-mode: cover;
}

It turns out this is possible, requires only a few lines of code, and is a rather handy option to have when developing all kinds of worklets. I won’t dive into too much technical detail here, but here’s a CodePen demonstrating the idea:

Gradients courtesy of Open Props.

You can find the worklet code in the JS tab and the CSS implementation in the CSS tab. Try toggling the --scale-mode custom property between contain and cover and see how the pattern reacts.