Rotate(); does not work in double for loop in createGraphics canvas

hi!

I’m a trying to make a poster generator inside P5.js. I’m quite new to programming and for every new step I watch tutorials so I know what to do. Right now I am facing a problem with rotating my ellipses. At the moment the ellipses are not rotating but I also do not get an error. The specific part of code is in the function pattern() part.

I think it has something to do with createGraphics(). If I use poster.rotate(45) (like I do with drawing the ellipses, poster.ellipse()) the ellipses are going crazy and moving all over the place.

I hope you can help me to rotate the ellipses :slight_smile: If you need more information, please tell me!
(English is not my native language, so I’m sorry if it’s not all clear)


function setup() {  
  createCanvas(windowWidth, windowHeight);
  poster = createGraphics(500,700);
}

function draw() {
  angleMode(DEGREES);
  ellipseMode(CENTER);
  drawPoster();
  image(poster,0,0);
}

function drawPoster(){ 
  poster.background(0);
  poster.fill(0);
  pattern(); 
}

function pattern(){
  push();
  translate(0,0);

  for (let x=25; x<=425; x=x+200) {
    for (let y=25; y<=650; y=y+200) { 
      poster.fill(255);

      push();
      translate (x,y);
      rotate(45);
      poster.ellipse(x+25,y+12.5,50,25);
      pop();
      
    }
  }
  pop();
}

You need everywhere apply the transformations etc to the poster as it is instead applied to the main graphics context …

Cheers
— mnse

Hello @Annemiek.

Example without createGraphics():

function setup() {  
  createCanvas(windowWidth, windowHeight);
}

function draw() {
  angleMode(DEGREES);
  ellipseMode(CENTER);
  drawPoster();
  image(poster,0,0);
}

function drawPoster(){ 
  background(0);
  fill(0);
  pattern(); 
}

function pattern(){
  let count = 0;
  for (let x=25; x<=425; x=x+200) {
    for (let y=25; y<=650; y=y+200) { 
      fill(255);
     push();
      translate (x, y);
      //rotate(45);        // Try this
      rotate(count*30);    // Or this
      count++;
      ellipse(0, 0, 50, 25); // You are translating so do not use x, y here !
     pop();
      text(count, x, y+50);  // Not translated or rotated!
    }
  }
}

Once that is working you can use createGraphics() and add poster. prefix where it is needed.

Note what happens with count++ and poster.count++

print() statements are useful during development.

Output with some modifications to loop increments and offsets:

:)

thank you! I had tried to put poster. in front of everything before, but made a mistake in the first translate part. I made the circles appear in the middle of the screen, but when I used poster.translate() it dissapeared out of the screen, which made me think it was not working. But I deleted that part and with the tips of glv it is now working :slight_smile:

1 Like