JavaScript tutorial: Using repeatable randomness with P5.js

With repeatable randomness, we can take advantage of happy accidents when generating art—and preserve the results

In the last few weeks, we’ve introduced P5.js and used it to generate a textured paper background and a relatively underwhelming (but fun!) representation of watercolor. In this post, we’ll discuss repeatable randomness and why you may want to use it (hint: repeatability!). Then we’ll dive in and update our code to draw on repeatable randomness to help us isolate and preserve the best visual effects we generate.

With the code we've written so far, our watercolor image changes, sometimes dramatically, every time the browser evaluates our JavaScript. This was by design. We used computer-generated randomness as a tool to create a variety of visual effects and further our artistic endeavor. These results are not all equally pleasing from a visual standpoint, though, and some may get us closer to the art we imagined than others.

Let’s refresh our browser, watching combinations of randomness that will likely never be produced again go by, until we generate an image that we find very appealing. Something about the positions and colors of our watercolor spots feels right, but perhaps we’d like to make those spots smaller and more opaque. If we change the values of the constants that define the range of the size of the spots or their opacity, however, we’ll have to refresh the page—and we’ll lose that perfect position and size combination.

Ideally, we’d be able to flip through our random results and, when we see something we really like, freeze all of those random values. Then we could modify other elements of the image to see how they’d turn out given our frozen set of random values. The way we’ll accomplish this is by using a seeded random number generator.

To continue reading this article register now