Things can get even more complex as it's possible to nest loops inside other loops.
function setup() { createCanvas(600,600); strokeWeight(1); } function draw() { background(255); for(let x = 0; x <= width; x+=30) // draw a smiley every 30 pixels in the width { for(let y = 0; y <= height; y+=30) // draw smileys every 30 pixels in the height { smiley(x,y); } } } function keyPressed() { if(key == 's') { save("screenShot.jpg"); print("save the screen to screenShot.jpg"); } } function smiley(x, y) { noFill(); ellipse(x, y, 18, 18); // head fill(0); ellipse(x - 3,y - 3,2,5); // left eye ellipse(x + 3,y - 3,2,5); // right eye noFill(); arc(x,y,10,10,radians(20),radians(180-20)); // mouth }
This example doesn't have a screen output, it generates a PDF-File instead. For that you will need to import a script in index.html which allows us to export a pdf file. https://github.com/zenozeng/p5.js-pdf
In html:
<script src="p5-pdf.js"></script>
var pdf; function setup() { createCanvas(600, 200, P2D); strokeWeight(1); // line thickness pdf = createPDF(); pdf.beginRecord(); } function draw() { background(255); for(let x = 0; x <= width; x+=30) // draw a smiley every 30 pixels in the width { for(let y = 0; y <= height; y+=30) // draw smileys every 30 pixels in the height { smiley(x,y); } } } function keyPressed() { if(key == 's') { pdf.save(); } } function smiley(x, y) { noFill(); ellipse(x, y, 18, 18); // head fill(0); ellipse(x - 3,y - 3,2,5); // left eye ellipse(x + 3,y - 3,2,5); // right eye noFill(); arc(x,y,10,10,radians(20),radians(180-20)); // mouth }
Exercise 7
- Create a new shape instead of the smiley, and put exactly 100 repetitions on the screen
- Modify the colour and/or the shape with each repetition