Randomness in generative art (Beginner)
written by Jonathan Barbea...
Excited to share a quick tip on using the random() function in p5.js while exploring the classic computer program 10 PRINT. This program uses only two characters to create complex and mesmerizing patterns on the screen. Here's an example of how you can use the random() function and a simple if-else statement to replicate the 10 PRINT program in p5.js
function setup() {
createCanvas(1280, 720); // create a 1280x720 canvas
colorMode(HSB, 360, 100, 100, 100); // use HSB with scale of 0-360, 0-100, 0-100
background(0, 5, 10); // use HSB to set the background to black
let spacing = 10;
strokeWeight(1);
stroke(0, 0, 100, 100);
for (let x = 0; x < width; x += spacing) {
for (let y = 0; y < height; y += spacing) {
if (random(1) < 0.5) {
line(x, y, x + spacing, y + spacing);
} else {
line(x, y + spacing, x + spacing, y);
}
}
}
}
In this example, random(1) generates a random number between 0 and 1, then we use an if-else statement to check if it's less than 0.5, If so, it will draw a diagonal line going up to the right, if not, it will draw a diagonal line going up to the left.
This program is a great example of how simple code can produce complex and beautiful patterns. If you're looking to explore the world of generative art and the power of randomness in code, 10 PRINT is a great place to start.
Here is a demo on codepen: