Ayush Nandi
Ayush Nandi

Reputation: 31

How to prevent draw() from resetting transformations in p5.js

Is there any way by which I can prevent draw() from resetting all transformations every time it resets? I am trying to simulate the growth of an L-system and want to achieve something like this: Barnsley Fern

In order to achieve this I need to keep track of all the transformations and rotations within the draw function in order to show the growth effect. Using a user-defined function instead of draw just draws the final tree and does not show the tree being "drawn"

So my question is basically this: Is there any way I can prevent draw() from resetting all transformations? or Any way I can keep track of the x, y coordinates and angle of the canvas so that every time draw resets, I can translate back to the previous state using the stored coordinates.

Upvotes: 3

Views: 640

Answers (1)

Chen Ni
Chen Ni

Reputation: 1144

Try using push() and pop():

function setup() {
  createCanvas(400, 400);
  
  //some initializations

  push(); //save an initial drawing state
}

function draw() {
  pop(); //restore latest saved drawing state (including transformations)

  // do some stuff

  push(); //save current drawing state (including transformations)
}

Upvotes: 3

Related Questions