Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.


deutsche Version

ItThings can get even more complex as it's possible to nest loops inside other loops. Hier is an example with a built-in Screen Shot-function

Code Block
voidfunction setup()
{
  sizecreateCanvas(600,600);      
  strokeWeight(1);    
}
  
voidfunction draw()
{
  background(255);    // def. background colour  
 
  for(intlet x = 0; x <= width; x+=30)   // draw a smiley every 30 pixels in the width
  {
    for(intlet y = 0; y <= height; y+=30) // draw smileys every 30 pixels in the height
    {
        smiley(x,y);        
    }
  }
  
}
  
voidfunction keyPressed()
{
  if(key == 's') {
    save("screenShot.jpg");
    printlnprint("save the screen to screenShot.jpg");
  }
}
  
//
function void smiley(int x, int 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>


Code Block
importvar processing.pdf.*;

 function void setup() {
    sizecreateCanvas(600,600,PDF,"ornament.pdf" 200, P2D);
	strokeWeight(1);     // def. output resolution
  strokeWeight(1line thickness 
    pdf = createPDF();
   // line thickness  pdf.beginRecord();
}

 
voidfunction draw()
{
  background(255);    // def. background colour 
 
  for(intlet x = 0; x <= width; x+=30)   // draw a smiley every 30 pixels in the width
  {
    for(intlet y = 0; y <= height; y+=30) // draw smileys every 30 pixels in the height
    {
        smiley(x,y);        
    //}
funtion call }
  
}
  
function keyPressed()
{
  }
if(key == 's') {
    exitpdf.save();
  }
}
  
//
function void smiley(int x, int y)
{
  println("smiley");
  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

Example Solution to Exercise 7 


Code Block
languagejs
linenumberstrue
collapsetrue
intlet Ww = 60;
void
function setup() {
  sizecreateCanvas(660,660);
  noStroke();
  colorMode(HSB);
}

voidfunction draw() {
  background(255);
  for  (intlet i =1; i<=10; i++) {
    for  (intlet j =1; j<=10; j++) {
      floatlet hue = j* i*2.5 3;
      fill(hue, 150, 255);
      myShape(i*Ww, j*Ww); 
    }
  }
}

voidfunction myShape(int x, int y) {
  int D = W/3;
  //ellipse(x, y, W, W);
  triangle(x, y-D, x-D, y+D, x+D, y+Dw, w);
}