Creating random-but-stable effects with the CSS Paint API

One of the side-effects when drawing things with a Houdini Paint Worklet and relying on Math.random() in your code, is that your layout might be jumpy.

Check out my CSS Houdini Paint Worklet that draws colorful circles for example: whenever you resize the available space or change one of its properties — or some of the other CSS properties — the circles are being drawn, at random places with random colors.

Sometimes this side-effect is unwanted: say you have a Paint Worklet that draws some random lines underneath an element. If you were to animate the --line-width on hover you don’t want it to draw different lines, but you want to keep the same lines in place, and only adjust their width.

To solve around this, Jake Archibald shows us how to implement mulberry32, which has consistent output no matter how many times you call it:

Computers can’t really do random. Instead, they take some state, and do some hot maths all over it to create a number. Then, they modify that state so the next number seems unrelated to the previous ones. But the truth is they’re 100% related.

If you start with the same initial state, you’ll get the same sequence of random numbers. That’s what we want – something that looks random, but it’s 100% reproducible.

Go check out the demos Jake has built. As per usual these are top-notch, and help explain everything well.

CSS paint API: Being predictably random →