Electric Dreams

Dialogues with the Machine

Language reference & template

Use the page linked below as a short guide to basics of drawing shapes with p5.js. It might be handy to keep this reference open while we work through the examples.

Interactive guide to p5.js

For making the sketches, you can start by cloning the template below. We have a little bit of setup already done to save sketches to SVG. Click the sketch on the right at any time to save it as an SVG. Also, remember to login in to save your changes!

Template with p5.js + p5-svg.js

Randomness as offsets

One common pattern for using randomness in a generative sketch is to apply it as an offset on parameters of a shape, such as its position or dimensions. By controlling where these offsets are applied or by layering multiple offsets we can create quite complex patterns.

In p5.js, you can call the random function with a minimum and maximum bounds, like so: random(-min, max). This returns a random value between those two values (excluding the ends).

Vera Molnár – Untitled (Squares), 1974

The same basic pattern can be applied in different forms to generate interesting visual variations. Here's a few ideas for you to try out:

Set equal offsets on the center x and y coordinates of the rectangle.
Instead of offsetting the center, try offsetting the rectangle's width and height.
Use other shapes such as circles.

Georg Nees – Cubic Disarray, 1968

Here's a couple of starting points for variations you can explore.

Increase the translation and rotation offsets along the x axis.
Or outwards from the center.
Use scale as another transform.

Randomness as chance

The next pattern we'll see in generative sketches is to use randomness as a kind of probability or chance — much like flipping a coin to decide. Instead of deterministically drawing a shape every time, you can knock off a piece some arbitrary percentage of time depending on these proverbial coin flips.

Translating to p5.js, the best way to use this pattern is to call the random function without any parameters. The default behaviour is to return a value between 0 and 1. When used inside an if condition like random() < 0.5, you can effectively draw something 50% or half of the time.

Vera Molnár – Des Ordres (Grid), 1974

Sol LeWitt – Cubes

Randomness as choice

The final pattern we'll look at treats randomness as a choice between drawing different shapes. In p5.js, you can translate this either as an if-else statement that uses random() < chance pattern. Each branch draws a different shape depending on the value of chance. We'll see in this in the 10PRNT example. Otherwise, you can also pass an array of functions like random([drawA, drawB, ...]) to random to pick a shape to draw. We'll see this in following tiling Waves example.

10PRNT();

C S Smith – Tiling (Waves)