xxxxxxxxxx
87
/*
nested for loop example
4/1/2024
*/
function setup() {
createCanvas(700, 400);
var b = createButton("Generate pattern");
b.mousePressed(pattern);
pattern();
textFont('Verdana');
textStyle (BOLD)
fill('black')
textSize(40)
text ("I love MMP",10, 100)
}
function pattern() {
background(220);
var cols = 24;
var rows = 12;
// size of each cell
var w = width / cols;
var h = height / rows;
noStroke();
// nested for loop
for (var x = 0; x <= width; x += 50) {
for (var y = 0; y <= width; y += 50) {
// color
{
var r = map(y, 0, height, 0,255);
var g = random(100, 255);
var b = random(0, 25);
}
//face
fill(r, g, b);
ellipse(x, y, 50); // head
fill(5);
ellipse(x + 10, y - 10, 10); // left eye
ellipse(x - 15, y - 10, 10); // left eye
rect(x - 10, y + 10, 20, 5, 2);
}
}
// using transformation
for (var x = 0; x <= width; x += 50) {
for (var y = 0; y <= width; y += 50) {
var xo = random(-w / 4, w / 4);
var yo = random(-h / 2, h / 2);
var wo = random(0, w / 2);
var ho = random(0, h / 2);
fill(r,g,b)
rect(x + xo, y + yo, w + wo, h + ho);
}
}
}