A customizable CSS Paint Worklet that renders geometric figures to the background of any element
CSS Paint Worklets are part of the CSS Paint API (also known as “CSS Custom Paint” or “Houdini’s paint worklet”) which allow us to programmatically generate an image that we can then use on any CSS property that expects an image (background-image
, border-image
, ...).
CSS Paint API article on the developers.google.com
⚠️ CSS Paint API features are experimental: Maybe you need to take a look at the CSS Paint Polyfill
ℹ️ If you want to use a CDN, skip steps 1 and 2 and instead add
<script scr="https://unpkg.com/geometric-paint-worklet"></script>
to your index.html
-
You can get the worklet js file from one of the following methods:
1.1. Copy the
dist/geomatric-paint-worklet.js
file into your project1.2. Install with npm
npm install geometric-paint-worklet
-
Import the worklet file on your index.html head:
<script src="node_modules/geometric-paint-worklet/dist/geometric-paint-worklet.js"></script>
- Add the paint worklet module to your index.html:
<script>
CSS.paintWorklet.addModule('node_modules/geometric-paint-worklet/dist/geometric-paint-worklet.js');
</script>
- Use the GeometricPaintWorklet on any Element. Ex:
.my-element {
background-image: paint(geometricPaintWorklet);
}
- Customize it to your needs using custom CSS Variables (see below)
You can customize it using css variables. Ex:
.nice-element {
--gpw-number-of-shapes: 32;
--gpw-shape-size: 16;
--gpw-line-width: 2;
--gpw-possible-colors: ['#E57373', 'pink', 'rgb(100, 150, 34)'];
--gpw-opacity: .25;
background-image: paint(geometricPaintWorklet);
}
Variable | Value Type | Default |
---|---|---|
--gpw-number-of-shapes |
number | 12 |
--gpw-shape-size |
number | 40 |
--gpw-line-width |
number | 40 |
--gpw-possible-colors |
array | ['#FFF59D', '#FFAB91', '#80DEEA', '#E57373'] |
--gpw-fill-shapes |
boolean | false |
--gpw-opacity |
number | 1 |
- Default Settings
.my-element {
background-image: paint(geometricPaintWorklet);
}
- Small shapes
.my-element {
--gpw-number-of-shapes: 80;
--gpw-shape-size: 6;
--gpw-line-width: 6;
--gpw-fill-shapes: false;
--gpw-opacity: .5;
background-image: paint(geometricPaintWorklet);
}
- Overlapping translucent forms
.my-element {
--gpw-number-of-shapes: 24;
--gpw-shape-size: 256;
--gpw-line-width: 1;
--gpw-fill-shapes: true;
--gpw-opacity: .25;
background-image: paint(geometricPaintWorklet);
}
- Large thin borders
.my-element {
--gpw-number-of-shapes: 8;
--gpw-shape-size: 240;
--gpw-line-width: 1;
--gpw-possible-colors: ['#ffffff'];
background-image: paint(geometricPaintWorklet);
}
- Solid colourful shapes
.my-element {
--gpw-number-of-shapes: 12;
--gpw-shape-size: 40;
--gpw-line-width: 40;
background-image: paint(geometricPaintWorklet);
}
😀 Have fun with it, and let me know if you use it somewhere...